Python Course 5: For Loops and Lists

For Loop Examples

Print the numbers 1 to 9

for k in range(1,10):
    print(k)

Countdown from 10 to 1

for k in range(10,0,-1):
    print(k)

Print the days of the week

days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
for day in days:
    print(day)

Print the five times table

for k in range(1,11):
    print("5 x {} = {}".format(k, 5*k))

For Loop Exercises

Write for loops to output the following sequences of numbers

  1. 0,1,2,3,4,5,6,7,8,9,10
  2. 0,2,4,6,8,10,12,14,16
  3. 1,2,3,4,5, … 97,98,99,100
  4. 7,14,21, … 63,70,77
  5. 20,18,16, … 4,2,0,-2
  6. 2,5,8,11,14,17,20,23,26,29
  7. 99,88,77,66,55,44,33,22,11,0
  8. Numbers 1 to 1000.
  9. Even numbers from 0 to 100.
  10. Odd numbers from -50 to 50
  11. All multiples of 3 up to 500.

Look at the days of the week example above. Use lists and for loops to do the following

  1. Print out the seasons of the year (Spring, Summer, Autumn, Winter)
  2. Create a list of the names of the four people closest to you. Use a for loop to print that list.

Extension

Look at the examples above.

  1. Use a for loop to print the 5 times table up to 12 x 5
  2. Use a for loop to print the 7 times table up to 12 x 7 in the form “3 x 7 = 21”
  3. Use a for loop to print the following sequence: 0.5, 0.4, 0.3, 0.2, 0.1, 0
  4. Use a for loop to print the following sequence: 0.03, 0.02, 0.01, 0, -0.01, -0.02, -0,03
  5. Use a for loop to print five random numbers between 1 and 10
  6. Use a for loop to print the first ten square numbers: 1, 4, 9, 16, 25, 36, 49, 64, 81, 100
  7. Use a for loop to print the first ten triangle numbers: 1, 3, 6, 10, 15, 21, 28, 36,45, 55

Python Course 4: Lists

Sample Code

food = ["Sausage", "eggs", "Bacon", "Beans"]
pupils = ["John", "Jill", "Emily", "Satpal"]
scores = [5,3,6,7,9,1,2]
days = ["Sunday","Monday","Tuesday","Wednesday","Thursday", "Friday","Saturday"]        

# Print all the days
for day in days:
    print(day)

#print eggs
print(food[1])

#print Emily, Satpal
print(pupils[2:])

#print Tuesday, Wednesday
print (days[2:4])

#print John, Jill
print(pupils[:2])

#print Friday
print(days[-2])

print(len(days))
print(max(scores))
print(min(scores))

if "John" in pupils:
    print("Pupil is present")
else:
    print ("Pupil absent")

pupils = pupils + ["Arthur"]
print(pupils)

Exercises

The following questions refer to the sample code. You can type the code into IDLE and run it to help you figure out the answer

  1. Look at the print(food[ 1 ]) line. What does the [ 1] do?
  2. How would you print the first item in the list?
  3. If a python list has seven items, what would number would the seventh item be?
  4. Look at the print(pupils[2:]) line. What does [2:] mean?
  5. Look at the print(days[2:4])line. What does [2:4] mean?
  6. Look at the print(days[-2]) line. What does [-2] mean?
  7. What does len do?
  8. What do max and min do?

Now write your own modules to do the following

  1. Create a list called months, containing the months in the year.
  2. Print out all the months, one after the other
  3. Use slicing (e.g. days[2:4]) to print out the spring months: March, April, May
  4. Print out the summer months: June, July, August
  5. Print out the first and last months of the year
  6. Print out the winter months: December, January and February

Extension: Research

Use a search engine and online manuals to find out how to get Python to do the following

  1. Reverse the following list: [“Sunday”,”Monday”,”Tuesday”,”Wednesday”,”Thursday”, “Friday”,”Saturday”] i.e. print out “Saturday”,”Friday”,”Thursday”,… etc
  2. Remove “eggs” from this list food = [“Sausage”, “eggs”, “Bacon”, “Beans”]
  3. Sort the following list into ascending order scores = [5,3,6,7,9,1,2]
  4. Insert “Mushrooms” into this list, just after “eggs”
  5. Count how many times “blue” appears in this list [“red”,”blue”,”blue”,”blue”,”red”,”blue”]

Python Course 3: Data Types and Integers

Good Practice

Which of the following is better programming practice? Why?

x = 35.51*1.17
print(x)

or

pounds = 35.51
euroRate = 1.17
euros = pounds * euroRate

