Python if...elif...else statements tutorial with easy,productive,high quality examples for beginners
Do you know what is if-else statements in python?
a = 300
b = 500
if b > a:
print("b is greater than a")
In this example, we use two variables, a and b, which are used as part of the if statement to test whether b is greater than a. As a is 300, and b is 500, we know that 500 is greater than 300, and so we print to screen that "b is greater than a".
Now we are showing you a flowchart:
![]() |
Python flowchart |
Python Example:

You will get this output:
Indentation
Python relies on indentation (whitespace at the beginning of a line) to define the scope in the code. Other programming languages often use curly brackets for this purpose.
a = 33
b = 200
if b > a:
print("b is greater than a")
Python if...else statement
The elif Statement
The elif statement allows you to check multiple expressions for TRUE and execute a block of code as soon as one of the conditions evaluates to TRUE.
Similar to the else, the elif statement is optional. However, unlike else, for which there can be at most one statement, there can be an arbitrary number of elif statements following an if.

Now explain what we write in this code.
Here we use the input function to get a value from users. Don't think about the input function. In the upcoming day, we will explain the input function. After getting a value from users python will check the following condition. First, it will check if statement then goes to the next step elif then go to the else statement and program will give you an output according to your condition.
Flowchart of if...elif...else statement:

Python Nested if statements
We can write an if...elif...else statement inside another if...elif...else statement. This is called nesting in computer programming.
Any number of these statements can be nested inside one another. Indentation is the only way to figure out the level of nesting. They can get confusing, so they must be avoided unless necessary.

Maybe you have a question what is if nested elements?
You can have if statements inside if statements, this is called nested if statements. Hope you get your answer.
Short Hand If
If you have only one or multiple statements to execute, you can put it on the same line as the if statement and it will decrease your program line:
if a > b: print("a is greater than b")
Short Hand If ... Else
a = 2
b = 330
print("A") if a > b else print("B")
a = 300
b = 300
print("A") if a > b else print("=") if a == b else print("B")
And
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
Or
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
The pass Statement
a = 330
b = 200
if b > a:
pass
We are creating a full python tutorial. If you see any problem with our content please comment or contact us.
Post a Comment