Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära if/elif/else Expressions | Conditional Statements in Python
Introduction to Python(ihor)

bookif/elif/else Expressions

To check an additional condition after the initial if statement, use elif. This enables multiple conditions to be evaluated sequentially.

if condition_a:
    # Do this if `condition_a` is `True`
elif condition_b:
    # Do this if `condition_a` is not `True`, but `condition_b` is
else:
    # Do this if neither condition is `True`

Sometimes you want your program to handle several possible conditions, not just one. Using if and elif, you can check multiple conditions one after the other. Finally, you can use else to catch any cases that don't match the previous conditions.

123456789101112
# Define your age age = 43 # Print a message based on your age if age < 13: print("You are a child.") elif age < 20: print("You are a teenager.") elif age < 65: print("You are an adult.") else: print("You are a senior.")
copy

You can stack multiple elif blocks as needed. However, keep in mind that using too many elif blocks may not be the most efficient way to structure your code.

question mark

What is the purpose of using the elif statement in Python?

Select the correct answer

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 3. Kapitel 9

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Suggested prompts:

Ställ mig frågor om detta ämne

Sammanfatta detta kapitel

Visa verkliga exempel

Awesome!

Completion rate improved to 1.67

bookif/elif/else Expressions

Svep för att visa menyn

To check an additional condition after the initial if statement, use elif. This enables multiple conditions to be evaluated sequentially.

if condition_a:
    # Do this if `condition_a` is `True`
elif condition_b:
    # Do this if `condition_a` is not `True`, but `condition_b` is
else:
    # Do this if neither condition is `True`

Sometimes you want your program to handle several possible conditions, not just one. Using if and elif, you can check multiple conditions one after the other. Finally, you can use else to catch any cases that don't match the previous conditions.

123456789101112
# Define your age age = 43 # Print a message based on your age if age < 13: print("You are a child.") elif age < 20: print("You are a teenager.") elif age < 65: print("You are an adult.") else: print("You are a senior.")
copy

You can stack multiple elif blocks as needed. However, keep in mind that using too many elif blocks may not be the most efficient way to structure your code.

question mark

What is the purpose of using the elif statement in Python?

Select the correct answer

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 3. Kapitel 9
some-alt