Making Decisions
Understand why programs need to run different code based on what happens
Right now, PyQuiz ends with Correct: True or Correct: False. That is a raw Boolean value — the player has to mentally interpret it. A real quiz should say something useful.
That requires your program to make a decision: run one piece of code when the answer is correct, and different code when it is not. Python's if statement does exactly that.
The if statement
An if statement evaluates a condition. When the condition is True, Python runs the indented block below it. When it is False, Python skips that block.
temperature = 35
if temperature > 30:
print("It's hot outside!")
print("Checked.")It's hot outside!
Checked.35 > 30 is True, so Python runs the indented line. The last print runs regardless — it is not inside the if block.
Indentation defines the block
Python uses indentation — four spaces at the start of a line — to group code into a block. Every line inside an if block must use the same indentation.
is_member = True
if is_member:
print("Welcome back!")
print("You have 3 rewards.")
print("Visit us again.")If is_member were False, the two indented lines would be skipped. Only "Visit us again." would print.
if with a Boolean variable
You already have a Boolean variable: is_correct. You can use it directly as the condition:
if is_correct:
print("Correct!")This is equivalent to if is_correct == True:. Python reads a Boolean variable directly as a condition, so you never need to write == True.
In the next chapter, you will replace print(f"Correct: {is_correct}") with this pattern.