If-else statements in Python

The programs we have written so far executes in a very orderly fashion. This is not how programs in 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 flow of programs, we also use control statements to loop or skip over statements when some condition is true.

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 statements.

if statement #

The syntax of if statement is as follows:

Syntax:

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 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 using 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

number = input("Enter a number: ")
if number > 10:
    print("Number is greater than 10")

First Run Output:

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 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

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")

First Run Output:

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

Second Run Output:

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 2,3 and 4 belongs to the if block. Consequently, statements in line 2,3 and 4 will execute only when the if condition is True, on the other hand statements in line 5 and 6 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:

>>>
>>> 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:

>>>
>>> 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.

>>>
>>> n = 100
>>> if n > 10:
...     print("n is greater than 10")
...
n is greater than 10
>>>

Simple 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 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:

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 a Circle

python101/Chapter-09/calculate_circles_area_circumference.py

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")

First Run Output:

Enter radius: 4
Circumference =  25.12
Area =  50.24

Second Run Output:

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 syntax error. For example:

python101/Chapter-09/if_and_else_not_aligned.py

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 running the above program and you will get a syntax error like this:

q@pro-vm:~/python101/Chapter-06$ python3 if_and_else_not_aligned.py 
  File "if_and_else_not_aligned.py", line 6
    else:
       ^
SyntaxError: invalid syntax
q@pro-vm:~/python101/Chapter-06$

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


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")

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

test15.py

password = input("Enter a password: ")
if password == "sssshhh":
    print("Welcome to the Secret World")
else:
    print("You are not allowed here")

First Run Output:

Enter a password: sssshhh
Welcome to the Secret World

Second Run Output:

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

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")

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 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 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:

$ ./test16.py
Enter your GRE score: 160
Enter percent secured in graduation: 75
Congratulations you are eligible for loan

Second Run Output:

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 per_grad above 70 and gre_score below than 150 like this:

Output:

./test16.py
Enter your GRE score: 150
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.

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

python101/Chapter-09/nested_if_else_statement.py

# A program to check whether a student is eligible for loan or not

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.")
./test16.py
Enter your GRE score: 150
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

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 the exam")

How it works:

When program control comes to the if-else statement, the condition (score >= 90) in line 6 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 8, 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 11. 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 14. 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:

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, condition_1 is tested. 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 then 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 a elif clause is found to be True. In case no elif clause found to be True then at last block of statements in the else block is executed.

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

python101/Chapter-09/if_elif_else_statement.py

# A program to determine student grade based upon entered marks

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 the exam")

First run output:

Enter your marks: 78
Good ! Your grade is C

Second run output:

Enter your marks: 91
Excellent! Your grade is A

Third run output:

Enter your marks: 55
You failed the exam

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