How to Used in conditional statements, same as else if in Python ?


In Python, the equivalent of else if is elif. It is used in conditional statements to check for multiple conditions.

The syntax for elif is as follows:

if condition1:
    # code to execute if condition1 is True
elif condition2:
    # code to execute if condition2 is True
elif condition3:
    # code to execute if condition3 is True
else:
    # code to execute if all conditions are False

Here's an 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, the first condition (x > 10) is False, so the code moves on to the next condition (x < 10). Since this condition is also False, the code executes the else block and prints "x is equal to 10".

You can have as many elif statements as you need to check for different conditions.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.