OverIQ.com

If-else statements in Python

Last updated on September 21, 2020


The programs we have written so far executes in a very orderly fashion. This is not how programs in the real world operate. Sometimes we want to execute a set of statements only when certain conditions are met. To handle these kinds of situations programming languages provide some special statements called Control Statements. In addition to controlling the flow of programs, we also use control statements to loop or skip over statements when some condition is true.

The Control Statements are of following types:

  1. if statement
  2. if-else statement
  3. if-elif-else statement
  4. while loop
  5. for loop
  6. break statement
  7. continue statement

In this lesson we are discussing the first three control statements.

if statement #

The syntax of if statement is as follows:

Syntax:

1
2
3
4
5
if condition:
    <indented statement 1>
    <indented statement 2>

<non-indented statement>

The first line of the statement i.e if condition: is known as if clause and the condition is a boolean expression, that is evaluated to either True or False. In the next line, we have have block of statements. A block is simply a set of one or more statements. When a block of statements is followed by if clause, it is known as if block. Notice that each statement inside the if block is indented by the same amount to the right of the if keyword. Many languages like C, C++, Java, PHP, uses curly braces ({}) to determine the start and end of the block but Python uses indentation. Each statement inside the if block must be indented by the same number of spaces. Otherwise, you will get syntax error. Python documentation recommends to indent each statement in the block by 4 spaces. We use this recommendation in all our programs throughout this course.

How it works:

When if statement executes, the condition is tested. If condition is true then all the statements inside the if block is executed. On the other hand, if the condition is false then all the statements in the if block is skipped.

The statements followed by the if clause which are not indented doesn't belong to the if block. For example, <non-indented statement> is not the part of the if block, as a result, it will always execute no matter whether the condition in the if clause is true or false.

Here is an example:

python101/Chapter-09/if_statement.py

1
2
3
4
number = int(input("Enter a number: "))

if number > 10:
    print("Number is greater than 10")

Try it now

First Run Output:

1
2
Enter a number: 100
Number is greater than 10

Second Run Output:

Enter a number: 5

Notice that in the second run when condition failed, statement inside the if block is skipped. In this example the if block consist of only one statement, but you can have any number of statements, just remember to properly indent them.

Now consider the following code:

python101/Chapter-09/if_statement_block.py

1
2
3
4
5
6
7
number = int(input("Enter a number: "))
if number > 10:
    print("statement 1")
    print("statement 2")
    print("statement 3")
print("Executes every time you run the program")
print("Program ends here")

Try it now

First Run Output:

1
2
3
4
5
6
Enter a number: 45
statement 1
statement 2
statement 3
Executes every time you run the program
Program ends here

Second Run Output:

1
2
3
Enter a number: 4
Executes every time you run the program
Program ends here

The important thing to note in this program is that only statements in line 3,4 and 5 belongs to the if block. Consequently, statements in line 3,4 and 5 will execute only when the if condition is true, on the other hand statements in line 6 and 7 will always execute no matter what.

Python shell responds somewhat differently when you type control statements inside it. Recall that, to split a statement into multiple lines we use line continuation operator (\). This is not the case with control statements, Python interpreter will automatically put you in multi-line mode as soon as you hit enter followed by an if clause. Consider the following example:

1
2
3
4
>>>
>>> n = 100
>>> if n > 10:
...

Notice that after hitting Enter key followed by if clause the shell prompt changes from >>> to .... Python shell shows ... for multi-line statements, it simply means the statement you started is not yet complete.

To complete the if statement, add a statement to the if block as follows:

1
2
3
4
5
>>>
>>> n = 100
>>> if n > 10:
...     print("n is greater than 10")
...

Python shell will not automatically indent your code, you have to do that yourself. When you are done typing statements in the block hit enter twice to execute the statement and you will be taken back to the normal prompt string.

1
2
3
4
5
6
7
>>>
>>> n = 100
>>> if n > 10:
...     print("n is greater than 10")
...
n is greater than 10
>>>

The programs we have written so far ends abruptly without showing any response to the user if the condition is false. Most of the time we want to show the user a response even if the condition is false. We can easily do that using if-else statement

if-else statement #

An if-else statement executes one set of statements when the condition is true and a different set of statements when the condition is false. In this way, a if-else statement allows us to follow two courses of action. The syntax of if-else statement is as follows:

Syntax:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
if condition:
    # if block
    statement 1
    statement 2
    and so on
