Python Course 13: Tests and Questions

Revision Questions

There will be test next week on the work we’ve done so far.  Here are some questions for you to practice:

  1. Prompt the user to enter their (name). Print out “Hello” (name) “I hope you’re well”
  2. Prompt the user to input two numbers.  Output the average of those two numbers.
  3. Prompt the user to enter their age.  If they are aged between 4 and 16 output “You should be at school”
  4. Create a list called months, containing the months in the year.  Now print out all the months, one after the other
  5. Use a for loop to print out the following numbers: 7,14,21, … 63,70,77
  6. Convert the String “I never saw a purple cow” to uppercase and output the resulting string.

Autumn 1 Test

Write programs to solve the following. Submit your answers as a word document here.

  1. Prompt the user “What’s the capital of France?” If they enter “Paris” print out “Correct!” otherwise print “Wrong!”
  2. Create a list containing the following houses “Rowntree”, “Wrigley”, “Lord”, “Mothersill”, “Birley”, “Hall”.  Print out the list, one after the other.
  3. The area of a triangle is half x base x height.  Prompt the user to enter the base and height of a triangle and then print out the area.
  4. Use a for loop to print out the 6 times table up to 12 x 6. Print it in the format “4 x 6 = 24” 
  5. Create a list containing the days of the week. Use string handling functions to print out the list in uppercase and then in lowercase.

Extension

Draw a house using turtle graphics. You get 1 point for each of the following features

  • Roof
  • Door
  • 1 Window
  • 2 Windows
  • Chimney
  • Garden Path

Code Golf: Songs

In code golf, the aim is to write a program with the lowest number of characters.

How short can you make the program to print out one of  the following songs?

Autumn 2 Test

Do the following questions.  Submit your code and output as screenshots on a Word Document here.

  1. Prompt the user to enter the number of bits in a byte.  If they answer 8 print correct, otherwise print “try again.”  The program should loop until the user gets the correct answer.
  2. Use a for loop to print out the 5 times table.
  3. Create a list containing the following names:  Ann, Sue, Andy, Steve, Charlotte, Craig, Mark, Raza.  Now print out all the names using a for loop.
  4. An online sweet shop charges for shipping as follows:  One box, £5.99; two to five boxes £7; more than five boxes, free.   Prompt the user to enter the number of boxes bought and output the shipping cost.
  5. In Python, open a file object with write access to a file called “cheese.txt”.
    1. Write the following three names to the file: Cheddar, Lancashire, Mozzarella
    2. Close the file object

Revision Questions 2

The Problems

Write programs to do the following. Take screenshots of your code and upload them as a word document.

  1. Prompt the user to enter the number of bits in a byte. If they answer 8 print correct, otherwise print “try again.” The program should loop until the user gets the correct answer.
  2. Use a for loop to print out the 5 times table.
  3. Create a list containing the following names: Ann, Sue, Andy, Steve, Charlotte, Craig, Mark, Raza. Now print out all the names, one after the other
  4. Create a dictionary called french containing the following data: chien – dog, chat – cat, vache – cow, cheval – horse, mouton – sheep. Loop through the keys printing out the associated values.

Extension

  1. Follow the link to find the text of the poem THE RIME OF THE ANCIENT MARINER: http://www.textfiles.com/etext/FICTION/coleridge-rime-371.txt
  2. Copy the text into a file called rime.txt
  3. Write a python program that reads rime.txt into a list.
  4. Modify your program so that it counts how many lines there are in the list.
  5. Modify the program further so that it counts how many words there are in the list.
  6. Modify the program so that it counts how many times the word “the” appears.
  7. Can you count the frequency of letters in the poem? In other words, how many times does ‘a’ appear, ‘b’ appear, ‘c’ appear and so on…

Time in Words

Given a time in numbers we can convert it into words. For example:

  • 5:00 Five o’clock
  • 5:10 Ten minutes past five
  • 5:15 Quarter past five
  • 5:30 Half past five
  • 5:45 Quarter to six
  • 5:47 Thirteen minutes to six

