Python Programming: A Self-Learning Guide

# Python Programming: A Self-Learning Guide

Note: If you already know how to program in another language, feel that the guide below is too slow for you, or just want to see more code examples then you may want to check out my Python Crash Course.

The purpose of this page is to guide someone wishing to learn to program using the Python programming language. Each section consists of

• a link to a video that teaches an element of the language
• sample problems for you to try. My solutions to the problems can be found at the bottom of the page. It’s OK if your solution isn’t the same as mine.

Once you reach the stage where you understand statements, conditionals, loops, and functions, I also include

• a link to a page in which I discuss my thinking process as I design a program to accomplish some task. That page also contains a link to a video with more details.

Note that the practice problems build upon your knowledge. Some of the practice problems assume you worked the earlier problems.

Tip: In order to learn to program, you have to be willing to try to write programs. In the beginning this may consist of doing very simple things or taking existing code and modifying it to change its functionality. As you gain experience and confidence, you need to work to write code from scratch.

### Introduction

Now you need to install the necessary software:

### Statements

Now try the following practice problems:

Practice #1: The following program finds the area of a rectangle. Modify it to find the area of a triangle.

```print("I will calculate the area of a rectangle for you.")
sideA = int( input("Enter the length of one side: ") )
sideB = int( input("Enter the length of an adjacent side: ") )

area = sideA * sideB

print("The area is {}".format(area))
```

Practice #2: Write a program that prompts the user for a number and then uses it to evaluate the following mathematical function: f(x) = 3x ^2 + 5x – 6. Note that to raise x to the nth power, you write x**n.

Practice #3: Write a program that will prompt the user for a temperature in Fahrenheit and then convert it to Celsius.  You may recall that the formula is C = (5/9) * (F – 32) . Assume the Fahrenheit temperature is an integer, but print the Celsius temperature to two decimal places.

Practice #4: Write a program that produces a random integer in the range of 1 to 100 and prints it out. At the top of your file you should have the lines (you can choose a variable name other than `value`).

```import random
value = random.randint(1, 100)
```

### Conditionals

Practice #1: Compare the two sets of conditionals below. Do you expect them to produce the same output (other than the version number printed at the beginning)?

```#  version 1:
x = 5

if x < 4:
print("1: %d is less than 4" % x)
elif x < 6:
print("1: %d is less than 6" % x)
elif x < 8:
print("1: %d is less than 8" % x)
elif x < 10:
print("1: %d is less than 10" % x)
else:
print("1: %d is greater than or equal to 10" % x)

#  version 2:
x = 5

if x < 4:
print("2: %d is less than 4" % x)
if x < 6:
print("2: %d is less than 6" % x)
if x < 8:
print("2: %d is less than 8" % x)
if x < 10:
print("2: %d is less than 10" % x)
else:
print("2: %d is greater than or equal to 10" % x)
```

Practice #2: Modify the temperature conversion program in the Statements section to state whether or not water would boil at the temperature given. Your output might look like this:

```What is the temperature in Fahrenheit? 100
A temperature of 100 degrees Fahrenheit is 37 in Celsius
Water does not boil at this temperature (under typical conditions).
```

Practice #3: Write a program that prompts the user for their age. If they are younger than 18 years old, only print “you are a child”. If they are 18 or older, print “you are NOT a child”. If they are at least 67 years old, also print “enjoy your retirement”. Your output might look like this (this is several runs of the program):

```age?  14
you are a child

age?  18
you are NOT a child

age?  50
you are NOT a child

age?  67
you are NOT a child
```

Practice #4: In the Statements section your wrote a program to generate a random integer in the range of 1 to 100. Extend the program now to generate two random integers in the range of 10 to 20, print each of the integers generated, and then print which is smallest and which is largest (or that they are equal). Note that you will only use a single `import` statement. Here is sample output from multiple runs of the program:

```the integers generated are 13 and 10
smallest = 10, largest = 13

the integers generated are 20 and 20
they are equal

the integers generated are 10 and 16
smallest = 10, largest = 16
```

### Loops

Practice #1: Write a program that prompts the user for two positive integers, Start and Stop, and then sums the integers from Start to Stop, inclusive.  Perform some basic error checking. If either number is negative or zero or Start is greater than Stop, tell the user there is an error and exit.