else:
    # else block
    statement 3 
    statement 4
    and so on:

How it works:

When if-else statement executes, condition is tested if it is evaluated to True then statements inside the if block are executed. However, if the condition is False then the statements in the else block are executed.

Here is an example:

Example 1: Program to calculate area and circumference of the circle

python101/Chapter-09/calculate_circles_area_circumference.py

1
2
3
4
5
6
radius = int(input("Enter radius: "))
if radius >= 0:
    print("Circumference = ", 2 * 3.14 * radius)
    print("Area = ", 3.14 * radius ** 2 )
else:
    print("Please enter a positive number")

Try it now

First Run Output:

1
2
3
Enter radius: 4
Circumference =  25.12
Area =  50.24

Second Run Output:

1
2
Enter radius: -12
Please enter a positive number

Now our program shows a proper response to the user even if the condition is false which is what is wanted.

In an if-else statement always make sure that if and else clause are properly aligned. Failing to do will raise a syntax error. For example:

python101/Chapter-09/if_and_else_not_aligned.py

1
2
3
4
5
6
7
radius = int(input("Enter radius: "))
if radius >= 0:
    print("Circumference = ", 2 * 3.14 * radius)
    print("Area = ", 3.14 * radius ** 2 )

    else:
        print("Please enter a positive number")

Try it now

Try running the above program and you will get a syntax error like this:

1
2
3
4
5
6
q@vm:~/python101/Chapter-09$ python3 if_and_else_not_aligned.py 
  File "if_and_else_not_aligned.py", line 6
    else:
       ^
SyntaxError: invalid syntax
q@vm:~/python101/Chapter-06$

To the fix the problem, align the if and else clause vertically as follows:

1
2
3
4
5
6
7
radius = int(input("Enter radius: "))
if radius >= 0:
    print("Circumference = ", 2 * 3.14 * radius)
    print("Area = ", 3.14 * radius ** 2 )

else:
    print("Please enter a positive number")

Try it now

Here is another example:

Example 2: A program to check the password entered by the user

python101/Chapter-09/secret_world.py

1
2
3
4
5
password = input("Enter a password: ")
if password == "sshh":
    print("Welcome to the Secret World")
else:
    print("You are not allowed here")

Try it now

First Run Output:

1
2
Enter a password: sshh
Welcome to the Secret World

Second Run Output:

1
2
Enter a password: ww
You are not allowed here

Nested if and if-else statement #

We can also write if or if-else statement inside another if or if-else statement. This can be better explained through some examples:

if statement inside another if statement. #

Example 1: A program to check whether a student is eligible for loan or not

python101/Chapter-09/nested_if_statement.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
gre_score = int(input("Enter your GRE score: "))
per_grad = int(input("Enter percent secured in graduation: "))

if per_grad > 70:
    # outer if block
    if gre_score > 150:
        # inner if block
        print("Congratulations you are eligible for loan")
else:
    print("Sorry, you are not eligible for loan")

Try it now

Here we have written a if statement inside the another if statement. The inner if statement is known as nested if statement. In this case the inner if statement belong to the outer if block and the inner if block has only one statement which prints "Congratulations you are eligible for loan".

How it works:

First the outer if condition is evaluated i.e per_grad > 70, if it is True then the control of the program comes inside the outer if block. In the outer if block gre_score > 150 condition is tested. If it is True then "Congratulations you are eligible for loan" is printed to the console. If it is False then the control comes out of the if-else statement to execute statements following it and nothing is printed.

On the other hand, if outer if condition is evaluated to False, then execution of statements inside the outer if block is skipped and control jumps to the else (line 9) block to execute the statements inside it.

First Run Output:

1
2
3
Enter your GRE score: 160
Enter percent secured in graduation: 75
Congratulations you are eligible for loan

Second Run Output:

1
2
3
Enter your GRE score: 160
Enter percent secured in graduation: 60
Sorry, you are not eligible for loan

This program has one small problem. Run the program again and enter gre_score less than 150 and per_grad greater than 70 like this:

Output:

1
2
Enter your GRE score: 140
Enter percent secured in graduation: 80

As you can see program doesn't output anything. This is because our nested if statement doesn't have an else clause. We are adding an else clause to the nested if statement in the next example.

Example 2: if-else statement inside another if statement.

python101/Chapter-09/nested_if_else_statement.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
gre_score = int(input("Enter your GRE score: "))
per_grad = int(input("Enter percent secured in graduation: "))

