How to Use Python If-Else Statements

Written by Coursera • Updated on

Learn how to work with if, else, if-else, and elif statements in Python.

[Featured image] Someone coding in python sits at a desk and works with a python if-else statement.

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.

Glossary

TermDefinition
ConditionIn 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.
LogicComputation follows facts and rules. In programming, logic is the automatic reasoning backed by those facts and rules.
SyntaxIn programming, syntax is the set of rules that defines the structure of a language.
ExpressionUnlike statements which are created to do something, expressions are representations of value. They are interpreted to produce some other value.
ifIf 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.
elseThe else statement contains the block of code that will execute if the condition from the if statement is false or resolves to zero.
if-elseAn if-else statement is used to execute both the true and false parts of a condition.
elifElif is the shortened version of else if. An elif statement is used to check the conditions for multiple expressions.

What is a Python if statement?

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: If Statement

How if statements work 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: If Statement

Try it yourself

PYTHON
1
2
3
4
x = 73
y = 55

#Write an if statement that prints "x is greater than y" when true

PYTHON
1
2
3
4
5
x = 73
y = 55

if x > y:
  print("x is greater than y")

What is a Python if-else statement?

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: if-else statement

How if-else statements work

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: If else Statement

Can you use if without else?

You can use if without else if you don’t want anything to be done when the if conditions are False.

How to write an if-else statement in Python

Here’s a breakdown of the syntax of an if-else statement:

PYTHON
1
2
3
4
if #expression:
    #statement
else:
    #statement

Try it yourself

PYTHON
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

PYTHON
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?

You can write an if-else statement in one line using a ternary operator, or, a conditional expression. Keep in mind that using this method in excess can make your code more difficult to read.

How to use an if-else statement in Python

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?

In a loop, you can use the jump 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.

What is elif in Python?

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: if elif else

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.

How if-elif-else else works in Python

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:

Elif statement

Can you have multiple elif blocks in python?

There is no limit to the number of elif blocks you use as long as there is only one if and one else per statement block.

What is a nested if-else statement?

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: nested if else

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.

How a nested if-else statement works in Python

Nested statements allow programmers to use minimal code by organizing information into layers where one object contains other similar objects. nested if else

Key takeaways

  • if, else, and elif are conditional statements used for decision-making operations.
  • You can use an if statement when you don’t need anything to be done if the condition is false.
  • You can use an else statement to provide further instructions for when a condition is false.
  • Use elif when you need to check for multiple conditions.
  • Nested if-else statements can be used when you have more than two options in your code.

Resources

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.

Continue building your Python expertise with Coursera.

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.


Written by Coursera • Updated on

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.

Learn without limits