Output from a couple of runs is:

```Enter a positive integer: 1
Enter a positive integer greater than or equal to the first: 5
The sum from 1 to 5 is 15

Enter a positive integer: 34
Enter a positive integer greater than or equal to the first: 33

ERROR: invalid input
```

Practice #2: Write a program that prompts the user for two positive integers, Start and Stop, and then counts the number of even integers in the range of Start to Stop.  Print the even integers in this range.  Output might look like this:

```Enter a starting integer:  8
Enter a stopping integer:  19
8
10
12
14
16
18
There are 6 even integers between 8 and 19
```

Practice #3: Write a program that repeatedly prompts a user for an integer and then prints the integer, stopping once the integer is greater than 10.

Practice #4: Write a program that repeatedly prompts a user for an integer and then prints the integer, stopping once the integer is > 10 or the user has provided 5 integers.

Practice #5: Write a program that prompts the user for grades and then prints the average grade. The program will continue to prompt for grades until a negative numbers (an invalid grade) is given.  Here is sample output.

```grade? 0
average of 4 grades is 1.50

average of 5 grades is 3.00
```

Practice #6: Write a program that picks a random integer in the range of 1 to 100.  It then prompts the user for a guess of the value, with hints of ‘too high’ or ‘too low’ from the program.  The program continues to run until the user guesses the integer. Sample output might look like this:

```true value: 74
too low
too high
too low
too high
you guessed it!!!
```

When designing this program, consider the following:

• what condition will the loop use to keep running until the user guesses correctly?
• for test purposes, you might choose to have the loop run a predetermined number of times.

### Bits, Bytes, and Number Bases

This video discusses the internal representation of numbers. While you can do a lot without knowing about bits, if you continue programming at some point you will want to know about this to have a better understanding of the internals of a computer.

### Functions

design example: generating a multiplication table

Many people struggle to write functions. Remember that many functions receive one or more input values and return an answer. Try thinking about the input and output of your function. Also, while this should only be a short-term solution, if you are struggling with the function try writing all of the code together and then move the appropriate parts to a function.

Practice #1: A positive integer n is a perfect number if the sum of the divisors of n (excluding n itself) is equal to n. For example, 6 has divisors 1, 2, 3, and 6 and 6 = 1 + 2 + 3. Write a program to prompt the user for an integer n and then calls a function that returns `True` if n is a perfect number and `False` if it is not a perfect number. Print the result based on the value returned by the function.  Here are several sample runs.

```n?  4
n?  6
6 is a perfect number
n?  10
n?  28
28 is a perfect number
```

Practice #2: Write a program that finds the perfect numbers in the range of 1 to 10,001 using the function that you created in the previous problem. Here is sample output.

```6 is a perfect number
28 is a perfect number
496 is a perfect number
8128 is a perfect number
```

Practice #3: Write a program to prompt the user for an integer n and then calls a function that when given n prints n asterisks.  Here are several sample runs. Hint: remember that by default print() adds a newline, so if you don’t want it you will need to suppress it.

```n?  1
*

n?  2
**

n?  5
*****

n?  10
**********
```

Practice #4: Write a program to prompt the user for an integer n and then calls a function that when given n prints n spaces followed by n asterisks.  Here are several sample runs.

```n?  1
*

n?  2
**

n?  3
***

n?  10
**********
```

Practice #5: Write a program that prompts the user for an integer n and then calls a function (passing n to it) that prints a pyramid n levels high from asterisks.  Here are several sample runs.

```how tall should the pyramid be?  5
*
* *
* * *
* * * *
* * * * *

how tall should the pyramid be?  10
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
```

### Lists and Tuples

design example: simulating a perfect shuffle

In my video I failed to discuss tuples. Tuples are similar to lists in the sense that they are and ordered collection of objects; the primary distinction is that tuples are immutable and therefore cannot be changed.

```aList  = [10, 20, 30]
aTuple = (10, 20, 20)

print( type(aList) )
print( type(aTuple) )
print()

print(aList)
print(aTuple)

aList = 99
# aTuple = 99  # tuples are immutable, so you can't do this

"""  output
<class 'list'>
<class 'tuple'>

10
10
"""
```

