Week 4 of 8
Conditionals
The program starts making choices. Students use if, elif, and else so it does different things depending on the player's answer. They build a short quiz that checks answers and responds to each one - the core of any game that can be won or lost.
- Estimated time
- 55-60 minutes
- Project
- Trivia or Personality Quiz
The idea
A conditional lets the program choose. Python checks a condition - something that is either true or false - and runs the indented lines under it only if the condition is true. With if, elif, and else, a program can react one way to a right answer, another to a close answer, and another to a wrong one. That is how a game decides whether you scored, won, or lost.
What you will learn
- Write an if statement that runs only when a condition is true.
- Add elif and else to handle the other answers.
- Compare the player's answer to an expected value with ==.
- Fix the common mix-up between = and ==.
New words
- condition
- A question with a true or false answer, like answer == "Earth".
- if
- Runs the indented lines below it only when its condition is true.
- elif
- Checks another condition when the ones above it were false.
- else
- Runs when none of the conditions above it were true.
- ==
- Checks whether two values are equal (different from =, which stores a value).
Project: Trivia or Personality Quiz
Edit the starter code below and press Run to see it work. Use Reset starter code to go back to the original at any time.
Run your program to see the output.
Expected output
Which planet do we live on? Earth
Correct! 1 point.Mini challenge
Add a second question with its own if / else, so your quiz has two questions in a row.
Debugging challenge
Python shows an error on the if line. One equals sign stores a value in a variable. What do you use when you want to check whether two things are the same?
Broken code
answer = input("Which planet do we live on? ")
if answer = "Earth":
print("Correct!")Show solutionHide solution
Comparing two values needs two equals signs:
if answer == "Earth":Extension challenge
Turn it into a personality quiz: ask a would-you-rather question and print a different result for each choice using if, elif, and else.
Reflect
Your program now reacts differently to different answers. In your final game, what is one decision the program will need to make, and what should happen for each choice?
Teacher notes
Two focus points: indentation (the lines under an if must be indented) and = versus == (store versus compare). String comparison is exact and case-sensitive, which the elif line is there to spotlight. Let students hit the = / == error themselves - the message points right at it.
Facilitating this lesson? See the teacher & librarian guide for how to run it, common mistakes, and an offline backup activity.
Finished this lesson? Mark it complete to unlock the next week.