Conditional Execution
Quiz: counts toward finishing the lesson. Check: just for practice.
if Statements
The if statement lets our code take different branches depending on whether a condition is True or False. Here's a simple example:
The else case is optional. Both the if and else cases can contain as many statements as needed:
Indentation matters in Python. Many languages use it only for readability, but in Python it determines which statements belong together. The code for an if statement is indented underneath it, and returning to the original indentation ends the block.
Python does not require a specific number of spaces, but 4 is the usual choice (unless the existing code uses a different amount).
Nested if statements and elif
You can also have nested if statements (if statements inside other if statements):
The indentation tells Python which ifs and elses go together. This much nesting is hard to read, so the more common way to write this example is:
Here elif is short for else if.
Check your understanding. Predict the result. Look at what the first if does to x before the second test runs.
x = 10
y = 0
if x > 5:
x = 2
y += 1
if x > 1:
y += 10
Predict what each variable holds after the program finishes. The program is not run for you. Change the values below to your predictions:
final_xis the value ofxat the endfinal_yis the value ofyat the end
Hint 1
The second if is a new test, and it reads x as it is after the first block ran.
Extra note on indentation
In Python, indentation is required and must be consistent. Every line in a block must have the same indentation. Avoid mixing spaces and tabs, because they can look the same but count differently.
Changing the indentation of a line can change what your program does. For example, if a line meant to run only when a condition is met is indented incorrectly, it may run every time, or never.
Quizzes
- Write a function named
range_labelthat takes one numeric parameter. It returns"in range"if the value is between 50 and 100 (inclusive) and"out of range"otherwise.
- Write a function named
size_labelthat takes one numeric parameter. It returns"small"if the value is less than 10,"medium"if it is at least 10 but less than 50, and"large"if it is at least 50.
- Write a function named
number_wordthat takes an integer parameter. If the integer is a value from 1 to 5, it returns the English word for that number. Otherwise it returns"input not recognized".
- Predict the result. Find which inner branch runs, then see what the last test reads.
x = 7
y = 0
if x > 5:
if x > 8:
y = 1
elif x > 6:
y = 2
x += 10
else:
y = 3
else:
y = 4
if x > 10:
y += 5
Predict what each variable holds after the program finishes. The program is not run for you. Change the values below to your predictions:
final_xis the value ofxat the endfinal_yis the value ofyat the end
Hint 1
Only one branch of a chain runs. Then the final if sees the changed x.