What does this code print?
prices = {"apple": 2, "banana": 3}
print(prices["banana"])
3
What does this print?
word = "python"
print(word[0])
p
What does this print?
for i in range(3):
print(i, end=" ")
0 1 2
What does this print?
def double(x):
return x * 2
print(double(4))
8
f = open("notes.txt", "r")
text = f.read()
f.close()
Reads the entire text file into text
closes the file on exit.
What does this code print?
inventory = {"pen": 4}
inventory["pen"] += 2
inventory["book"] = 1
print(len(inventory), inventory["pen"])
2 6
What does this print?
word = "python"
print(word[1:4])
yth
What does this print?
total = 0
for n in [2, 4, 6]:
total += n
print(total)
12
Predict the output.
def add(a, b=5):
return a + b
print(add(3), add(3, 2))
8 5
You open an existing file using
open("results.txt", "w").
What happens to its old contents? What mode appends instead?
Old contents are truncated
use "a" to append.
Predict the output.
stock = {"tea": 3, "coffee": 5, "water": 2}
total = 0
for item in stock:
total += stock[item]
print(total)
10
Write first_letters(sentence) using a loop.
For "the code runs"
it should return "tcr".
def first_letters(sentence):
result = ""
for word in sentence.split():
result += word[0]
return result
Predict n and steps.
n = 20
steps = 0
while n > 3:
n /= 2
steps += 1
print(n, steps)
2.5 3
What does this print?
class Student:
def __init__(self, name, major):
self.name = name
self.major = major
s = Student("Alex", "CS")
s.major = "Math"
print(s.major)
Math
Name the exception for each expression:
A. int("hello")
B. [10, 20][5]
C. 10 / 0
A: ValueError
B: IndexError
C: ZeroDivisionError
What does the function return for "banana"?
def letter_count(word):
counts = {}
for ch in word:
counts[ch] = counts.get(ch, 0) + 1
return counts
print(letter_count("banana"))
{"b": 1, "a": 3, "n": 2}
A function get_indices(items, target)
returns every matching index.
What is get_indices(["a", "b", "a", "c", "a"], "a")?
[0, 2, 4]
How many pairs are printed? Name the first and last pair.
for row in range(2):
for col in range(3):
print(row, col)
6 pairs; first (0, 0), last (1, 2)
Fill the two blanks so Library starts empty and can add books.
class Library:
def __init__(self, name):
self.name = name
________
def add_book(self, book):
________
self.books = [] ;
self.books.append(book)
Assume scores.txt contains lines:
10, 20, 30.
What prints?
total = 0
with open("scores.txt") as f:
for line in f:
total += int(line.strip())
print(total)
60
Write find_oldest(people) without max(). Assume the dictionary is nonempty. It should return the key with the largest age. Test on {"Emma": 71, "Jack": 45, "Olivia": 82}.
def find_oldest(people):
oldest = None
best_age = float("-inf")
for name, age in people.items():
if age > best_age:
oldest, best_age = name, age
return oldest
Write flip_flop(word) to swap the two halves.
If length is odd, keep the center character between the swapped halves.
Examples: "abcd" -> "cdab", "abcde" -> "decab".
def flip_flop(word):
mid = len(word) // 2
if len(word) % 2 == 0:
return word[mid:] + word[:mid]
return word[mid+1:] + word[mid]+word[:mid]
Find TWO logic bugs in this hailstone function. It should stop at 1 and return every term.
def hailstone(n):
seq = [n]
while n == 1:
n = n // 2 if n % 2 == 0 else 3*n + 1
seq.append(n)
return seq
def hailstone(n):
seq = [n]
while n != 1:
n = n // 2 if n % 2 == 0 else 3*n + 1
seq.append(n)
return seq
A Time class stores hours and minutes.
What is Time(1,30) + Time(2,45)?
Show how to handle minutes >= 60 in __add__.
Total minutes = 1*60+30+2*60+45 = 255. hours=255//60=4; minutes=255%60=15.
Example __add__:
def __add__(self, other):
total = 60*(self.hours+other.hours)+self.minutes+other.minutes
return Time(total//60, total%60)
The code handles invalid text but crashes for 0. Identify the missing exception and explain how to keep asking until input is valid.
try:
n = int(input("Number: "))
print(10 / n)
except ValueError:
print("Bad number")
while True:
try:
n = int(input("Number: "))
print(10 / n)
break
except ValueError:
print("Bad number")
except ZeroDivisionError:
print("Cannot divide by zero")
The loop retries after either error and stops only when division succeeds.