Write a program which inputs two numbers (the first between 1 and 12, the second between 0 and 59 inclusive) and then prints out the time they represent, in words. You should follow the format of the examples above. Your program should then terminate.

Sample run
Hours: 4
Minutes: 12
Twelve minutes past four

Partial Solution

The following code should start you off. It will answer some times correctly but not all. You will have test the code and then add extra lines to fix it.

times = ["o'clock","One","two","three","four", "five", "six",
	 "seven","eight","nine","ten","eleven","twelve","thirteen","fourteen",
	 "quarter","sixteen","seventeen","eighteen","nineteen","twenty",
	 "twenty one","twenty two","twenty three","twenty four",
	 "twenty five","twenty six","twenty seven","twenty eight",
	 "twenty nine","Half past"]

hours = 4
minutes = 12

if minutes>30:
    print(times[60-minutes]+ " to " + times[hours])
else: 
    print(times[minutes] + " past " + times[hours])

Test the code with examples given at the top of the screen.

The test data at the top of the screen is not exhaustive. Think of some other times that are not covered. Adjust your code accordingly.

Have you considered all the options? There is some test data at the bottom of this page…

Paste your completed code to a word document

Extension

  1. Which times, when written in words, have the longest length?
  2. Write a program that outputs times in 24 hour clock format, eg 13 hours 0 minutes outputs 13:00 and 9 hours 15 mins prints out 09:15.  You must include the leading 0s! 

Time in Words Test Data

  1. 3 o’clock
  2. 6:25
  3. 7:45
  4. 12:00 (noon)
  5. 0:00 (midnight)
  6. 12:55
  7. 0:05
  8. 0:30

Python Course 12: Robust and Secure Programming

  • Robust programming means writing programs that can cope with errors. One example would be to use data validation to avoid incorrect input.
  • Secure programming means writing programs that use security features such as passwords

You must check your validation with normal, boundary and erroneous data.

Examples

NOTE: All the following use while loops, not ifs! Why?

The following code checks that a value is entered

ans = input("Enter your choice")

while ans == "":
    ans = input("You must enter a value")

Test data: Erroneous: “” Normal: “Pizza”

The following code checks that the username is at least 6 characters long

ans = input("Choose your username")

while len(ans) <6:
    ans = input("Username must be at least 6 characters")

Test data: Erroneous: “Pizza” Normal: “Hamburger”

The following checks that someone is aged between 11 and 18

age = int(input("Enter your age: "))

while age < 11 or age > 18:
    age = int(input("Age must be between 11 and 18 "))

Test data: Erroneous: 8 Boundary: 11 Normal: 15

The following checks that someone is in a year 9 form

forms = ["9b","9h","9bh","9l","9m","9lm","9r","9w","9rw"]

f = input("Enter your form group: ").lower()

while f not in forms:
    f = input("Not a valid form group: ").lower()

Test data: Erroneous: “8qt” Normal: “9l”

Exercise

Write code to perform the following validation checks.

  1. Jockey club names cannot be more than 18 characters long. Write a validation check for these names. Test with the normal data “Ariel” and the erroneous data “supercalifragilisticexpialidocious”
  2. Modify your answer to question 1 so that blank names are also rejected
  3. Police officers in the UK are aged between 18 and 60. Write a validation check for this. Test your code with the following data: 25, 60 and 81
  4. A cafe sells the following drinks: tea, black coffee, white coffee, hot chocolate, lemonade. Write a validation check for the above drinks.

Extension

The following code demonstrate the instartswith and endswith functions

>>> s ="I never saw a purple cow"
>>> s.endswith("cow")
True
>>> s.startswith("I")
True
>>> "never" in s
True

Use them to write validation checks for the following:

