How to execute an if-else statement in Python

When writing a computer program, we often want it to execute different actions for different scenarios and conditions.

This is where the if-else statement is used.

if-else is a conditional statement where if the condition evaluates to true, then a certain part of the code is executed, else an alternative path is taken.

The else keyword catches anything which isn’t caught by the preceding if conditions.

Syntax

The following is the syntax for an if-else statement.

Example

Let’s start by taking a look at an example which checks if a variable a is greater than or less than b:

#change the value of "a" so it's less than b in order to execute the else statement
a = 50
b = 20
if (a > b):
#this code is executed only if a is greater than b
print "a is greater than b";
else:
#this code is executed if the preceding "if" condition evaluates to false
print "a is less than b";

The figure below illustrates the working of the above code using a flow chart:

if-else Flowchart
1 of 6
New on Educative
Learn any Language for FREE all September 🎉
For the entire month of September, get unlimited access to our entire catalog of beginner coding resources.
🎁 G i v e a w a y
30 Days of Code
Complete Educative’s daily coding challenge every day in September, and win exciting Prizes.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved