Learn how to work with if, else, if-else, and elif statements in Python.
Materials Required: Latest version of Python (Python 3), an integrated development environment (IDE) of your choice (or terminal), and a stable internet connection.
Prerequisites/helpful expertise: Basic knowledge of Python and programming concepts
Conditional statements allow us to control what a program does through logic. They enhance our programs by equipping them with decision-making capabilities. By the end of this tutorial, you will be able to use conditional statements like if-else to establish rules for your program to follow.
Term | Definition |
---|---|
Condition | In programming, a condition is something the computer can decide to be true or false. You can use conditions to provide different instructions to your program depending on the answer. |
Logic | Computation follows facts and rules. In programming, logic is the automatic reasoning backed by those facts and rules. |
Syntax | In programming, syntax is the set of rules that defines the structure of a language. |
Expression | Unlike statements which are created to do something, expressions are representations of value. They are interpreted to produce some other value. |
if | If is a common conditional statement. It dictates whether a statement should be executed or not by checking for a given condition. If the condition is true, the “if” block of code will be executed. |
else | The else statement contains the block of code that will execute if the condition from the if statement is false or resolves to zero. |
if-else | An if-else statement is used to execute both the true and false parts of a condition. |
elif | Elif is the shortened version of else if. An elif statement is used to check the conditions for multiple expressions. |
If
is a conditional statement used for decision-making operations. In other words, it enables the programmer to run a specific code only when a certain condition is met. The body of a Python if statement begins with indentation. The first unindented line marks the end. Remember that non-zero values are interpreted by Python as True
while None
and 0
are False
.
Example of an if
statement in Python:
First, the program evaluates your test expression. If it is true, the statement (or statements) will be executed. If it is false, the statement(s) will not be executed. The following flow chart demonstrates how an if statement works in Python:
1 2 3 4
x = 73 y = 55 #Write an if statement that prints "x is greater than y" when true
1 2 3 4 5
x = 73 y = 55 if x > y: print("x is greater than y")
An if-else
statement adds onto the function of an if
statement. Instead of simply refraining from executing statement(s) when the test expression is false, it provides alternative instructions for the program to follow. You’ll use indentation to separate the if
and else
blocks of code.
Example of an if-else
statement in Python:
The program evaluates your test expression. If it is true, the statement (or statements) will be executed. If it is false, the program will follow the alternative instructions provided. The following flow chart demonstrates how an if-else statement works in Python:
Can you use if without else?
if
without else
if you don’t want anything to be done when the if
conditions are False
.
Here’s a breakdown of the syntax of an if-else statement:
1 2 3 4
if #expression: #statement else: #statement
1 2 3 4 5
fruits = ["apple","orange","banana","grape","pear"] item = "cucumber" #Write an if-else statement that prints "[item] is a fruit" or "[item] is not a fruit" #depending on whether it's in the list of fruits
1 2 3 4 5 6 7
fruits = ["apple","orange","banana","grape","pear"] item = "cucumber" if item in fruits: print(item + " is a fruit") else: print(item + " is not a fruit")
How can you write an if-else statement in one line?
If you need a program to execute certain functions under specific conditions, you should use an if-else statement. Conditional statements like if-else are also known as conditional flow statements. This name comes from the ability to control the flow of your code on a situational basis. It can be helpful to think of conditional statements as a set of rules for Python to follow.
How can you exit out of an if-else statement?
break
. break
enables you to move the flow of program execution outside the loop once a specific condition is met. In a function, you can use return
or yield
to exit an if
statement.
Elif is the shortened version of else if. It enables you to perform a series of checks to evaluate the conditions of multiple expressions. For example, suppose the first statement is false, but you want to check for another condition before executing the else
block. In that case, you can use elif
to look for the other specified condition before Python decides which action to take. You can have any number of elif
statements following an if
statement.
Example of an if-elif-else statement:
Here, each number from -2 to 1 gets passed through the if-elif-else statement. Once a condition is true, the interpreter executes that block of code.
The interpreter will evaluate multiple expressions one at a time, starting with the if
statement. Once an expression is evaluated as True
, that block of code will execute. If no expression is True
, the else
statement will execute. The following flow chart demonstrates how an if-elif-else statement works in Python:
Can you have multiple elif blocks in python?
elif
blocks you use as long as there is only one if
and one else
per statement block.
In programming, “nesting” is a term that describes placing one programming construct inside another. For example, suppose you have more than two options to handle in your code. In that case, you can use a nested if-else statement to check conditions in consecutive order. Once a condition succeeds, it will move on to the next block. In the event that none of the conditions are true, the else clause will take effect.
Example of a nested if-else
statement:
The interpreter starts by evaluating the first number in the range, in this case, -2. Since the first if
statement is True
for -2, the interpreter will then evaluate the if
statement nested within the first if
statement. If True
again, it will execute that block of code. If False
, it will execute the nested else
statement. The process repeats for each number in the range.
Nested statements allow programmers to use minimal code by organizing information into layers where one object contains other similar objects.
if
, else
, and elif
are conditional statements used for decision-making operations.if
statement when you don’t need anything to be done if the condition is false.else
statement to provide further instructions for when a condition is false.elif
when you need to check for multiple conditions.if-else
statements can be used when you have more than two options in your code.Click here to find a downloadable cheat sheet for the tutorial above. You can also get involved with the Python community to stay current on tips and recent releases by subscribing to the free Python email newsletter or connecting with peers by joining the Python programming Slack channel.
Decision-making operations are essential programming concepts. You can practice using conditional statements by developing your own interactive game through a Guided Project like Python Basics: Create a Number Game from Scratch. Or, take the next step in mastering the Python language and earn a certificate from the University of Michigan in Python 3 Programming.
This content has been made available for informational purposes only. Learners are advised to conduct additional research to ensure that courses and other credentials pursued meet their personal, professional, and financial goals.