Close
Close

Python If and Else


This chapter starts your real coding part. We are well equipped with all the basics we needed and now we can directly dive into the real programming logics.

Many times, we need to first see the conditions and accordingly make a decision. For example, if it is raining, we will take an umbrella, otherwise not. Similarly, if a number is divisible by 2, it is even, otherwise, it is odd.

Similarly, we can implement logics like if a user is admin then allow few features, otherwise not.

decision making

We make such types of decisions in Python using if...else.

Python if Statement


Again take the example of raining. If it is raining, a person will take an umbrella.

In Python, such types of decisions are taken using an if statement. Let's first have a look at its syntax.

Python if statement Syntax


if condition:
    statement
    statement
    ...

We first write if condition:. This condition is based on the decision that we will be making.

If the condition is True, then only the body of if is executed.

Let’s take an example.

Python if statement Examples


a = 2
if a == 2:
    print("a is 2")

In this example, the condition of the if statement is a == 2.

The body of the if statement consists of the statement print(“a is 2”). This statement will get executed only if the condition is True.

Since the value of the variable a is 2, the condition a == 2 became True and the statement body of if got executed and thus a is 2 got printed on the screen.

If the value of a was not 2, then the statement in the body of if would not have got executed.

Let’s take one more example.

print("Enter your name")
name = input()

if(name=="Sam"):
    print("Your name is Sam")
    print("It’s a good name")

Here both statements are inside the if block. But how did we decide which is inside it and which is not? Notice the space before the statements print(“Your name is Sam”) and print(“It’s a good name”). It is called indentation.

Also notice a colon : after if.

All the statements after colon (:) which are indented using space are body of the if statement. We can use space or tab to provide indentation. You can also set this up in the text editor you are using.

indentation in if clause in Python

Now, a statement after if block which is not indented using tab or space will not be a part of if.

indentation in if clause in Python

Let’s take an example.

age = int(input("Enter age"))
if age >= 18:
    print("Your age is 18+")
    print("You are eligible to vote")
	
print("This statement is outside the body of if statement")
Output
Enter age20
Your age is 18+
You are eligible to vote
This statement is outside the body of if statement

Here, the condition of the if statement is age >= 18.

The body of the if statement consists of print("Your age is 18+") and print("You are eligible to vote"). These two statements will get executed only if the condition is True.

Since the user entered the age as 20, which is greater than 18, the condition age >= 18 became True. Therefore, the statements in the body of if got executed. 

If the user enters the age less than 18, then the condition age >= 18 will become False and the statements in the body of if will not get executed.

That was easy, right?

Let’s see one more example.

a = 45
b = 45
if a == b:
    print("a is equal to b")
Output
a is equal to b

Here the condition a == b is True and thus the statement in the body of the if statement got executed and "a is equal to b" got printed.

Python Indentation


Statements written inside the body of if or else (we will read about else in the next section) must be indented equally from the left margin. It means that all the statements written inside the body of if must be equally spaced from the left. We have used an indentation of 4 spaces in this chapter. This means that before every statement inside the body of if, there is a left space of 4 spaces.

The best way to add indentation is to press the TAB key where you want to add the indentation. You can set a different width of Tab space in text editors. We have this width of 4 in this chapter. That's why we are getting a width of 4 spaces every time.
In Python, this equal indentation represents the body. Here, it is the body of if. It represents what things are inside if. We will see giving indentation in many more places like loops, functions to represent their body.

Python if...else Statement


Now, assume that a chocolate costs 10 rupees and a candy costs 5 rupees. So, if you have at least 10 rupees, you can buy a chocolate, otherwise you have to buy a candy.

In the world of programming, this is done by using if...else statement. Let's see how.

Python if..else Syntax


if condition:
    statement
    statement
    ...
else:
    statement
    statement
    ...

The body of if consists of all the indented statements following if, unless some unindented statement is written.

The body of else consists of all the indented statements following else, unless some unindented statement is written.

If the condition is True, then the body of if is executed, otherwise the body of else is executed.

Python if..else Examples


age = int(input("Enter age"))
if age >= 18:
    print("Your age is 18+")
    print("You are eligible to vote")
else:
    print("You are not yet 18")
    print("You are not eligible to vote")
Output
Enter age15
You are not yet 18
You are not eligible to vote

Since the user entered the age as 15, the condition age >= 18 became False. Therefore, the statements in the body of else got executed.

Look at another example.

a = 45
b = 56
if a == b:
    print("a is equal to b")
else:
    print("a is not equal to b")
Output
a is not equal to b

In the above example, the value of a is not equal to that of b. Since the expression a == b is False, therefore the statement in the body of else i.e., print("a is not equal to b") got executed.

Let’s write a program to find out if a number is even or odd.

a = 14
if a%2 == 0: #checking divisibility by 2
    print("Your number is even")
else:
    print("Your number is odd")
