if/elif/else Statements

In Python, the computer can make a decision between several options with if/elif/else statements. Based on the values of the conditions, these statements let you change the flow of control in a program. Almost all programs use one or more if statements, so they are important to understand. if/elif/else statements are often used together in a set. Let's go through each of them.

The syntax

if condition1:
    # do something if condition1 is True
elif condition2:      
    # do something if condition1 is False but condition2 is True
elif condition3:      
    ... 
else:                
    # do something else if both condition1 and condition2 are False

Note that elif and else statements are optional.

Simple if statement

n = 3
if n > 1:
    print(n)

The console result:

3

Testing different things with elif

If you want to test other conditions after the first if statement, add elif statements after it. You may have as many elif statements as you'd like, but note that after the computer finds a condition that is true and runs the code inside, it will skip over all of the remaining statements so that it only runs one in the entire set of if/elif/else statements.

age = int(input('Enter your age:'))

if age > 12:
    print('It will be hard for me to make you laugh.')
elif age > 5:
    print('What did O say to 8?')
    print('Nice belt!')
else:
    print('You are too young for my jokes.')

Run the program. The pop up window shows a message:

Enter your age:

Type in 8.
Console results:

What did O said to 8?
Nice belt!

Run again and enter 15:

Enter your age: 15
It will be hard to get you laugh.

Adding an else

else statement is also optional. The computer will run the else if the conditions in the if and elif statements are all false. Notice that the else statement does not have a condition in it, unlike the other two, because it is meant to indiscriminately catch all the conditions that don't qualify the if and elif statements directly before it.

n = 3
if n > 10:
    print (n, 'is larger than 10')
else:
    print (n, 'is smaller than 10')

Console result:

3 is smaller than 10

Then change n = 3 to be n = 12, and run it again:

12 is larger than 10

Example: even_odd()

Let's create a function that takes an integer as input and uses if/else statements to determine whether it is even or odd.

def even_odd():
  n = int(input('Enter an integer here:'))
  if n % 2 == 0:
    print("The number is even.")    
  else:
    print("The number is odd.")       

# call the function:  
even_odd()

Call to run the function a few times, each time enter a different number, you will get message like this:

Enter an integer here: 8
The number is even.

Enter an integer here: 15
The number is odd.

results matching ""

    No results matching ""