print("£", pounds ,  " = " , euros , " euros")
print("at a rate of " , euroRate , " euros to the pound")

Formatting

Take a look at the output from the second piece of code

£ 35.51  =  41.546699999999994  euros
at a rate of  1.17  euros to the pound

This would be better if it read 41.55 euros, rather than 41.546699999999994

Also, take a look at this line

print("£", pounds ,  " = " , euros , " euros")

All those commas and speech marks are confusing. It’s easy to make a mistake when entering them.

There’s a better way to format your data.

pounds = 35.51
euroRate = 1.17
euros = pounds * euroRate

print("£ {} = {} euros".format(pounds, euros))
print("at an rate of {} euros to the pound".format(euroRate))

The above does the same as the original code. It has the advantage of being slightly easier to enter and read. As an added bonus, you can format the number of decimal places

pounds = 35.51
euroRate = 1.17
euros = pounds * euroRate

print("£ {} = {:.2f} euros".format(pounds, euros))
print("at an rate of {} euros to the pound".format(euroRate))

Notice the {:.2f}. This says “format the number as a float (a decimal) to 2 decimal places”

This produces the following output

£ 35.51 = 41.55 euros
at a rate of 1.17 euros to the pound

Much more user friendly!

Loop Question

Use a while loop to produce the sequence 0.1, 0.2, 0.3, …1.0

number = 0.1
while number <=1:
    print(number)
    number = number + 0.1

Produces

0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999

Format the number for a neater answer

number = 0.1
while number <=1:
    print("{:.1f}".format(number))
    number = number + 0.1

0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1.0

Number bases

You can format numbers into different bases as follows

print("{:d}".format(17))
print("{:b}".format(17))
print("{:X}".format(17))

The numbers are printed in denary, binary and hexadecimal.

17
10001
11

Remember that the input command reads strings. You have to convert strings to integers (whole numbers) or floats (decimals) if you want to use them to perform calculations.

Examples

1) Write a program that prompts the user to enter the length and width of a rectangle. Output the area of the rectangle

length = int(input("Enter the length of the rectangle"))
width = int(input("Enter the width of the rectangle"))
area = length*width
print("The rectangle has an area of {}".format(area))

2) To convert miles to kilometers, you multiply the number of miles by 1.609. Write a program that prompts the user to enter the number of miles, and then output the answer converted to kilometers

Note the use of float as a user may input 12.5 miles, for example.

miles = float(input("Enter the number of miles"))
kilometers = miles * 1.609
print("{} miles = {:.2f} kilometers".format(miles,kilometers))

Exercise

  1. Write a program with two variables, length and width, that outputs the perimeter of a rectangle. Test it with length = 5 and width = 4.
  2. At the time of writing, the exchange rate for pounds to euros is 1 GBP = 1.19984 Euros. Write a program that will convert pounds to euros. Test it using the data GBP4.50 (Don’t forget to convert the input to a float!)
  3. Now write a program to convert euros to pounds. Test it using the data Euro 7.40
  4. Prompt the user to input a number. Output the square of that number.
  5. Prompt the user to input two numbers. Output the average of those two numbers.
  6. Prompt the user to input three numbers. Output the sum and the average of those three numbers.
  7. Assume pi = 3.1415. Prompt the user to input the radius of a circle. Output the circumference and the diameter of that circle

Extension: Fahrenheit to Celsius

Here are the formulas to convert from Fahrenheit to Celsius and back again.

°F to °C Deduct 32, then multiply by 5, then divide by 9 °C to °F Multiply by 9, then divide by 5, then add 32

  1. Now write a program to convert Celsius to Fahrenheit. Use the test data to check your program.
  2. Write a program to convert Fahrenheit to Celsius. Again, use the test data below to check your program.

Test data

CF
032
1254
100212
-327
-180
-23-10

Python Course 2: Bracelets and Snakes

The following code draws a snake

import turtle

SIDE = 50

def triangle():
    turtle.begin_fill()
    for n in range(3):
	turtle.forward(SIDE)
	turtle.right(120)
    turtle.end_fill()

def black_triangle():
    turtle.fillcolor("black")
    triangle()

def white_triangle():
    turtle.fillcolor("white")
    triangle()

def snake():
    black_triangle()
    turtle.forward(SIDE)
    turtle.right(60)
    white_triangle()
    turtle.left(60)

snake()