Practice #1: Write a function that when given a 2-dimensional list will print the list in its original shape.  For example, if given the list

```dataList = [ [ 1,  2,  3,  4],
[ 5,  6,  7,  8],
[ 9, 10, 11, 12] ]
```

the function will print

``` 1   2   3   4
5   6   7   8
9  10  11  12
```

If you have a 2-dimensional list called `myList`, then to find the number of rows in the list you can use `len(myList) `and to find the number of elements in each row (assuming they are all the same) you can use `len(myList)`.

Practice #2: Write a function that when given a 1-dimensional list will sum the values in the list and return the sum. Check your work by applying Python’s `sum()` function to your list.

Practice #3: Write a function that when given a 1-dimensional list will sum the values in the list if they are multiples of 3 and return the sum.

Practice #4: Write a function that when given a 2-dimensional list will sum and print the values of each row. The printing should take place in the function.

Practice #5: Write a function that when given a 2-dimensional list will return a list of the column sums. Assume that each row has the same number of elements. For example, given the list

```a = [[1, 2, 3, 10],
[4, 5, 6, 10],
[7, 8, 9, 10]]
```

the returned value should be

```[12, 15, 18, 30]
```

Practice #6: Python’s `range()` function returns a `range` object. Without using the `range` function, write `myrange()` that will be called using the form `myrange(a, b)` and the function returns a list with the integers from a to less than b.  If you want more of a challenge, add a third parameter, c, that is the step size for the values in the list. You can assume that a will be less than or equal to b.

### Strings

design example: converting numbers to words

Practice #1: Write a function that will receive a string of comma-separated words and count how many of the words have more than five letters.  The function will return the count when finished. For example,

```s = "cat,dog,horse,elephant,giraffe"
print(wordCount( s ))   # prints 2
```

Practice #2: Write a function that will receive a string and a delimiter and print each token in the string as well as the number of characters in the token.

Practice #3: Write a function that receives a string that consists of any combination of spaces, digits, uppercase or lowercase letters.  The function should count the number of uppercase letters and return this count.

Practice #4: Write a function that receives a string that consists of any combination of spaces, digits, uppercase or lowercase letters.  The function will print the number of spaces, the number of digit characters, the number of uppercase characters, and the number of lowercase characters.

### File Input/Output

design example #1: printing a class schedule

Practice #1: Write a program to write the integers 1 to 10 to a file, one number per line. Then have the program read the file, summing the integers.

Practice #2: Use an editor to create a file in which each line consists of two integers, separated by a comma. For example, the file might be

```4,6
8,2
44,44
21,-3
50,99
```

Then write a program to read this CSV-formatted file and, for each line, prints the largest number on the line.

Practice #3: Read a CSV file in which each line consists of numbers separated by commas.  Sum the numbers in the last column. Don’t assume each line consists of the same quantity of numbers.

Practice #4: Read a CSV file in which each line consists of animal names separated by commas.  Print the names sorted (remember that there is a list method for sorting). The file to use is

```cat,dog,horse
rabbit,mouse
bat,rat,giraffe,gorilla
elephant
```

### Dictionaries

Practice #1: Create a dictionary with people’s names as keys and their ages as values and print each person’s name and age.

Practice #2: Modify the previous program to only print the names and ages of people over 20 years old.

Practice #3: Modify the previous program to find the youngest person in the dictionary. Print the person’s age and name.

Practice #4: Write a program that stores the following key/value pairs in a dictionary and then produces the sum of the values corresponding to keys that would come after the letter ‘f’ if sorted (you are not being asked to actually sort).

```"rabbit" : 7
"dog" : 42
"mouse" : 55
"cat" : -23
"horse" : 13
```

Practice #5: Store the names and ages from the first problem in a CSV file and read in the file, creating a dictionary from it. Print the names and ages, sorted by name. Finally, print the sum of the ages.

Practice #6: We have the following data:

```Name  Age  Weight
-------------------
Tom    43   185
John   50   170
Susan  35   125
```

Store this data in a dictionary with the name as the key.  Write a function that when given a dictionary of this form and either the word “age” or “weight” will print the name of the user with the largest age or weight (depending on the word passed). You can assume that age and weight will be the only two things stored for each name, but don’t make assumptions about the number of entries in the dictionary.

