Editor settings

General settings

Save settings

Learn to program with Python

Handle more conditions with elif #

In Python, elif stands for "else if". It is a conditional statement that comes after an if statement and before an optional else statement. elif allows you to check multiple conditions and execute different code blocks depending on the condition that is True.

We can add elif keyword after if keyword, like so:

if condition1:
    # do something
elif condition2:
    # do something else
else:
    # do something if none of the conditions above are true

For example:

x = 10

if x > 10:
    print("x is greater than 10")
elif x < 10:
    print("x is less than 10")
else:
    print("x is equal to 10")

In this example, we're checking the value of x using an if statement. If x is greater than 10, we print a message saying so. If it's less than 10, we print a different message. If neither of these conditions are True, we move on to the else block and print a message saying that x is equal to 10.

Note that both elif and else are optional in an if statement, meaning that we can write an if statement without any of those keywords.


Exercise #

Write your code inside the get_discount so that:

  • If the value of total is at least 1000, return the number 30.
  • If the value of total is at least 500, return the number 20.
  • For other value of total, return the number 10.

Tests #

  • get_discount(300) should return 10
  • get_discount(500) should return 20
  • get_discount(1000) should return 30
  • get_discount(1500) should return 30
Output will be displayed here