get consultation

If-Elif-Else

The if statement can be combined with else and elif

Else

With the if/else statement only one of the blocks is going to execute.

if-else.py
# Enter your first number
first_input = input("Enter your first number: ")

# Enter your second number
second_input = input("Enter your second number: ")

# Convert inputs into numbers (first_number, second_number)
first_number = int(first_input)
second_number = int(second_input)

if first_number == second_number:
    print(first_number, "is equal to", second_number)
else:
    print(first_number, "is not equal to", second_number)

Output:

Enter your first number: 1
Enter your second number: 2
1 is less than 2

Enter your first number: 1
Enter your second number: 1
1 is equal to 1

Elif

With the if/elif you can combine many comparisons but again only one is going to execute.

if2.py
# Enter your first number
first_input = input("Enter your first number: ")

# Enter your second number
second_input = input("Enter your second number: ")

# Convert inputs into numbers (first_number, second_number)
first_number = int(first_input)
second_number = int(second_input)

if first_number < second_number:
    print(first_number, "is less than", second_number)
elif first_number == second_number:
    print("They are equal")
elif first_number > second_number:
    print(first_number, "is greater than", second_number)

Output:

Enter your first number: 1
Enter your second number: 1
They are equal

Enter your first number: 1
Enter your second number: 2
1 is less than 2

Enter your first number: 2
Enter your second number: 1
2 is greater than 1

Complex Conditions

You can also have complex conditions.

age = 10
color = 'red'

# Either age equals 10 OR age equals 12
if age == 10 or age == 12:
    print("You are 10 or 12")

# Both age should equal 10 AND color should equal red
if age == 10 and color == 'red':
    print('You are 10 and red')

Links

Exercises (5 mins)

  1. Write the following program. If you are less than 13, print you are a child. If you are less than 20, print you are a teenager. Otherwise, print you are an adult.

    # Enter your age
    age = input("Enter your age: ")
    
    age = int(age)
    
    if :
        print("You are a child")
    elif :
        print("You are a teenager")
    ???:
        print("You are an adult")
    
    

    Output:

    Enter your age: 5
    You are a child
    
    Enter your age: 15
    You are a teenager
    
    Enter your age: 22
    You are an adult