## Solutions to Practice Problems

———- Statements, Practice #1

```print("I will calculate the area of a triangle for you.")
w = int( input("Enter the width: ") )
h = int( input("Enter the height: ") )

area = (w*h)/2

print("The area is {} square units".format(area))
```

———- Statements, Practice #2

```x = int( input("Enter a number: ") )

f = 3 * x**2 + 5*x - 6
print("f({}) = {}".format(x, f))
```

———- Statements, Practice #3

```f = int( input("Enter a temperature in Fahrenheit: ") )

c =  (f - 32)*5/9
print("{} degrees Fahrenheit = {:.2f} degrees Celsius".format(f, c))
```

———- Statements, Practice #4

```import random

value = random.randint(1, 100)
print(value)
```

———- Conditionals, Practice #1

No. The top code contains `elif` statements and so each is only evaluated if all previous conditionals are `False`. In the bottom version, each `if` statement is independent of the others and each is evaluated.

———- Conditionals, Practice #2

```f = int( input("Enter a temperature in Fahrenheit: ") )

c =  (f - 32)*5/9

if c >= 100 :
print("water normally boils at {:.2f} degrees Celsius".format(c))
else :
print("{:.2f} degrees Celsius is not hot enough to boil water".format(c))
```

———- Conditionals, Practice #3

```age = int( input("age? ") )

if age < 18 :
print("you are only a child")
else :
print("you are NOT a child")

if age >= 67 :
```

———- Conditionals, Practice #4

```import random

a = random.randint(10, 20)
b = random.randint(10, 20)

print("the integers generated are %d and %d" % (a, b))

if a < b :
print("smallest = %d, largest = %d" % (a, b))
elif a > b :
print("smallest = %d, largest = %d" % (b, a))
else :
print("they are equal")
```

———- Loops, Practice #1

```start = int( input("Enter a positive integer: ") )
stop = int( input("Enter a positive integer greater than or equal to the first: ") )

if start < 1 or stop < 1 or start > stop :
print("\n ERROR: invalid input")
else :
mysum = 0
i = start
while i <= stop :
mysum += i
i += 1

print("The sum from %d to %d is %d" % (start, stop, mysum))
```

———- Loops, Practice #2

```start = int( input("Enter a positive integer: ") )
stop = int( input("Enter a positive integer greater than or equal to the first: ") )

if start < 1 or stop < 1 or start > stop :
print("\nERROR: invalid input")
else :
even = 0
i = start
while i <= stop :
if i%2 == 0 :
print(i)
even += 1
i += 1

print("The are %d even integers between %d and %d" %
(even, start, stop))
```

———- Loops, Practice #3

```while True :
number = int( input("enter an integer: ") )

if number > 10 :
break

print(number)
```

———- Loops, Practice #4

```count = 0
while count < 5 :
number = int( input("enter an integer: ") )

if number > 10 :
break

count += 1
print(number)
```

———- Loops, Practice #5

```grade = 0
count = 0
mysum = 0

count += 1

print("average of {} grades is {:.2f}".format(count, mysum/count))
```

———- Loops, Practice #6

```import random

value = random.randint(1, 100)
print("true value: %d (for testing)" % value)

guess = -99  # initial value to get loop going

while value != guess :
guess = int( input("guess? ") )

if guess > value :
print("  too high")
if guess < value :
print("  too low")

print("you guessed it!!!")
```

———- Functions, Practice #1

```def perfectCheck( n ) :
mysum = 0
for i in range(1, n) :
if n%i == 0 :
mysum += i

if n == mysum :
return True
else :
return False

####  main  ####
number = int( input("enter an integer: ") )

if perfectCheck(number) :
print("{} is a perfect number".format(number))
```

———- Functions, Practice #2

```def perfectCheck( n ) :
mysum = 0
for i in range(1, n) :
if n%i == 0 :
mysum += i

if n == mysum :
return True
else :
return False

####  main  ####
for i in range(1, 10001) :
if perfectCheck(i) :
print("{} is a perfect number".format(i))
```

———- Functions, Practice #3

