Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
if-else

How to execute an if-else statement in Python

Educative Answers Team

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

RELATED TAGS

python
if-else
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring