The Basics of Conditional Statements in Python
Like most programming languages, with Python, we can control the direction of code by leveraging control structures i.e. the blocks of code that control the flow of a program.
Note: This is similar to what we discussed in loops.
Conditionals as such, enable us to make decisions based on certain conditions(hence the name) and execute different blocks of code depending on whether these conditions are met.
Python If Statements
So, let's dive in and take a look at
if statements, as the first concept you'll likely be exposed to.
Generally speaking, the
if statement and other conditionals, rely on the use of booleans and operators to determine whether a particular condition is met. If it is, the specified block of code will be executed, like so:
language = "Python" if language == "Python": print("That's exactly right!") # Output: That's exactly right!
First off, we created a variable and assigned it a string value. Then, with the
if statement we checked if the value of
language is equal to
"Python" by using the equality operator (
==). Since the condition is true, the code inside the
if block executed, and the message
"That's exactly right!" was printed out as a result.
Indentation in Python Conditionals
In contrast to other languages, Python uses indentation to define the scope of code blocks. Simply put, this means that the code inside a block is indented a bit further to the right compared to the code outside of it.
x = 10 y = 5 if x > y: print("x is greater than y") # Correct indentation # Output: x is greater than y if x > y: print("x is greater than y") # Incorrect indentation # Output: IndentationError: expected an indented block after 'if' statement
The code in the second example isn't indented correctly, which means that it won't be considered part of the
if block, resulting in an error as seen in the output.
Short Hand Expressions
Starting from Python 2.5, it's possible to write one-line conditional statements using shorthand expressions. While the interpreter can read these statements, it's usually not the best practice, especially for more elaborate ones.
Let's convert the example from the previous section using the shorthand syntax:
x = 10 y = 5 if x > y: print("x is greater than y") # Output: x is greater than y
We can also use this in combination with the
else keyword which we'll cover in the subsequent sections:
num1 = 7 num2 = 4 print("num1 + num2 is even") if (num1 + num2) % 2 == 0 else print("num1 + num2 is odd") # Output: num1 + num2 is odd
Here, we have two variables
num2 with their respective values. We use the shorthand syntax to see if the sum of the numbers is even or odd. In this case, the sum of the numbers is
11, which is odd, so we get the output
"num1 + num2 is odd".
The Else Statement
In addition to
if statements, the
else keyword in Python signals the use of a catch-all condition if all previous conditions aren't met.
color = "red" if color == "blue": print("We chose blue") else: print("We'll stick with red") # Output: We'll stick with red
elif statement allows us to chain multiple conditions giving us additional flexibility in our programs. Let's demonstrate:
temperature = 75 if temperature > 90: print("It's hot outside.") elif temperature > 60: print("It's warm outside.") else: print("It's cool outside.") # Output: It's warm outside.
In this code, we're checking the temperature and printing a message that reflects the current weather conditions. With the help of the
elif statement, we're able to chain multiple conditions together, allowing us to accurately describe the temperature.
Conditional statements can also be nested. To illustrate that, we'll combine all mentioned statements and create a simple user input game.
level = int(input("Enter your level: ")) if level >= 10: if level >= 20: print("You are a Grand Wizard.") else: print("You are a Senior Wizard.") else: if level >= 5: print("You are a Junior Wizard.") else: print("You are an Apprentice Wizard.")
Initially, we ask the user to input their level as an integer. Depending on the value of the level, different print statements are executed. The code checks if the user's level is greater than or equal to 10. If so, then it checks if the level is greater than or equal to 20. If both conditions are true, then the output is
"You are a Grand Wizard." If only the first condition is true, then the output is
"You are a Senior Wizard.".
However, if the user's level is less than 10, the code moves to the next set of conditions. It checks if the level is greater than or equal to 5. If that's the case, then the output is
"You are a Junior Wizard.". If not, then the output is
"You are an Apprentice Wizard.".
The precedence of the conditions is from the outermost
if statement, to the innermost
else statement. The code checks each set of conditions in the order they are written and only executes the first true condition it encounters.
Official Documentation for Control Flow Tools in Python
Control Flow Basics in Python - A Guide to Loops