"If" can be understood as metaphorical English "what if" which most people use in their day to day life. What if this doesn't happen? If this car doesn't start, use the other one. We are loaded with numerous examples from across the globe on usage of if
. Decision making is one of the most basic requirement of any kind of programming language. Majority of the programming languages have control statements and you will find majority of them use the keyword if in their control statements.
In python we can use if..elif..else
statement for such conditional checks. So in this tutorial we will learn about python if else statement along with their respective syntax using multiple examples.
What is indentation? Why is it important?
- You must be familiar with the term "indentation" before we go ahead.
- Indentation is one of Python's singular features and is used everywhere in Python.
- Python uses indentation to determine how a line, or group of lines, is related to the rest of the program.
- Basically, it uses whitespace to force you to write neatly formatted code with a clear visual structure.
- One of the advantage here is readability. It's clearer and easier to read code when it all shares the same indentation, meaning the block of code belongs to the same branch.
- If the indentation is not followed properly then you may get an "
IndentationError
" error. - Unlike some of the other programming language we do not have a closing function for the
if block
. - For example in perl we use
{}
curly braces to define the start and end of the block, in shell we use "fi
" to end the block. - So indentation is important, anything under this "
if condition:
" block which starts with indentation would be part of thatif
statement.
Python if statement
With python if statement we can only check for single condition only.
Syntax
The syntax to use python if statement would be:
if condition:
statements-1
- Here we have a single conditional check and if the condition returns
True
then thestatements-1
will be executed. - If the condition returns
False
then theif block
will be ignored True
value means zero exit status whileFalse
boolean value means non-zero exit status.- There is no way to define an end of
if block
, you must put all theif block
statements under same indentation
For example:
if condition:
statements-1
statements-2
statements-3
Here as you observe, all the statements under the if block
are following the same indentation value. In this example, statements-3
will be considered outside the if block
and will be executed irrespective of the if
condition Return value.
if condition:
statements-1
statements-2
statements-3
Flowchart
This flowchart will give you a graphical representation of the syntax value:
Python Script Example
In this example we will ask user to provide any integer value. For now if you are not familiar with try
and except
, you can ignore that function. We have added that to make sure, user is allowed to enter only integers.
if
condition will check if the provided number is greater than 5.- If this comparison returns
True
, i.e. provided number is greater than 5 then the script will enter theif block
- If the provided number is less than 5, then the condition will return
False
hence theif block
will not be executed - I am using
print()
to help you understand the content ofif block
, observe the indentation. All the statements in theif block
are having the same indentation - The last
print
statement i.e. "Now we are in main function
" will be called irrespective of the condition value because it is called outside theif block
#!/usr/bin/env python3 import sys # Only integers allowed try: num = int(input("Enter any number: ")) except: print("Only numbers allowed") sys.exit(1) # if block condition if num > 5: # if block starts, notice the indentation print("You have entered the if block") print("The provided number is greater than 5") print("Exiting if block") # if block ends, notice the indentation print("Now we are in main function")
Output (if
condition returns True
):
# python3 /tmp/if_else_example.py
Enter any number between 1-10: 6
You have entered the if block
The provided number is greater than 5
Exiting if block
Now we are in main function
Output (if
condition returns False
):
# python3 /tmp/if_else_example.py
Enter any number: 4
Now we are in main function
Python if..else statement
As you understood correctly, this adds an else
statement which means now we have an option to execute commands if the condition returns False
Syntax
The syntax to use python if..else
statement would be:
if condition:
statements-1
else:
statements-2
- From the syntax you can understand the benefit we get with
if..else
statement, if the condition returnsTrue
then theif block
is executed but if the condition returnsFalse
thenelse block
will be executed instead of going to the main script True
value means zero exit status whileFalse
boolean value means non-zero exit status.- There is no way to define an end of
if..else
block, you must put all theif..else
block statements under same indentation
Flowchart
The syntax is explained in the form of a flowchart with single if..else
statement
Python Script Example
- We will continue to use our existing example, and we will add one additional
else block
- Observe the indentation, once the
if block
ends, we switch back to the starting of line where theif block
had started. - Both
if
andelse
condition should start at the same point of line - Next provide indentation of all the statements in the
else block
similar toif block
- Now if the provided number is greater than 5, then the if condition returns
True
and theif block
will be called. - But if the provided number is less than 5, then if condition returns
False
and theelse block
will be executed - The last
print
statement i.e. "Now we are in main function
" will be called irrespective of the condition value because it is called outside theif..else
block
#!/usr/bin/env python3 import sys # Only integers allowed try: num = int(input("Enter any number: ")) except: print("Only numbers allowed") sys.exit(1) # if block condition if num > 5: # if block starts, notice the indentation print("You have entered the if block") print("The provided number is greater than 5") print("Exiting if block") # else block else: # else block starts, notice the indentation print("You have entered the else block") print("The provided number is less than 5") print("Exiting else block") # if..else block ends, notice the indentation print("Now we are in main function")
Output (if
condition returns True
):
# python3 /tmp/if_else_example.py
Enter any number: 6
You have entered the if block
The provided number is greater than 5
Exiting if block
Now we are in main function
Output (if
condition returns False
):
# python3 /tmp/if_else_example.py
Enter any number: 4
You have entered the else block
The provided number is less than 5
Exiting else block
Now we are in main function
Python if..elif..else statement
It is possible that we have more than 2 conditions, in such case we can use if..elif..else
condition.
Syntax
The syntax to use if..elif..else
statement would be:
if condition-1:
sequence of statements-1
elif condition-n:
sequence of statements-n
else:
default sequence of statements
- Here, in the syntax, we are illustrating a series of branching statements under different conditions which is also called conditional branching in any language.
- First, we encounter an
if block
and if the condition inside theif block
is satisfied or becomesTrue
, only then will theif block
be executed. - If while executing the condition inside the
if block
is not satisfied i.e. returnsFalse
, then the control is handed over to the immediate condition statement, that is,elif block
, where the condition would be checked differently - Finally, we have the
else block
, where if all the conditions before theelse
condition fail, then theelse block
will process the code.
Flowchart
The syntax is explained in the form of a flowchart with single if..elif..else
statement
Python Script Example
- We will continue to use our existing example, and we will add one
elif block
betweenif..else block
- In our
elif block
we add a condition to check if provided number is equal to 5. If this returnsTrue
then theelif block
will be executed - If both
if
andelif block
returnsFalse
then theelse block
will be executed - The last
print
statement i.e. "Now we are in main function
" will be called irrespective of the condition value because it is called outside theif..elif..else block
#!/usr/bin/env python3 import sys # Only integers allowed try: num = int(input("Enter any number: ")) except: print("Only numbers allowed") sys.exit(1) # if block condition if num > 5: # if block starts, notice the indentation print("You have entered the if block") print("The provided number is greater than 5") print("Exiting if block") elif num == 5: # elif block starts, notice the indentation print("You have entered the elif block") print("The provided number is equal to 5") print("Exiting elif block") else: # else block starts, notice the indentation print("You have entered the else block") print("The provided number is less than 5") print("Exiting else block") # if..elif..else block ends, notice the indentation print("Now we are in main function")
Output (if condition for if block
returns True
):
# python3 /tmp/if_else_example.py
Enter any number: 6
You have entered the if block
The provided number is greater than 5
Exiting if block
Now we are in main function
Output (if condition for elif block
returns True
):
# python3 /tmp/if_else_example.py
Enter any number: 5
You have entered the elif block
The provided number is equal to 5
Exiting elif block
Now we are in main function
Output (if condition for both if
and elif block
returns False
):
# python3 /tmp/if_else_example.py
Enter any number: 4
You have entered the else block
The provided number is less than 5
Exiting else block
Now we are in main function
Python Nested if statement
We can add nested if..elif..else
statement inside if..elif..else blocks
. The existing syntax which I showed above can be used, the only important point to note is that you must use proper indentation within the blocks or else you may get indentation error
Python Script Example
- Let us use our existing example, I will add nested
if..elif..else block
inside theelse block
- The first
if condition
checks if the provided number is less than 5 or else returnsFalse
- The
elif condition
checks if the provided number is equal to 5, if this returnsFalse
thenelse block
is executed - Inside
else block
we had addednested if..elif..else condition
- So if num is equal to 1 then
nested if block
will be executed, if this returnsFalse
thennested if..elif block
will be executed. lastly if bothnested if..elif
returnsFalse
then thenested if..elif..else block
will be executed - The last
print
statement i.e. "Now we are in main function
" will be called irrespective of the condition value because it is called outside the if..elif..else block
#!/usr/bin/env python3 import sys # Only integers allowed try: num = int(input("Enter any number: ")) except: print("Only numbers allowed") sys.exit(1) # if block condition if num > 5: # if block starts, notice the indentation print("You have entered the if block") print("The provided number is greater than 5") print("Exiting if block") elif num == 5: # elif block starts, notice the indentation print("You have entered the elif block") print("The provided number is equal to 5") print("Exiting elif block") else: # else block starts, notice the indentation print("You have entered the else block") if num == 1: # nested if block starts, notice the indentation print("You have entered into nested if block") print("The provided number is equal to 1") print("Exiting nested if block") elif num == 2: # nested if..elif block starts, notice the indentation print("You have entered into nested if..elif block") print("The provided number is equal to 2") print("Exiting nested if..elif block") else: # nested if..elif..else block continues, notice the indentation print("The provided number is less than 5") print("Exiting nested if..elif..else block") # if..elif..else block ends, notice the indentation print("Now we are in main function")
Output (if condition for nested if block
returns True
):
# python3 /tmp/if_else_example.py
Enter any number: 1
You have entered the else block
You have entered into nested if block
The provided number is equal to 1
Exiting nested if block
Now we are in main function
Output (if condition for nested if block
returns False
and nested if..elif block
returns True
):
# python3 /tmp/if_else_example.py
Enter any number: 2
You have entered the else block
You have entered into nested if..elif block
The provided number is equal to 2
Exiting nested if..elif block
Now we are in main function
Output (if condition for both nested if
and nested if..elif block
returns False
):
# python3 /tmp/if_else_example.py
Enter any number: 3
You have entered the else block
The provided number is less than 5
Exiting nested if..elif..else block
Now we are in main function
Python logical operator with if condition
In the if condition
, you can define multiple conditions using python logical operators. Use logical and
, or
, not
operator in your python scripts to define multiple condition. These operators can be used with if
or elif
condition
In all the syntax I shared above, replace condition with
- For and operator:
condition-1 and condition-2
- For or operator:
condition-1 or condition-2
- For not operator:
not condition
Python Script Example-1
- In this example I will use
and
operator withif condition
andor
operator withelif condition block
- The first
if condition
checks if num is greater than 5and
less than 10 using and operator - The second
elif condition
checks if num is equal to 4or
5 using or operator - The last
print
statement i.e. "Now we are in main function
" will be called irrespective of the condition value because it is called outside theif..elif..else block
#!/usr/bin/env python3 import sys # Only integers allowed try: num = int(input("Enter any number: ")) except: print("Only numbers allowed") sys.exit(1) # if block condition if num > 5 and num < 10: # if block starts, notice the indentation print("You have entered the if block") print("The provided number is greater than 5 and less than 10") print("Exiting if block") elif num == 4 or num == 5: # elif block starts, notice the indentation print("You have entered the elif block") print("The provided number is equal to 4 or 5") print("Exiting elif block") else: # else block starts, notice the indentation print("You have entered the else block") print("The provided number is less than 5") print("Exiting else block") # if..elif..else block ends, notice the indentation print("Now we are in main function")
Output (if and
operator from if condition
returns True
)
# python3 /tmp/if_else_example.py
Enter any number: 6
You have entered the if block
The provided number is greater than 5 and less than 10
Exiting if block
Now we are in main function
Output (if or
operator from elif condition
returns True
)
# python3 /tmp/if_else_example.py
Enter any number: 4
You have entered the elif block
The provided number is equal to 4 or 5
Exiting elif block
Now we are in main function
Python Script Example-2
- In this example I will use the logical
not
operator. - When the
if condition
returnsTrue
i.e. if num isnot
greater than 5 thenif block
will be executed - If the
if block
returnsFalse
i.e. if num is greater than 5 thenelse block
will be executed - The last
print
statement i.e. "Now we are in main function
" will be called irrespective of the condition value because it is called outside theif..else
block
#!/usr/bin/env python3 import sys # Only integers allowed try: num = int(input("Enter any number: ")) except: print("Only numbers allowed") sys.exit(1) # if block condition if not num > 5: # if block starts, notice the indentation print("You have entered the if block") print("The provided number is less than 5") print("Exiting if block") else: # else block starts, notice the indentation print("You have entered the else block") print("The provided number is greater than 5") print("Exiting else block") # if..else block ends, notice the indentation print("Now we are in main function")
Output(if not
operator from if condition
returns True
)
# python3 /tmp/if_else_example.py
Enter any number: 3
You have entered the if block
The provided number is less than 5
Exiting if block
Now we are in main function
Output(if not
operator from if condition
returns False
)
# python3 /tmp/if_else_example.py
Enter any number: 6
You have entered the else block
The provided number is greater than 5
Exiting else block
Now we are in main function
Conclusion
In this tutorial we learned about if..elif..else
statement used in Python programming language. Along with these condition you can use string comparison operators or logical operators such as and
, or
, not
for comparison. The respective condition block will be executed based on their exist status.
The True
boolean represents zero exit status while the False
boolean represents non-zero exit status. Lastly I hope this tutorial guide on python if else statement was helpful. So, let me know your suggestions and feedback using the comment section.