This is an example of a URL: http://blue-coat.org

  1. URL check: does it end in .com or .org?
  2. Does it start with http:// or https://
  3. Simple check for email: does the string contain an ‘@’?
  4. More complex email check: does a string contain ‘@’ and end with .com or .org?

Python Course 11: Dictionaries and REPLs

Copy the following code into your IDE

terms = {"bit":"binary digit", "byte":"8 Bits", "kilobyte":"1000 Bytes"}

def Main():
    # The input output loop
    ans = ""
    while ans != "end":
	print("L to Look up a Word")
	print("E to Enter new Word")
	print("end to exit the program")

	ans = input("What do you want to do?")

	if ans == "L":
	    lookup()

	elif ans == "E":
	    enter()

	else:
	    print("I don't understand that command")


def lookup():
    word = input("Enter the word you wish to look up")
    if word in terms:
	print(terms.get(word))
    else:
	print("Word not in dictionary")


def enter():
    word = input("Enter new word")
    definition = input("Enter the definition")
    terms[word] = definition


Main()

Revision Helper Exercise

  1. Run the above code. Make sure you understand how it works
  2. Follow the link to see Computing Key Terms. Add some of these to your dictionary.
  3. Add an option to the Main() loop to print out all the key values in the terms dictionary. Implement that option

Python Course 10: Dictionaries

Sample Code

# Create a dictionary
graphics = {"pixel": "Picture Element", "resolution": "Number of pixels on screen", "bitmap":"Image composed of pixels"}

# Print a value
print(graphics["pixel"])

# Loop through the keys
for key in graphics:
    print(key)

# Loop through keys and values (note the .items()!)
for key, value in graphics.items():
    print(key, " is ", value)

# Add an entry to the dictionary
graphics["colour depth"] = "Number of bits used to represent each pixel"

# Check to see entry
print(graphics)

Exercise

  1. Create a python file called dict.py
  2. Create a dictionary called sound containing the following terms: analogue – continuously variable data, digital – data stored as bits, sample – measure of amplitude at a point in time
  3. Print out the value of sample
  4. Add the following two definitions to the dictionary: sampling rate – number of samples taken in a second, Sample resolution – number of bits per sample.
  5. Loop through all the keys in the dictionary and print them out.

Extension

Choose a different subject. Create a key terms dictionary with at least 5 items for that subject. Print out all the keys and values

Python Course 9: File Objects

Write to Disk

my_file = open("sample.txt","w")
my_file.write("Sausage\n")
my_file.write("Egg\n")
my_file.write("Chips\n")

my_file.close()
my_file = open("hello.txt","w") 
lines_of_text = ["Sausage\n","Egg\n","Chips\n"] 
my_file.writelines(lines_of_text) 
my_file.close() 

Read from Disk

Read One Line from Disk

my_file = open("sample.txt","r")
print(my_file.readline())
my_file.close()

Read all Lines and Strip Line Breaks

file = open("sample.txt", "r") 
for line in file: 
    print(line.rstrip('\n'))

or

file = open("sample.txt", "r") 
for line in file: 
    print(line, end = "")

Read Lines into a List

my_file = open("sample.txt","r")
print(my_file.readlines())

my_file.close()

Exercise

  1. In Python, open a file object with write access to a file called “people.txt”.
    1. Write the following three names to the file: George, Alison, Jasprit.
    2. Close the file object
    3. Open the file in Notepad and check the names were written correctly.
  2. Use Notepad to create a text file called “shopping.txt”. Add the following items, one item per line: milk, sugar, flour, 6 eggs, butter, raisins, raspberry jam
    1. In Python, open a file object with read access to shopping.txt
    2. Use a for loop to print out the items in your shopping list
  3. In Python, open a file object with write access to a file called “todo list.txt”
    • Write a question loop that will prompt the user “Add another item”
    • If the user enters “N” the loop will terminate and the file object will be closed.
    • Otherwise, the item entered will be written to the file object
    • Run your program and check that the todo list is created.

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”]