```def printStars( n ) :
for i in range( n ) :
print("*", end="")

print()

####  main  ####
number = int( input("enter a nonnegative integer: ") )

printStars(number)
```

———- Functions, Practice #4

```def printStars( n ) :
for i in range( n ) :
print(" ", end="")

for i in range( n ) :
print("*", end="")

print()

####  main  ####
number = int( input("enter a nonnegative integer: ") )

printStars(number)
```

———- Functions, Practice #5

```def printStars( n, spaces ) :
for i in range( spaces-n ) :
print(" ", end="")

for i in range( n ) :
print("* ", end="")  # notice the space after *

print()

####  main  ####
number = int( input("enter a nonnegative integer: ") )

for i in range( 1, number+1 ) :
printStars(i, number)
```

———- Lists, Practice #1, version 1

```def printList( d ) :
for row in d :       # get row
for col in row : # get column within row
print("%2d " % col, end="")
print()

print()

####  main  ####
# test with different sizes
a = [[1, 2, 3],
[4, 5, 6]]

b = [[ 1,  2,  3,  4,  5],
[ 6,  7,  8,  9, 10],
[11, 12, 13, 14, 15]]

printList(a)
printList(b)
```

———- Lists, Practice #1, version 2

```def printList( d ) :
rows = len( d )
cols = len( d )
for r in range( rows) :
for c in range( cols ) :
print("%2d " % d[r][c], end="")
print()

print()

####  main  ####
# test with different sizes
a = [[1, 2, 3],
[4, 5, 6]]

b = [[ 1,  2,  3,  4,  5],
[ 6,  7,  8,  9, 10],
[11, 12, 13, 14, 15]]

printList(a)
printList(b)
```

———- Lists, Practice #2

```def sumList( d ) :
mySum = 0
for i in d :
mySum += i

return mySum

####  main  ####
# test with different sizes
a = [1, 2, 3]
b = [ 1,  2,  3,  4,  5]

print(sumList(a))
print(sumList(b))
```

———- Lists, Practice #3

```def sumList( d ) :
mySum = 0
for i in d :
if i%3 == 0 :
mySum += i

return mySum

####  main  ####
# test with different sizes
a = [1, 2, 3, 9, 81]
b = [ 1,  2,  3,  4,  5, 6, 7]

print(sumList(a))
print(sumList(b))
```

———- Lists, Practice #4

```def sumRow( d ) :
for row in d :
mySum = 0
for col in row :
mySum += col
print("row sum = {}".format(mySum) )

####  main  ####
a = [[1, 2],
[3, 4, 5, 6],
[7, 8, 9]]

sumRow(a)
```

———- Lists, Practice #5

```def colSums( d ) :
rows = len(d)
cols = len(d)
sums = []

for c in range(cols) :  # process each column
mySum = 0
for r in range(rows) :
mySum += d[r][c]
sums.append(mySum)

return sums

####  main  ####
a = [[1, 2, 3, 10],
[4, 5, 6, 10],
[7, 8, 9, 10]]

print( colSums(a) )
```

———- Lists, Practice #6

```def myRange( a, b, c=1 ) :
# since an initial value is given to c, we
#   can leave c out in the function call if
#   we are OK with its initial value
out = []

while a < b :
out.append( a )
a += c

return out

####  main  ####
print( myRange(2, 5) )
print( myRange(5, 5) )
print( myRange(4, 10) )
print( myRange(4, 10, 2) )
print( myRange(4, 10, 3) )
```

———- Strings, Practice #1

```def wordCount( s ) :
count = 0

tokens = s.split(',')
for t in tokens :
print(t)   # uncomment for testing
if len(t) > 5 :
count += 1

return count

####  main  ####
s = "cat,dog,horse,elephant,giraffe"

print(wordCount( s ))
```

———- Strings, Practice #2

```def printTokens( s, d ) :
tokens = s.split(d)
for t in tokens :
print("{} has {} characters".format(t, len(t)))

print()

####  main  ####
s = "cat,dog,horse,elephant,giraffe"

printTokens( s, ',' )
printTokens( s, 'o' )
```

———- Strings, Practice #3

```def countUpper( s ) :
count = 0

i = 0
while i < len(s) :
if 'A' <= s[i] and s[i] <= 'Z' :
count += 1

i += 1

return count

####  main  ####
s = "lower 123 UPPER mIxEd"

print(countUpper( s ))
```

