Quiz 2 Study Guide
This page contains a list of things you should know before taking Quiz 2.
Booleans
We introduced booleans, a type for the “truth values” True and False. You should know how to create True and False values from various Python operators and how to describe conditions using Python expressions.
Exercises
For each of the following expressions, is the result True or False? Why?
5 > 44 >= 413 % 2 == 15 != 3True and FalseTrue or TrueFalse and False(3 > 4) or (4 < 5)- (5 in range(5)) or (3 in “3”)
For each of the following conditions, write a Python expression which is True when that condition holds.
- A variable
xcontains the value9. - A variable
ycontains a number which is strictly greater than the number contained in a variablez. - A variable
scontains the empty string. - A variable
scontains a string that appears somewhere inside of the string in a variablet. - A variable
scontains no more than ten characters. - The sum of the contents of the variables
xandyis no greater than 10.
if statements
We introduced branching control flow in the form of if statements. You should know how if statements are executed; you should also be familiar with the associated elif and else blocks.
Exercises
Predict (without the use of a computer) what each of the following programs will print.
-
for n in range(0,10): if n > 4: print n else: print "Small" -
for word in ["These","are","words","from","a","sentence"]: if len(word) > 4: print word -
for n in range(1,21): if n % 3 == 0: print 3 elif n % 5 == 0: print 5 if n % 7 == 0: print 7
Debugging
As with the last quiz, you should know how to find mistakes in small programs. Given a description of what a program should do and the program itself, you should be able to identify how it can be fixed. (Hint: there may be more than one thing wrong with a program.)
Exercises
For each of the following descriptions, a program is provided which is an incorrect implementation. Identify how that implementation can be corrected to conform with the description.
#1
Description
This program was intended to print all of the squares between 1 and 25 (inclusive).
Program
for n in range(5):
print n*n
#2
Description
This program was intended to print only the vowels from the string provided by the user.
Program
phrase = raw_input("Please enter a phrase: ")
output = ""
for c in phrase:
if c == ["a","e","i","o","u"]:
output += c
print output
#3
Description
This program was intended to print all of the numbers between 1 and 1000 (inclusive) which are divisible by both 3 and 5.
Program
for n in range(1,1001):
if n % 3 and 5 == 0:
print n
#4
Description
This program sums the cubes of the numbers between 1 and 10 and then prints the result.
Program
total = 0
for n in range(1,11):
total = n ** 3
print total