- Define "control structure."
- Use the
ifkeyword to create a simple decision block. - Understand the critical role of indentation in Python for defining code blocks.
Creating a Fork in the Road
In the last lesson, we learned how to ask a question that results in True or False. Now, we'll use that to control the "flow" of our program. A control structure is a block of code that can change the path of execution. The simplest control structure is the if statement.
The if Statement
An if statement tells the computer: "If this condition is true, then execute the following block of code. Otherwise, just skip it."
if some_condition_is_true:
This code is indented, so it only runs if the condition is True.
do_this_action() do_another_action()
This code is NOT indented, so it runs normally after the if block.
carry_on_with_program()
In Python, the colon (:) at the end of the if line and the indentation (the space at the beginning of the lines below it) are extremely important. The indentation is how Python knows which lines of code belong to the if statement. All the code inside the indented block is conditional. The first line of code that is "un-indented" signals the end of the if block.
Live Example: The Age Checker
The code below asks for your age. If, and only if, the age is 18 or greater, it will print a special message. Notice that the final "Thank you" message is not indented, so it prints every time.
Your challenge: Run the program twice. First, enter an age like 25. Second, enter an age like 14. Watch how the output changes!
An if statement is like a one-way fork in the road. It gives the program a chance to do something extra, but it doesn't provide an alternative path. If the condition is false, the program doesn't do anything special; it just continues on the main road. In the next lesson, we'll learn how to create a true two-way fork.
Interactive Sandbox
Use this space to practice writing code and complete the "Your Turn" activities above.