Exercises: Variables, Types, and Expressions
These exercises progress from concept checks to challenging coding problems. Start with Part A to verify your understanding, then work through the coding sections.
Difficulty Guide: - ⭐ Foundational (5-10 min each) - ⭐⭐ Intermediate (10-20 min each) - ⭐⭐⭐ Challenging (20-40 min each) - ⭐⭐⭐⭐ Advanced/Research (40+ min each)
Part A: Conceptual Understanding ⭐
A.1. In your own words, explain the difference between the "box" model and the "name tag" model of variables. Why does this chapter insist on the name tag model? Give a specific example where the two models would predict different behavior.
A.2. For each of the following values, state its Python type (int, float, str, or bool):
- a) 42
- b) 42.0
- c) "42"
- d) True
- e) 0
- f) ""
- g) 3.14
- h) "False"
A.3. Explain the difference between = and == in Python. Give an example of each and describe what it does.
A.4. What is the difference between / and // in Python? Give an example where they produce different results and explain why.
A.5. Which of the following are legal Python variable names? For the illegal ones, explain why.
- a) my_variable
- b) 2nd_place
- c) _private
- d) for
- e) student-name
- f) MAX_SIZE
- g) class
- h) camelCase
A.6. Without running the code, predict the output of each expression:
- a) 17 % 5
- b) 2 ** 5
- c) 10 / 3
- d) 10 // 3
- e) bool("")
- f) bool("0")
- g) int(7.9)
- h) type(True).__name__
Part B: Applied Analysis ⭐⭐
B.1. Predict the output of this code WITHOUT running it. Then run it to check your answer. If you were wrong, explain why.
x = 10
y = x
x = 20
z = x + y
print(f"x = {x}, y = {y}, z = {z}")
B.2. Predict the output of this code WITHOUT running it. Then run it to check.
a = "3"
b = "5"
print(a + b)
print(int(a) + int(b))
B.3. The following code has a bug. Identify the error, explain what type of error it is (SyntaxError, TypeError, ValueError, etc.), and fix it.
temperature = input("Enter temperature in Fahrenheit: ")
celsius = (temperature - 32) * 5 / 9
print(f"{temperature}°F = {celsius:.1f}°C")
B.4. Write the output of each line, or state what error it produces:
print(type(42))
print(type(42.0))
print(type("42"))
print(type(42 == 42.0))
print(type(int("42")))
B.5. Rewrite the following code to use augmented assignment operators wherever possible:
total = 0
total = total + 10
total = total + 25
total = total - 5
total = total * 2
total = total / 3
print(total)
Part C: Coding Exercises ⭐⭐
C.1. Write a program that asks the user for their name and birth year, then calculates and prints their approximate age. Use an f-string for the output. Example:
Enter your name: Elena
Enter your birth year: 2004
Elena, you are approximately 21 years old.
C.2. Write a program that converts a temperature from Fahrenheit to Celsius. The formula is: C = (F - 32) * 5 / 9. Display the result with 1 decimal place.
Enter temperature in Fahrenheit: 98.6
98.6°F = 37.0°C
C.3. Write a program that takes a number of seconds as input and converts it to hours, minutes, and seconds. Use // and %.
Enter total seconds: 3661
3661 seconds = 1 hour(s), 1 minute(s), 1 second(s)
C.4. Write a program that calculates the area and circumference of a circle given the radius. Use pi = 3.14159. Display results with 2 decimal places.
Enter the radius: 5
Area: 78.54
Circumference: 31.42
C.5. Write a program that asks for a price and a tip percentage, then calculates and displays the tip amount and total bill.
Enter the bill amount: 85.50
Enter tip percentage: 20
Tip amount: $17.10
Total: $102.60
C.6. Write a program that creates a nicely formatted "receipt" using f-string alignment. It should display at least 3 items with prices, aligned in columns, and show the total at the bottom.
Example output:
==============================
RECEIPT
==============================
Coffee $ 4.50
Sandwich $ 12.99
Cookie $ 3.25
------------------------------
TOTAL $ 20.74
==============================
Part D: Debugging Practice ⭐⭐-⭐⭐⭐
D.1. Each of the following code snippets contains exactly one bug. Find it and fix it.
a)
student name = "Elena"
print(f"Student: {student name}")
b)
price = 19.99
tax_rate = 0.08
total = price + price * tax_rate
print("Your total is: $" + total)
c)
num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
average = num1 + num2 / 2
print(f"Average: {average}")
d)
x = 10
y = 0
result = x / y
print(f"Result: {result}")
D.2. A student wrote this code and says "it doesn't work." The program runs but produces the wrong answer. Find the logical error and fix it.
# Calculate weighted average:
# Homework 40%, Midterm 30%, Final 30%
homework = 85
midterm = 90
final = 78
weighted = homework * 40 + midterm * 30 + final * 30
print(f"Weighted average: {weighted}")
D.3. This code runs without errors but has a subtle problem. What is it, and why might it cause trouble later?
l = [1, 2, 3]
O = 0
I = 1
print(l[O])
print(l[I])
Part M: Multiple Representations ⭐⭐
M.1. Draw a memory diagram (using the name tag style from section 3.10) showing the state of memory after each line executes:
x = 100
y = x
z = 200
x = z
Show the diagram after all four lines. Which variables point to the same object?
M.2. Fill in the following table by converting each value to every other type (or writing "Error" if the conversion fails):
| Original Value | int() |
float() |
str() |
bool() |
|---|---|---|---|---|
42 |
— | ? | ? | ? |
3.7 |
? | — | ? | ? |
"10" |
? | ? | — | ? |
"" |
? | ? | — | ? |
True |
? | ? | ? | — |
"hello" |
? | ? | — | ? |
Part E: Extension Challenges ⭐⭐⭐-⭐⭐⭐⭐
E.1. The Swap Problem ⭐⭐⭐
Write a program that swaps the values of two variables WITHOUT using a third temporary variable. (Hint: Python has a way to do this in one line.)
a = "first"
b = "second"
# Your code here — swap a and b
print(f"a = {a}, b = {b}") # Should print: a = second, b = first
E.2. The Change Calculator ⭐⭐⭐
Write a program that takes a purchase price and the amount paid, then calculates the change in the fewest number of bills and coins. Use only // and %.
Purchase price: $17.38
Amount paid: $20.00
Change: $2.62
1 x $1 bill
2 x quarter
1 x dime
0 x nickel
2 x penny
E.3. BMI Calculator ⭐⭐⭐
Write a program that calculates Body Mass Index. The formula is: BMI = weight_kg / (height_m ** 2). Accept weight in pounds and height in feet/inches, and convert internally. Display the BMI with 1 decimal place and the weight category:
- Under 18.5: Underweight
- 18.5 to 24.9: Normal
- 25.0 to 29.9: Overweight
- 30.0 and above: Obese
(Note: you'll need if statements from Chapter 4 for the categories. For now, just calculate and display the BMI value.)
E.4. The ID Experiment ⭐⭐⭐⭐
Python caches small integers for performance. Write a program that determines the range of cached integers on your system. Test integers from -10 to 300 by creating them in two different ways and comparing their id() values:
for i in range(-10, 301):
a = i
b = int(str(i)) # Force Python to create a potentially new object
if id(a) != id(b):
print(f"First non-cached integer: {i}")
break
Run this and report your findings. Then research: why does Python cache these specific integers?
E.5. Data Type Explorer ⭐⭐⭐
Write a program that takes any user input and displays:
- The original string
- Its length
- Whether it can be converted to an int (try/except — look ahead to Chapter 11, or just try and see what happens)
- Whether it can be converted to a float
- Its truthiness (bool() value)
Run it with these inputs and record the results: "hello", "42", "3.14", "", "0", "True"
Solutions
Selected solutions are available in Appendix G.