Python Course 8:

Question Loop Examples

A Basic Question Loop

Keep asking the question until the correct answer is entered

answer = ""
while (answer != "Paris"):
    answer = input("What is the capital of France?")
print("Correct!")

A Question Loop with a Count

Keep a count of how many attempts were made

answer = ""
count = 0

while (answer != "Paris"):
    answer = input("What is the capital of France?")
    count = count + 1

print("Correct!")
print("You took ", count , "goes")

A Question Loop with a Flag

finished = False
number = 0
print("Denary to Binary Converter")
print("Enter -1 to finish")

while (finished == False):
    number = int(input("Enter a number in Denary"))
    if (number == -1):
	finished = True
    else:
	print("{:b}".format(number))

A Question Loop with a Count and a Flag

finished = False
correct = False
answer = ""
tries = 3

while (finished == False):
    password = input("Enter the password: ")
    if (password == "p455w0rd"):
	finished = True
	correct = True
    elif (tries == 1):
	finished = True
	correct = False
    else:
	tries = tries - 1
	print("Wrong.  You have", tries, "tries remaining")


if(correct == True):
    print("You're in!")
else:
    print("Locked out!")

Exercises

1) Write a program that asks “Are we there yet?” and prompts the user to enter an answer. The program loops until the user enters “Yes”. The program then outputs “Hooray!”

2) Write a program that asks the user to guess a number between 1 and 10. The program loops until the user enters the correct answer [7]. The program then outputs then the number of guesses made.

3) Modify the program from question 2 so that the user now has to guess a number between 1 and 100. The program outputs “Too low” if the guess is lower the number, “Too high” if the guess is highter than the number and “Correct” if the guess is correct. The program then terminates

4) The following code converts pounds to kilograms. Write a program that prompts the user to enter a weight in pounds or -1 to terminate. The program will output the weight in kilograms. If -1 is entered the program will print “Goodbye”

pounds = 4
kilograms = pounds * 0.453592
print(kilograms)

5) A house alarm system is triggered when the front door is open. The user has three attempts to enter a four digit code. If the user enters the correct code the system outputs “Deactivated!”. If the user enters the incorrect code the system outputs the number of attempts remaining. If the user does not enter the correct code within three attempts the system outputs “Alarm!”

Extension

Write a quiz program that asks the user 5 questions.  The user is allowed 2 attempts at each question.  At the end the program prints out the users score out of 5

Python Course 7: Functions

Sample Code

def hello(name):
    answer = "Hello " + name
    return answer

print(hello("George"))
print(hello("Gill"))
def isChild(age):
    if age < 18:
        return "Child"
    else:
        return "Adult"

print(isChild(35))
def AreaRect(length, width):
    return length*width

l = int(input("Enter the length"))
w = int(input ("Enter the width"))
print(AreaRect(l, w))
PI = 3.1415

def main():
    radius = 4
    print("The area of a circle radius ", radius, " is ", Area(radius))     


def Area(r):
    return PI*r*r

main()

Exercises

  1. Write a function that accepts a string and returns “Pleased to meet you, ” + string
  2. Write a function that accepts a number and returns “Child” if the number is <18 and “Adult” otherwise
  3. Write a function that accepts a number and returns “Grade A” if the number is >20, “Grade B” if the number is >15, “Grade C” if the number is >10 and “Fail” otherwise.
  4. Write a function that accepts two numbers and returns the average of the numbers
  5. Write a function that accepts three integers and returns the average of the numbers.
  6. Write a function that accepts the length and width of a rectangle and returns the perimeter of the rectangle
  7. Write a function that accepts the base and height of a triangle and returns the area of the triangle
  8. Write a function that accepts a list and returns the sum of the list

Extension

  1. Write a function that returns the hypotenuse of a triangle when the other two sides are int a and int b. (Remember: hypotenuse squared equals a squared plus b squared)
  2. The scalar product of u=(u1,u2,u3) and v=(v1,v2,v3) is defined to be u1v1+u2v2+u3v3. Write a function that accepts two int tuples as parameters and returns an int representing the scalar product of those two tuples
  3. If A = (a1,a2, …an) and B = (b1,b2, …bn) then the vector sum of the two tuples A + B = (a1+b1, a2+b2, … , an+bn). Write a function that accepts two tuples as parameters and returns an array representing the vector sum of those two tuples
  4. The Euclidean distance between two points A = (a1,a2, …an) and B = (b1,b2, …bn) is defined as sqrt((a1-b1)2 + (a2-b2)2 +… + (an-bn)2). Write a function that accepts two int tuples representing A and B as parameters and returns a double representing the Euclidean distance between them.

Python Course 6: String Handling

Sample Code

s = "This is a sample string"
print(s)
print("It contains this many characters: ", len(s))
print("Here it is in upper case...")
print(s.upper())
print("Here it is split into a list:")
words = s.split()
for word in words:
    print(word)
print("Here it is split by the letter \'a\'")
words = s.split("a")
for word in words:
    print(word)
print("Here's the characters from index 1 to 3")
print(s[1:3])
print("Here's the sample string with the letter s changed to z")
print(s.replace("s","z"))
print("And now with the letter s changed to sausage...")
print(s.replace("s","sausage"))
print("And now with the spaces removed...")
print(s.replace(" ",""))
print("Notice the original string is unchanged... ")
print(s)

Exercise

  1. Output the length of the String “I never saw a purple cow”
  2. Convert the String “I never saw a purple cow” to uppercase and output the resulting string.
  3. Use \n to create a string that prints out the words to Happy Birthday. Make it yourself (Happy Birthday dear Kevin). Print out the string
  4. Use the replace method to print out the words to Happy Birthday, this time for Mr Lightfoot
  5. Output the String “I never saw a purple cow” as a list of separate words.
  6. Output the initial letters of the String “I never saw a purple cow”
  7. Prompt the user to enter a String. Output a list of the initial letters of the words input. Example: input “British Broadcasting Corporation” output “B”,”B”,”C”.

Extension

  1. Prompt the user to enter a String. Output a String with the vowels replaced with *’s. Example: input “I never saw a purple cow” output “* n*v*r s*w * p*rpl* c*w”
  2. Prompt the user to enter a string. Output the string as separate words in alternate upper and lower case: SO it LOOKS like THIS example
  3. Output the following list as one String: words = [“Calling”, “occupants”, “of”, “interplanetary”, “craft”]
  4. Prompt the user to enter a string. Output the number of vowels in the String.
  5. A palindrome is a string that reads the same forwards and backwards. Examples are “radar” and “rotavator”. Write a program that accepts a String as input and outputs “Palindrome” if the String is a palindrome, and “Not Palindrome” otherwise.

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