If else statement in Python

if,elif,else Statements in Python help us to perform different actions based on the input

We can use elif and else to perform various actions based on the certain condition.
Syntax for if,elif and else statments


First Example

Let’s see a quick example of this:

output:

It was true!

Let’s add in some else logic:

a = False if a: print 'a is True!' else: print 'a is not true'

Output:

a is not true

Multiple Branches

Let’s check complete example

We write this out in a nested structure. please check code for if,elif,and else line up in the code.

We’ll reintroduce a comparison syntax for Python.

country = 'India' if country == 'India': print('Welcome to India!') elif country == 'China': print ('Welcome to the China!') else: print ('Please send us your location')

Output:

Welcome to India!

Please note that you can put as many elif as you want before putting one else statement

Let’s create two more simple examples for the if,elif, and else statements:

name="John" if name == 'George': print('Hey George') elif name == 'John': print ('Hey John') else: print ('What is your name?')

Output:

Hey John

Indentation

Please note that Indentation plays important role while writing python code,so need to be careful while putting spaces.
As you might know in java, we use {} to open and close if block but python uses Indentation to achieve that.
It is important to keep a good understanding of how indentation works in Python to maintain the structure and order of your code.

Leave a Reply

Your email address will not be published. Required fields are marked *