Python

if elif and else

We can chain if statements.

How?

Using the keywords elif and else. That way, we can walk through all options for the condition. Imagine a weather app: if snow, elif rain, elif thunder, else sunny. We can execute different code for each condition.

Related Course: Complete Python Bootcamp: Go from zero to hero in Python

If elif and else

We can execute blocks of code using if-statements. We can also do that if we have multiple conditions.
Lets start with an if statement, like so:

 
x = 3

if x < 5:
print('x smaller than 5')
else:
print('x is too big')


It will make the decision based on the value of x, also known as the condition.

x smaller than 5

What if you want to have multiple cases?
In that case you can use elif

 
x = 8

if x < 5:
print('x smaller than 5')
elif x >= 5 and x <= 10:
print('great choice')
else:
print('x is too big')

Previous Post Next Post

Cookie policy | Privacy policy | ©