How do I write better code, Python

I started learning Python these last weeks and I’m concerned about writing better code or skipping through some lines and I have some questions.

I will be posting some of the exercises I have done.

Thanks a lot.

By the way, should I will be thinking like this?

"If it works, I’m done."

My mind tends to overanalyze things, “Add this condition, add this as well”

These are simple exercises but overanalyzing sometimes is torture.

Exercise 1:

# Write a program that reads the words in words.txt
# and stores them as keys in a dictionary.
# It doesn't matter what the values are.
# Then you can use the in operator as a fast way
# to check whether a string is in the dictionary.

text_file = "words.txt"
th = open(text_file)
word_dict = dict()

for line in th:
    line = line.rstrip()
    print("Line: ", line)
    words = line.split(",")
    print(words)
    for word in words:
        print(word)
        atpos = word.find(":")
        first_part = word[0:atpos]
        second_part = word[atpos+1:]
        if first_part == "" or second_part == "":
                continue
        print(first_part)
        print(second_part)
        # word_dict[first_part] = second_part
        if first_part in word_dict:
                continue
        word_dict.update({first_part : second_part})
print(word_dict)

Exercise 2 (similar):

# Open the file romeo.txt and read it line by line.
# For each line, split the line into a list of words using the split() method.
# The program should build a list of words.
# For each word on each line check to see if the word is already in the list and if not append it to the list.
# When the program completes, sort and print the resulting words in alphabetical order.

fname = "romeo.txt"
fh = open(fname)
lst = list()
for line in fh:
    line = line.rstrip()
    print("Line: ", line)
    words = line.split(" ")
    print("Words: ", words)
    words.sort()
    print("Sorted words: ", words)
    for word in words:
        if word in lst:
            continue
        lst.append(word)
    print("List: ", lst)
lst.sort()
print(lst)

Exercise 3:

# Write a program that prompts for a file name,
# then opens that file and reads through the file,
# looking for lines of the form:
# X-DSPAM-Confidence: 0.8475

# Count these lines and extract the floating point values
# from each of the lines and compute the average of those
# values and produce an output as shown below.
# Do not use the sum() function or a variable named sum in your solution.
fname = input("Enter file name: ")
try:
    fh = open(fname)
except:
    print("File cannot be opened: ", fname)
    quit()

count = 0
total = 0
line_number = 0
for line in fh:
    line_number += 1
    line = line.rstrip()
    if not line.startswith("X-DSPAM-Confidence:") :
        continue
    atpos = line.find(":")
    try:
        number = float(line[atpos+1:])
    except:
        print(" Line doesn't have a float number, continuing \n Line Number: ", line_number)
        continue
    total = number + total
    count = count + 1
print("Average spam confidence:", total/count)
print("Done")

sample file.txt

From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
Return-Path: <postmaster@collab.sakaiproject.org>
Received: from murder (mail.umich.edu [141.211.14.90])
	 by frankenstein.mail.umich.edu (Cyrus v2.3.8) with LMTPA;
	 Sat, 05 Jan 2008 09:14:16 -0500
X-Sieve: CMU Sieve 2.3
Received: from murder ([unix socket])
	 by mail.umich.edu (Cyrus v2.2.12) with LMTPA;
	 Sat, 05 Jan 2008 09:14:16 -0500
Received: from holes.mr.itd.umich.edu (holes.mr.itd.umich.edu [141.211.14.79])
	by flawless.mail.umich.edu () with ESMTP id m05EEFR1013674;
	Sat, 5 Jan 2008 09:14:15 -0500
Received: FROM paploo.uhi.ac.uk (app1.prod.collab.uhi.ac.uk [194.35.219.184])
	BY holes.mr.itd.umich.edu ID 477F90B0.2DB2F.12494 ;
	 5 Jan 2008 09:14:10 -0500
Received: from paploo.uhi.ac.uk (localhost [127.0.0.1])
	by paploo.uhi.ac.uk (Postfix) with ESMTP id 5F919BC2F2;
	Sat, 5 Jan 2008 14:10:05 +0000 (GMT)
Message-ID: <200801051412.m05ECIaH010327@nakamura.uits.iupui.edu>
Mime-Version: 1.0
Content-Transfer-Encoding: 7bit
Received: from prod.collab.uhi.ac.uk ([194.35.219.182])
          by paploo.uhi.ac.uk (JAMES SMTP Server 2.1.3) with SMTP ID 899
          for <source@collab.sakaiproject.org>;
          Sat, 5 Jan 2008 14:09:50 +0000 (GMT)
