Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn if/elif/else Expressions | Conditional Statements in Python
Introduction to Python
course content

Course Content

Introduction to Python

Introduction to Python

1. First Acquaintance with Python
2. Variables and Types in Python
3. Conditional Statements in Python
4. Other Data Types in Python
5. Loops in Python
6. Functions in Python

book
if/elif/else Expressions

To check an additional condition after the initial if statement, use elif. This allows for multiple conditions to be evaluated in sequence. The structure is as follows:

The code following the final else runs only if none of the previous conditions are met. You can use it to categorize a string as large if it contains more than 20 characters, medium if it has between 11 and 20 characters (inclusive), and small if it has 10 or fewer characters.

123456789101112131415161718192021
# Assign some medium string test = "medium string" # Conditional statements if len(test) > 20: print("String: '", test, "' is large") elif len(test) > 10: print("String: '", test, "' is medium") else: print("String: '", test, "' is small") # One more checking test = "small" # Conditional statement if len(test) > 20: print("String: '", test, "' is large") elif len(test) > 10: print("String: '", test, "' is medium") else: print("String: '", test, "' is small")
copy

Note

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

question mark

Below, you're presented with an if/elif/else block. Given the values, what output would you expect if b = 150 and if b = 25?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 3. Chapter 9
We're sorry to hear that something went wrong. What happened?
some-alt