
Breif note and answers to a Python beginning lesson by Charles Severance.
Preface
I had a required Course of Python in my sophomore year but it’s pretty straightforward or shallow, even when it comes to so-called machine learning. We did the homework almost by copying the codes or algorithm from the Internet, and had little understanding of the principle about how it runs, and finally got a very average score. In fact, I’m quite interested in programing and there’s a chance to use it in my graduation project, which means it’s important to learn Python in depth.
There is a course called Python for Everybody which is highly recommended by many people to be the first step of programming. That’s why I picked this course to learn Python once again, and also could practice my English no matter the skill of listening, reading or pronunciations, it’s all good for them. The course provides a free e-book with a lot of exercises per chapter, so I make this note to write my answers.
Chapter 1 : Why Program

CPU
The Central Processing Unit (or CPU) is the part of the computer that is built to be obsessed with “what is next?” If your computer is rated at 3.0 Gigahertz, it means that the CPU will ask “What next?” three billion times per second. You are going to have to learn how to talk fast to keep up with the CPU.
The Main Memory is used to store information that the CPU needs in a hurry. The main memory is nearly as fast as the CPU. But the information stored in the main memory vanishes when the computer is turned off.
The Secondary Memory
The Secondary Memory is also used to store information, but it is much slower than the main memory. The advantage of the secondary memory is that it can store information even when there is no power to the computer. Examples of secondary memory are disk drives or flash memory (typically found in USB sticks and portable music players).
Input and Output Devices
The Input and Output Devices are simply our screen, keyboard, mouse, microphone, speaker, touchpad, etc. They are all of the ways we interact with the computer.
Network Connection
These days, most computers also have a Network Connection to retrieve information over a network. We can think of the network as a very slow place to store and retrieve data that might not always be “up”. So in a sense, the network is a slower and at times unreliable form of Secondary Memory.
Reserved word
Python reserves 33 keywords:
and, del, from, None, True, as, elif, global, nonlocal, try, assert, else, if, not, while, break, except, import, or, with, class, False, in, pass, yield, continue, finally, is, raise, def, for, lambda, return.
Chapter 2 : Variables, expressions, and statements
Exercise 2.2
Write a program that uses input to prompt a user for their name and then welcomes them.
1 | Enter your name: Chuck |
1 | name = input('Enter your name: ') |
Exercise 2.3
Write a program to prompt the user for hours and rate per hour to compute gross pay.
1 | Enter Hours: 35 |
1 | hrs = input('Enter Hours: ') |
Exercise 2.4
Assume that we execute the following assignment statements:
1 | width = 17 |
For each of the following expressions, write the value of the expression and the type (of the value of the expression).
1 | 1. width//2 |
Use the Python interpreter to check your answers.
1 | 8 |
Exercise 2.5
Write a program which prompts the user for a Celsius temperature, convert the temperature to Fahrenheit, and print out the converted temperature.
1 | Celsius = input('Enter Celsius temperature: ') |
Chapter 3 : Conditional execution
Exercise 3.1
Rewrite your pay computation to give the employee 1.5 times the hourly rate for hours worked above 40 hours.
1 | Enter Hours: 45 |
1 | hrs = input('Enter Hours: ') |
Exercise 3.2
Rewrite your pay program using try and except so that your program handles non-numeric input gracefully by printing a message and exiting the program. The following shows two executions of the program:
1 | Enter Hours: 20 |
1 | hrs = input('Enter Hours: ') |
Exercise 3.3
Write a program to prompt for a score between 0.0 and 1.0. If the score is out of range, print an error message. If the score is between 0.0 and 1.0, print a grade using the following table:
1 | Score Grade |
Run the program repeatedly as shown above to test the various different values for input.
1 | score = input("Enter Score: ") |
Chapter 4 : Functions
Exercise 4.1
Run the program on your system and see what numbers you get. Run the program more than once and see what numbers you get.
1 | import random |
Exercise 4.6
Rewrite your pay computation with time-and-a-half for overtime and create a function called computepay which takes two parameters(hours and rate).
1 | Enter Hours: 45 |
1 | def computepay(): |
Exercise 4.7
Rewrite the grade program from the previous chapter using a function called computegrade that takes a score as its parameter and returns a grade as a string.
1 | Score Grade |
Run the program repeatedly to test the various different values for input.
1 | def computegrade(): |
Chapter 5 : Iteration
Exercise 5.1
Write a program which repeatedly reads numbers until the user enters “done”. Once “done” is entered, print out the total, count, and average of the numbers. If the user enters anything other than a number, detect their mistake using try and except and print an error message and skip to the next number.
1 | Enter a number: 4 |
1 | num = 0 |
Exercise 5.2
Write another program that prompts for a list of numbers as above and at the end prints out both the maximum and minimum of the numbers instead of the average.
1 | largest = None |
Chapter 6 : Strings
Exercise 6.5
Take the following Python code that stores a string: str = ‘X-DSPAM-Confidence: 0.8475’
Use find and string slicing to extract the portion of the string after the colon character and then use the float function to convert the extracted string into a floating point number.
1 | text = "X-DSPAM-Confidence: 0.8475" |
Chapter 7 : Files
Exercise 7.1
Write a program to read through a file and print the contents of the file (line by line) all in upper case. Executing the program will look as follows:
1 | python shout.py |
You can download the file from http://www.py4e.com/code3/mbox-short.txt
1 | fn = input('Enter a file name: ') |
Exercise 7.2
Write a program to prompt for a file name, and then read through the file and look for lines of the form:
1 | X-DSPAM-Confidence: 0.8475 |
When you encounter a line that starts with “X-DSPAM-Confidence:” pull apart the line to extract the floating-point number on the line. Count these lines and then compute the total of the spam confidence values from these lines. When you reach the end of the file, print out the average spam confidence.
1 | Enter the file name: mbox-short.txt |
1 | i = 0 |
Exercise 7.3
Sometimes when programmers get bored or want to have a bit of fun, they add a harmless Easter Egg to their program Modify the program that prompts the user for the file name so that it prints a funny message when the user types in the exact file name “na na boo boo”. The program should behave normally for all other files which exist and don’t exist. Here is a sample execution of the program:
1 | python egg.py |
1 | i=0 |
Chapter 8 : Lists
Exercise 8.4
Download a copy of the file from www.py4e.com/code3/romeo.txt
Write a program to 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 function. For each word, check to see if the word is already in a list. If the word is not in the list, add it to the list. When the program completes, sort and print the resulting words in alphabetical order.
1 | Enter file: romeo.txt |
1 | fname = input("Enter file name: ") |
Exercise 8.5
Write a program to read through the mail box data and when you find line that starts with “From”, you will split the line into words using the split function. We are interested in who sent the message, which is the second word on the From line.
You will parse the From line and print out the second word for each From line, then you will also count the number of From (not From:) lines and print out a count at the end. This is a good sample output with a few lines removed:
1 | python fromcount.py |
1 | fname = input("Enter file name: ") |
Exercise 8.6
Rewrite the program that prompts the user for a list of numbers and prints out the maximum and minimum of the numbers at the end when the user enters “done”. Write the program to store the numbers the user enters in a list and use the max() and min() functions to compute the maximum and minimum numbers after the loop completes.
1 | Enter a number: 6 |
1 | k = list() |
Chapter 9 : Dictionaries
Exercise 9.2
Write a program that categorizes each mail message by which day of the week the commit was done. To do this look for lines that start with “From”, then look for the third word and keep a running count of each of the days of the week. At the end of the program print out the contents of your dictionary (order does not matter).
Sample Line:
1 | From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 |
Sample Execution:
1 | python dow.py |
1 | d = {} |
Exercise 9.3
Write a program to read through a mail log, build a histogram using a dictionary to count how many messages have come from each email address, and print the dictionary.
1 | Enter file name: mbox-short.txt |
1 | d = {} |
Exercise 9.4
Add code to the above program to figure out who has the most messages in the file. After all the data has been read and the dictionary has been created, look through the dictionary using a maximum loop (see Chapter 5: Maximum and minimum loops) to find who has the most messages and print how many messages the person has.
1 | Enter a file name: mbox-short.txt |
1 | d = {} |
Exercise 9.5
This program records the domain name (instead of the address) where the message was sent from instead of who the mail came from (i.e., the whole email address). At the end of the program, print out the contents of your dictionary.
1 | python schoolcount.py |
1 | d = {} |
Chapter 10 : Tuples
Exercise 10.1
Revise a previous program as follows: Read and parse the “From” lines and pull out the addresses from the line. Count the number of messages from each person using a dictionary.
After all the data has been read, print the person with the most commits by creating a list of (count, email) tuples from the dictionary. Then sort the list in reverse order and print out the person who has the most commits.
1 | Sample Line: |
1 | d = {} |
Exercise 10.2
This program counts the distribution of the hour of the day for each of the messages. You can pull the hour from the “From” line by finding the time string and then splitting that string into parts using the colon character. Once you have accumulated the counts for each hour, print out the counts, one per line, sorted by hour as shown below.
1 | python timeofday.py |
1 | d = {} |
Exercise 10.3
Write a program that reads a file and prints the letters in decreasing order of frequency. Your program should convert all the input to lower case and only count the letters a-z. Your program should not count spaces, digits, punctuation, or anything other than the letters a-z. Find text samples from several different languages and see how letter frequency varies between languages.
Compare your results with the tables at https://wikipedia.org/wiki/Letter_frequencies.
1 | import string |
Chapter 11 : Regular Expressions
Exercise 11.1
Write a program to sum all the numbers happened in the file.
- Sample data: http://py4e-data.dr-chuck.net/regex_sum_42.txt (There are 90 values with a sum=445833)
- Actual data: http://py4e-data.dr-chuck.net/regex_sum_1678990.txt (There are 87 values and the sum ends with 886)
1 | import re |
Exercise 11.2
Write a program to look for lines of the form:
1 | New Revision: 39772 |
Extract the number from each of the lines using a regular expression and the findall() method. Compute the average of the numbers and print out the average.
1 | Enter file:mbox-short.txt |
1 | import re |
Updating…
This page is kept updating.
Latest updated at 11/05/2022
Click to return to homepage, or Methodology of Jang.