Received: from nakamura.uits.iupui.edu (nakamura.uits.iupui.edu [134.68.220.122])
	by shmi.uhi.ac.uk (Postfix) with ESMTP id A215243002
	for <source@collab.sakaiproject.org>; Sat, 5 Jan 2008 14:13:33 +0000 (GMT)
Received: from nakamura.uits.iupui.edu (localhost [127.0.0.1])
	by nakamura.uits.iupui.edu (8.12.11.20060308/8.12.11) with ESMTP id m05ECJVp010329
	for <source@collab.sakaiproject.org>; Sat, 5 Jan 2008 09:12:19 -0500
Received: (from apache@localhost)
	by nakamura.uits.iupui.edu (8.12.11.20060308/8.12.11/Submit) id m05ECIaH010327
	for source@collab.sakaiproject.org; Sat, 5 Jan 2008 09:12:18 -0500
Date: Sat, 5 Jan 2008 09:12:18 -0500
X-Authentication-Warning: nakamura.uits.iupui.edu: apache set sender to stephen.marquard@uct.ac.za using -f
To: source@collab.sakaiproject.org
From: stephen.marquard@uct.ac.za
From: f
Subject: [sakai] svn commit: r39772 - content/branches/sakai_2-5-x/content-impl/impl/src/java/org/sakaiproject/content/impl
X-Content-Type-Outer-Envelope: text/plain; charset=UTF-8
X-Content-Type-Message-Body: text/plain; charset=UTF-8
Content-Type: text/plain; charset=UTF-8
X-DSPAM-Result: Innocent
X-DSPAM-Processed: Sat Jan 5 09:14:16 2008
X-DSPAM-Confidence: 0.8475
X-DSPAM-Probability: 0.0000

Details: http://source.sakaiproject.org/viewsvn/?view=rev&rev=39772

Author: stephen.marquard@uct.ac.za
Message-ID: <200801041515.m04FFv42007050@nakamura.uits.iupui.edu>
Mime-Version: 1.0
Content-Transfer-Encoding: 7bit
Received: from prod.collab.uhi.ac.uk ([194.35.219.182])
          by paploo.uhi.ac.uk (JAMES SMTP Server 2.1.3) with SMTP ID 25
          for <source@collab.sakaiproject.org>;
          Fri, 4 Jan 2008 15:17:11 +0000 (GMT)
Received: from nakamura.uits.iupui.edu (nakamura.uits.iupui.edu [134.68.220.122])
	by shmi.uhi.ac.uk (Postfix) with ESMTP id 5B396236B9
	for <source@collab.sakaiproject.org>; Fri, 4 Jan 2008 15:17:08 +0000 (GMT)
Received: from nakamura.uits.iupui.edu (localhost [127.0.0.1])
	by nakamura.uits.iupui.edu (8.12.11.20060308/8.12.11) with ESMTP id m04FFv85007052
	for <source@collab.sakaiproject.org>; Fri, 4 Jan 2008 10:15:57 -0500
Received: (from apache@localhost)
	by nakamura.uits.iupui.edu (8.12.11.20060308/8.12.11/Submit) id m04FFv42007050
	for source@collab.sakaiproject.org; Fri, 4 Jan 2008 10:15:57 -0500
Date: Fri, 4 Jan 2008 10:15:57 -0500
X-Authentication-Warning: nakamura.uits.iupui.edu: apache set sender to zqian@umich.edu using -f
To: source@collab.sakaiproject.org
From: zqian@umich.edu
Subject: [sakai] svn commit: r39757 - in assignment/trunk: assignment-impl/impl/src/java/org/sakaiproject/assignment/impl assignment-tool/tool/src/webapp/vm/assignment
X-Content-Type-Outer-Envelope: text/plain; charset=UTF-8
X-Content-Type-Message-Body: text/plain; charset=UTF-8
Content-Type: text/plain; charset=UTF-8
X-DSPAM-Result: Innocent
X-DSPAM-Processed: Fri Jan 4 10:17:42 2008
X-DSPAM-Confidence: 0.7605
X-DSPAM-Probability: 0.0000

Details: http://source.sakaiproject.org/viewsvn/?view=rev&rev=39757

Author: zqian@umich.edu
Date: 2008-01-04 10:15:54 -0500 (Fri, 04 Jan 2008)
New Revision: 39757

Modified:
assignment/trunk/assignment-impl/impl/src/java/org/sakaiproject/assignment/impl/BaseAssignmentService.java
assignment/trunk/assignment-tool/tool/src/webapp/vm/assignment/chef_assignments_instructor_list_submissions.vm
Log:
fix to SAK-12604:Don't show groups/sections filter if the site doesn't have any