Exercise

  1. Copy the code into your IDE and run it.
  2. Draw a snake 6 segments long
  3. Draw a red and green snake, 6 segments long.
  4. Draw pink and yellow snake, 6 segments long, but half the size of the previous snake.
  5. Use a for loop to simplify your code.
  6. Now draw a snake 10 segments long

Extension

Modify your code to draw a bracelet, as shown below.

Functions and Turtle Graphics

The following code is the start of a solution to the problem of  drawing a chessboard. It uses functions to help make the code  understandable

import turtle

# Declare this at the top.  Put it in capitals to show it shouldn't be changed
SIDE = 50

def square():
    turtle.begin_fill()
    for n in range(4):
	turtle.forward(SIDE)
	turtle.right(90)
    turtle.end_fill()


def black_square():
    turtle.fillcolor("black")
    square()

def white_square():
    turtle.fillcolor("white")
    square()

def move_one_square_right():
    turtle.penup()
    turtle.forward(SIDE)
    turtle.pendown()

def move_one_square_down():
    turtle.penup()
    turtle.right(90)
    turtle.forward(SIDE)
    turtle.left(90)
    turtle.pendown()

def white_black_line():
    for n in range(4):
	white_square()
	move_one_square_right()
	black_square()
	move_one_square_right()

# Speed up the turtle
turtle.speed(0)

# Draw two lines of the chessboard
white_black_line()
turtle.home()
move_one_square_down()
move_one_square_down()
white_black_line()

Exercise

  1. Copy the code into your IDE. Watch out for indents!
  2. Run the code and see what it does.
  3. Add a function to draw a black_white() line
  4. Draw a chessboard using the functions provided
  5. Can you make you code more efficient, perhaps by using a for loop?
  6. What happens if you change the value of SIDE?
  7. Draw a 10×10 chessboard

Extension

The following function draws a hexagon:

def hexagon():
  for n in range(6):
      turtle.forward(50)
      turtle.left(60)
  1. Use the function to draw a honeycomb pattern
  2. Can you make the honeycomb cover the whole screen?

Python Course 1: Turtle Graphics

Useful Code

Moving the Turtle

turtle.forward(100)
turtle.back(50)
turtle.right(90)
turtle.left(45)
turtle.goto(10,10)
turtle.home()
turtle.setheading(0)

Changing the Pen

turtle.pencolor('red')
turtle.penup()
turtle.pendown()
turtle.pensize(4)

Changing the Board

turtle.reset()
turtle.bgcolor('blue')
turtle.showturtle()
turtle.hideturtle()

Exercise

Draw the following

  1. A square with sides of length 100
  2. An equilateral triangle with sides of length 80
  3. A noughts and crosses board
  4. Draw a star by turning an angle of 144 degrees.
  5. A red hexagon on a blue background.

Lesson 2

The following program draws a purple square with a black border. Note the use of begin_fill() and end_fill()

import turtle

turtle.fillcolor('purple')
turtle.pencolor('black')

turtle.begin_fill()
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
turtle.end_fill()

The above requires a lot of cut and paste code: always a sign that there is a better way of doing things. Here’s one way:

import turtle

turtle.fillcolor('purple')
turtle.pencolor('black')

turtle.begin_fill()

for times in range(4):
    turtle.forward(100)
    turtle.left(90)

turtle.end_fill()

We are going to be drawing lots of squares. We can define the  code to draw a square as a function, that way we can reuse it. (Learning  to use functions is the main reason we are using turtle graphics!)

import turtle

def square():
    for times in range(4):
	turtle.forward(100)
	turtle.left(90)

turtle.fillcolor('purple')
turtle.pencolor('black')

turtle.begin_fill()
square()
turtle.end_fill()

We can add a size parameter to the function. Now we can draw squares of different sizes.

import turtle

def square(size):
    for times in range(4):
	turtle.forward(size)
	turtle.left(90)

square(50)
square(100)
square(200)

Exercise

1) Enter the following code and run it. Make sure you understand what it’s doing.

import turtle

def square():
    for times in range(4):
	turtle.forward(100)
	turtle.left(90)

for n in range(8):
    square()
    turtle.right(45)

2) What do you think the following code will do? Enter it and run it.

import turtle

def square(size):
    for times in range(4):
	turtle.forward(size)
	turtle.left(90)

for n in range(8):
    square(20*n)

3) Define a function to draw a triangle.
4) Use your triangle function to draw the following shape

Extension

  1. Write a function to draw a pentagon
  2. Write a function to draw a hexagon
  3. Draw a function that accepts a parameter number_of_sides that draws a  polygon with that number of sides
  4. Write a function to draw a chessboard
  5. Write a function to draw a honeycomb