Practice reading, tracing, and writing Python conditionals that choose what code to run based on true or false conditions.
Read each problem carefully. Trace the code step by step when needed. Write complete answers and show your reasoning in the space provided.
Make decisions in code using if, elif, and else
CS - Grade 6-8
- 1
Trace this code: age = 12 if age >= 13: message = "teen" else: message = "not teen" What is the value of message? Explain why.
- 2
Write an if statement that prints "You can ride" when height is greater than or equal to 48.
- 3
Trace this code: temperature = 68 if temperature > 80: clothing = "shorts" elif temperature > 60: clothing = "light jacket" else: clothing = "coat" What is the value of clothing? Explain why.
- 4
What is the difference between if and elif in Python?
- 5
Fix the indentation error in this code: score = 95 if score >= 90: print("Great job") else: print("Keep practicing")
- 6
Trace this code: coins = 10 if coins > 20: prize = "large" elif coins > 5: prize = "small" elif coins > 0: prize = "sticker" else: prize = "none" What is the value of prize? Explain why.
- 7
Write a conditional that sets status to "passing" if grade is 60 or higher. Otherwise, it should set status to "not passing".
- 8
Trace this code: number = 7 if number % 2 == 0: result = "even" else: result = "odd" What is the value of result? Explain how the % operator is used here.
- 9
A game gives a player a bonus if both conditions are true: the player has at least 100 points and has collected a key. Write an if statement using and that prints "Bonus unlocked".
- 10
Trace this code: has_ticket = False is_vip = True if has_ticket or is_vip: entry = "allowed" else: entry = "denied" What is the value of entry? Explain why.
- 11
Rewrite this code using elif so that only one message can print: if score >= 90: print("A") if score >= 80: print("B") if score >= 70: print("C") else: print("Try again")
- 12
Trace this code: score = 92 if score >= 70: print("Passed") elif score >= 90: print("Excellent") else: print("Needs work") What prints? Explain why this may not give the message the programmer expected.
- 13
Put these conditions in the best order for a grade checker: score >= 90, score >= 70, score >= 80. Explain your choice.
- 14
Write a conditional for a weather app. If rain_chance is 70 or higher, set advice to "Bring an umbrella". If rain_chance is 30 or higher, set advice to "Maybe bring an umbrella". Otherwise, set advice to "No umbrella needed".
- 15
Find the bug in this code and explain how to fix it: password = "robot" if password = "robot": print("Access granted") else: print("Access denied")