----------------------
This automatic notification message was sent by Sakai Collab (https://collab.sakaiproject.org/portal) from the Source site.
You can modify how you receive notifications at My Workspace > Preferences.



From antranig@caret.cam.ac.uk Fri Jan 4 10:04:14 2008
Return-Path: <postmaster@collab.sakaiproject.org>
Received: from murder (mail.umich.edu [141.211.14.25])
	 by frankenstein.mail.umich.edu (Cyrus v2.3.8) with LMTPA;
	 Fri, 04 Jan 2008 10:04:14 -0500
X-Sieve: CMU Sieve 2.3
Received: from murder ([unix socket])
	 by mail.umich.edu (Cyrus v2.2.12) with LMTPA;
	 Fri, 04 Jan 2008 10:04:14 -0500
Received: from holes.mr.itd.umich.edu (holes.mr.itd.umich.edu [141.211.14.79])
	by panther.mail.umich.edu () with ESMTP id m04F4Dci015108;
	Fri, 4 Jan 2008 10:04:13 -0500
Received: FROM paploo.uhi.ac.uk (app1.prod.collab.uhi.ac.uk [194.35.219.184])
	BY holes.mr.itd.umich.edu ID 477E4AE3.D7AF.31669 ;
	 4 Jan 2008 10:04:05 -0500
Received: from paploo.uhi.ac.uk (localhost [127.0.0.1])
	by paploo.uhi.ac.uk (Postfix) with ESMTP id 933E3BAC17;
	Fri, 4 Jan 2008 15:04:00 +0000 (GMT)
Message-ID: <200801041502.m04F21Jo007031@nakamura.uits.iupui.edu>
Mime-Version: 1.0
Content-Transfer-Encoding: 7bit
Received: from prod.collab.uhi.ac.uk ([194.35.219.182])
          by paploo.uhi.ac.uk (JAMES SMTP Server 2.1.3) with SMTP ID 32
          for <source@collab.sakaiproject.org>;
          Fri, 4 Jan 2008 15:03:15 +0000 (GMT)
Received: from nakamura.uits.iupui.edu (nakamura.uits.iupui.edu [134.68.220.122])
	by shmi.uhi.ac.uk (Postfix) with ESMTP id AC2F6236B9
	for <source@collab.sakaiproject.org>; Fri, 4 Jan 2008 15:03:12 +0000 (GMT)
Received: from nakamura.uits.iupui.edu (localhost [127.0.0.1])
	by nakamura.uits.iupui.edu (8.12.11.20060308/8.12.11) with ESMTP id m04F21hn007033
	for <source@collab.sakaiproject.org>; Fri, 4 Jan 2008 10:02:01 -0500
Received: (from apache@localhost)
	by nakamura.uits.iupui.edu (8.12.11.20060308/8.12.11/Submit) id m04F21Jo007031
	for source@collab.sakaiproject.org; Fri, 4 Jan 2008 10:02:01 -0500
Date: Fri, 4 Jan 2008 10:02:01 -0500
X-Authentication-Warning: nakamura.uits.iupui.edu: apache set sender to antranig@caret.cam.ac.uk using -f
To: source@collab.sakaiproject.org
From: antranig@caret.cam.ac.uk
Subject: [sakai] svn commit: r39756 - in component/branches/SAK-12166/component-api/component/src/java/org/sakaiproject/component: impl impl/spring/support impl/spring/support/dynamic impl/support util
X-Content-Type-Outer-Envelope: text/plain; charset=UTF-8
X-Content-Type-Message-Body: text/plain; charset=UTF-8
Content-Type: text/plain; charset=UTF-8
X-DSPAM-Result: Innocent
X-DSPAM-Processed: Fri Jan 4 10:04:14 2008
X-DSPAM-Confidence: 0.6932
X-DSPAM-Probability: 0.0000

Details: http://source.sakaiproject.org/viewsvn/?view=rev&rev=39756
1 Like

Dude what actually u looking for ? Can u explain ? U need better code python ? Lol

Yes, at this level of exercise, “if it works, I’m done” is fine!  

Writing “better code” becomes much more important when working on larger projects or with other people. “Other people” can include yourself, 6 months later: if you can’t figure out what your own code is doing after a span of time, then you need to do a better job.

The best way to learn “good” programming style or technique is to read other people’s code. Whether that is from a blog, books, open-source here on Github, or courses, you can see how others have written code: if you have trouble following their code or it feels messy or has problems, then don’t write like that!

If you have any specific questions or concerns, please elaborate and we can discuss.

1 Like