if per_grad > 70:
    if gre_score > 150:
        print("Congratulations you are eligible for loan.")
    else:
        print("Your GRE score is no good enough. You should retake the exam.")
else:
    print("Sorry, you are not eligible for loan.")

Try it now

Output:

1
2
3
Enter your GRE score: 140
Enter percent secured in graduation: 80
Your GRE score is no good enough. You should retake the exam.

How it works:

This program works exactly like the above, the only difference is that here we have added an else clause corresponding to the nested if statement. As a result, if you enter a GRE score smaller than 150 the program would print "Your GRE score is no good enough. You should retake the exam." instead of printing nothing.

When writing nested if or if-else statements always remember to properly indent all the statements. Otherwise you will get a syntax error.

if-else statement inside else clause. #

Example 3: A program to determine student grade based upon marks entered.

python101/Chapter-09/testing_multiple_conditions.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
score = int(input("Enter your marks: "))

if score >= 90:
    print("Excellent ! Your grade is A")
else:
    if score >= 80:
        print("Great ! Your grade is B")
    else:
        if score >= 70:
            print("Good ! Your grade is C")
        else:
            if score >= 60:
                print("Your grade is D. You should work hard on you subjects.")
            else:
                print("You failed in the exam")

Try it now

First Run Output:

1
2
Enter your marks: 92
Excellent ! Your grade is A

Second Run Output:

1
2
Enter your marks: 75
Good ! Your grade is C

Third Run Output:

1
2
Enter your marks: 56
You failed in the exam

How it works:

When program control comes to the if-else statement, the condition (score >= 90) in line 3 is tested. If the condition is True, "Excellent ! Your grade is A" is printed to the console. If the condition is false, the control jumps to the else clause in line 5, then the condition score >= 80 (line 6) is tested. If it is true then "Great ! Your grade is B" is printed to the console. Otherwise, the program control jumps to the else clause in the line 8. Again we have an else block with nested if-else statement. The condition (score >= 70) is tested. If it is True then "Good ! Your grade is C" is printed to the console. Otherwise control jumps again to the else block in line 11. At last, the condition (score >= 60) is tested, If is True then "Your grade is D. You should work hard on you subjects." is printed to the console. On the other hand, if it is False, "You failed the exam" is printed to the console. At this point, the control comes out of the outer if-else statement to execute statements following it.

Although nested if-else statement allows us to test multiple conditions but they are fairly complex to read and write. We can make the above program much more readable and simple using if-elif-else statement.

if-elif-else statement #

If-elif-else statement is another variation of if-else statement which allows us to test multiple conditions easily instead of writing nested if-else statements. The syntax of if-elif-else statement is as follows:

Syntax:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
if condition_1: 
    # if block
    statement
    statement   
    more statement
elif condition_2:
    # 1st elif block
    statement
    statement
    more statement
elif condition_3:   
    # 2nd elif block
    statement
    statement
    more statement

...

else    
    statement
    statement
    more statement

... means you means you can write as many elif clauses as necessary.

How it works:

When if-elif-else statement executes, the condition_1 is tested first. If the condition found to be true, then the statements in the if block is executed. The conditions and statements in the rest of the structure is skipped and control comes out of the if-elif-else statement to execute statements following it.

If condition_1 is false the program control jumps to the next elif clause and condition_2 is tested. If condition_2 is true the statements in the 1st elif block is executed. The conditions and statements in the rest of the if-elif-else structure is skipped and control comes out of the if-elif-statement to execute statements following it.

This process keeps repeating until an elif clause is found to be true. In case no elif clause found to be true then at last the block of statements in the else block is executed.

Let's rewrite the above program using if-elif-statement.

python101/Chapter-09/if_elif_else_statement.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
score = int(input("Enter your marks: "))

if score >= 90:
    print("Excellent! Your grade is A")
elif score >= 80:
    print("Great! Your grade is B")
elif score >= 70:
    print("Good! Your grade is C")
elif score >= 60:
    print("Your grade is D. You should work hard on you studies.")
else:
    print("You failed in the exam")

Try it now

First run output:

1
2
Enter your marks: 78
Good ! Your grade is C

Second run output:

1
2
Enter your marks: 91
Excellent! Your grade is A

Third run output:

1
2
Enter your marks: 55
You failed in the exam

As you can see the above program is quite easy to read and understand unlike it's nested equivalent.