Output
Your number is even

The above code is self-explanatory. a%2 gives us the remainder of the division of a by 2. If the remainder is 0 (perfectly divisible by 2), then the body of if gets executed otherwise that of else gets executed. In our case where the value of a is 14, the condition of if is True and therefore the body of if got executed.

Python if...elif...else Statement


elif is a short form of else if. It is a combination of multiple if...else statements.

Python if...elif...else Syntax


if condition:
    statement
    statement
    ...
elif condition:
    statement
    statement
    ...
elif condition:
    statement
    statement
    ...
else:
    statement
    statement
    ...

Firstly, as usual the condition of if is checked. If it is True, then the body of if is executed.

If the condition of if is False, then the condition of the first elif is checked. If the condition of the first elif is True then the statements inside its body are executed, otherwise the next elif condition is checked.

If the conditions of if and all elif are False, then the body of else is executed.

Python if...elif...else Examples


age = int(input("Enter your age"))
if age < 13: # condition - age < 13
    print("Hey! kid")
elif age > 13 and age < 20: # condition - age > 13 and age < 20
    print("So, you are enjoying your teenage.")
else:
    print("You are grown up.")
Output
Enter your age15
So, you are enjoying your teenage.

if age < 13: → We are first checking the condition of if - is the age entered by the user less than 13. If this condition is True, then the body of if is executed. If the condition is False, then the condition of the next elif is checked.

elif age > 13 and age < 20: → We are checking the condition of elif - is the age between 13 (included) and 20. If this condition is True, then the body of elif is executed. If the condition is False, then the body of else is executed.

Let's see one more example.

a = int(input("Enter a number"))
if a%2 == 0 and a > 10: # condition - a%2 == 0 and a > 10
    print("Your number is even and greater than 10")
elif a%2 == 0 and a < 10: # condition - a%2 == 0 and a < 10
    print("Your number is even and smaller than 10")
else:
    print("Your number is odd")
Output
Enter a number6
Your number is even and smaller than 10

a%2 is used to check the divisibility by 2. If a%2 is 0, then a is an even number, otherwise an odd number.

if a%2 == 0 and a > 10: → If the number entered by the user is divisible by even and greater than 10, then the body of if is executed. 

elif a%2 == 0 and a <= 10: → If the number is even and less than or equal to 10, then the body of elif is executed.

else → If the conditions of both if and elif are False, then the body of else is executed. 

Python Nested if Statements


We can use if, if...else or if...elif...else statements in the body of if, elif or else. This is also called nesting.

The last example is rewritten below using nesting.

a = int(input("Enter a number")) #taking input from user
if a%2 == 0: #checking divisibility by 2
    if a > 10:
        print("Your number is even and greater than 10")
    else:
        print("Your number is even and smaller than or equal to 10")
else:
    print("Your number is odd")
Output
Enter a number14
Your number is even and greater than 10

Here,

if a > 10:
    print("Your number is even and greater than 10")

else:
    print("Your number is even and smaller than or equal to 10")

is inside if a%2 == 0.

nested if in Python

Notice the indentation from the left margin in the above example - print("Your number is even and greater than 10") is inside both if a > 10 and if a%2 == 0. If you are facing any difficulty, feel free to ask your question.

Here, we are checking if the number entered by the user is even or odd. If the number is even, then we are further checking if it is greater than 10 or not. Accordingly, we are displaying the message. For example, if the user enters 14, then the number is even (a%2 == 0 is True) and greater than 10 (a > 10 is True) and therefore "Your number is even and greater than 10" will get displayed.

Python pass Statement


The pass statement is used to skip from if, elif or else. If we don’t want to give anything in the body of if, elif or else, then we give the pass statement in the body. On executing pass, nothing happens.

age = int(input("Enter your age."))
if age < 13:
    print("Hey! kid")
elif age>13 and age < 20:
    pass
else:
    print("You are grown up.")
Output
Enter your age.15

The body of elif contains pass. This means that if the age entered by the user is between 13 (included) and 20, then nothing will get executed. Therefore, on giving the age as 15, using pass just skipped and printed nothing.

You might be wondering why someone would use pass. There can be different reasons for using it. One can be that you want to do nothing for some specific conditions, like in the last example where you don’t want to display anything if age is between 13 and 20. Another reason can be that you want to write some code in future and you can’t leave the body empty as that would throw an error, therefore you just give the pass statement there.

We highly recommend you to practice the concepts taught in this section. You will get a bunch of different problems in the practice section.
You will go through many questions including the above concepts in the practice section. If you are facing difficulty anywhere, then feel free to ask questions.
To learn from simple videos, you can always look at our Python video course on CodesDope Pro. It has over 500 practice questions and over 20 projects.
If you don't practice, you don't deserve to win.
- Andre Agassi


Ask Yours
Post Yours
Doubt? Ask question