———- Strings, Practice #4

```def countChars( s ) :
# we could have separate variables for each counter
#   but using a list allows me to loop through the
#   counts when printing

classes = ["lowercase", "uppercase", "digits", "spaces"]
counts = [0, 0, 0, 0]

i = 0
while i < len(s) :
if 'a' <= s[i] and s[i] <= 'z' :
counts += 1
elif 'A' <= s[i] and s[i] <= 'Z' :
counts += 1
elif '0' <= s[i] and s[i] <= '9' :
counts += 1
elif s[i] == ' ' :
counts += 1

i += 1

for i in range( len(counts) ) :
print("{} = {}".format(classes[i], counts[i]))

####  main  ####
s = "lower 1234 UPPER mIxEd"

countChars( s )
```

———- Files, Practice #1

```fp = open("practice.txt", "w")

for i in range(1, 11) :
fp.write("%d\n" % i)

fp.close()

fp = open("practice.txt", "r")
mysum = 0

for line in fp :
mysum += int(line)

fp.close()

print("sum = %d" % mysum)
```

———- Files, Practice #2

```fp = open("practice.txt", "r")

for line in fp :
# if I know the number of tokens, I can assign
#   each to a variable name instead of getting
#   a list
left, right = line.strip().split(',')
left, right = int(left), int(right)

if left > right :
print("%d > %d" % (left, right))
elif left < right :
print("%d > %d" % (right, left))
else :
print("%d = %d" % (right, left))

fp.close()
```

———- Files, Practice #3

```fp = open("practice.txt", "r")

mysum = 0

for line in fp :
tokens = line.strip().split(',')

x = int(tokens[-1])
mysum += x

fp.close()

print("sum = {}".format(mysum))
```

———- Files, Practice #4

```fp = open("practice.txt", "r")

animals = [ ]

for line in fp :
tokens = line.strip().split(',')
for t in tokens :
animals.append(t)

fp.close()

animals.sort()

for a in animals :
print(a)
```

———- Dictionaries, Practice #1

```d = {"Ralph" : 7,
"Suzy" : 42,
"Mike" : 55,
"Allison" : 13}

for k in d :
print("{} is {} years old".format(k, d[k]))
```

———- Dictionaries, Practice #2

```d = {"Ralph" : 7,
"Suzy" : 42,
"Mike" : 55,
"Allison" : 13}

for k in d :
if d[k] > 20 :
print("{} is {} years old".format(k, d[k]))
```

———- Dictionaries, Practice #3

```d = {"Ralph" : 77,
"Suzy" : 42,
"Mike" : 55,
"Allison" : 63}

"""
there are several ways to do this
this way requires no assumptions about the
initial value of the min age
"""

initialize = True

for k in d :
if initialize :  # check if first person
minName = k
minAge  = d[k]
initialize = False
elif d[k] < minAge :
minName = k
minAge  = d[k]

print("{} is {} years old".format(minName, minAge) )
```

———- Dictionaries, Practice #4

```d = {"rabbit" : 7,
"dog" : 42,
"mouse" : 55,
"cat" : -23,
"horse" : 13}

mysum = 0
for k in d :
if k > 'f' :
mysum += d[k]

print("sum = %d" % mysum)
```

———- Dictionaries, Practice #5

```d = {}

fp = open("names.csv", "r")
for line in fp :
name, age = line.strip().split(',')
d[name] = int(age)

fp.close()

mysum = 0
keys = sorted( d.keys() )

for k in keys :
print("{} is {} years old".format(k, d[k]))
mysum += d[k]

print("\nthe sum of the ages is %d" % mysum)
```

———- Dictionaries, Practice #6

```def findMax(d, term) :
mymax = 0

for k in d :
if d[k][term] > mymax :
mymax = d[k][term]

print("max %s is %d" % (term, mymax) )

#####  main  #####
d = {"Tom"   : {"age" : 43, "weight" : 185},
"John"  : {"age" : 50, "weight" : 170},
"Susan" : {"age" : 35, "weight" : 125} }

findMax(d, "age")
findMax(d, "weight")
```