Python if else is a conditionals statement, which basically is used to have your program make decisions. For example, if one number is greater than others do this, if it’s not greater then do this other thing, that’s basically the idea about if else in python (and other programming languages).
In this tutorial you will learn about:-
- Basic python
if
statement - if statement with else condition –
if...else
- and Python
if...elif..else
Let’s start learning one by one Syntax and Examples
A conditional is a block of code that performs different actions depending on whether a given conditional evaluates to true or false so let’s create a conditional (if and if-else) in Python.
Syntax
The general Python syntax for a simple if
statement is
if condition : StatementBlock
You can see the syntax, If the condition is true, then do the statements and If the condition is not true, then skip the statement.
Python if Statement Example :
In this example print() message according to the condition is true or not.
marks = 70 if marks > 60: print("A Grade") print("This is always printed.")
Output: A Grade
This is always printed.
if-else Syntax
This is general if-else statement python syntax, you can put more if conditions before the else …use elif
if expression: statement(s) else: statement(s)
Python if else Example:
In the example, the first condition variable mark is not greater then 60 so if condition false.
marks = 50 if marks > 60: print("A Grade") else: print("B Grade") print("This is always printed.")
Output: B Grade
This is always printed.
if…elif…else Syntax
The if block can have only one else block. But it can have multiple elif blocks.
if expression1: statement(s) elif expression2: statement(s) elif expression3: statement(s) else: statement(s)
So you can achieve multiple if condition using elif
.
Python if…elif…else Example:
We are using only one elif you can add more. In this example, Variable b is greater than a, so first if it is false. Then elif a < b
condition is true, so it will print “B grater then A”
a = 5 b = 7 if a > b: print("A Grater then B") elif a < b: print("B Grater then A") else: print("None") print("This is always printed.")
Output: B Grater then A
This is always printed.
Do comment for any doubts and suggetion. There is a lot of condition and way to use this statement.
Note : This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6Python 3.7
All Examples are in Python 3, so it may change its different from python 2 or upgraded versions.