If/Elif/Else Conditions
Welcome back to the Python basics tutorial! Today I'll teach you about if/elif/else conditions.
In the 3rd part, Data types and operators in Python, you learned about comparing values. What if you wanted to do something when a specific value is greater or smaller compared to another? In that case, we use If statements.
Simple, right? We can also compare strings.
You must have noticed that we're moving the print calls a bit to the right by adding spaces. This is called indention. Indention is used to make "code blocks". Like we put the print call inside the code block of the if statement. That means that the print call will only be executed if the condition being evaluated is True. The top line of the code block, in this case if password == 'therightpassword'
is called the "header" and in the next code block the header is the "else:". The code inside the code block is called a "suite".
A code block is a piece of code that is specified to be run only when the expression is evaluated to True. There can be other cases too, which you will learn about later. Code blocks are created by indenting the code.
We don't always have to use an else
with an if
:
Ok. So we got that part. But if someone enters their age as 2000 our program will still say "Welcome", but that is obviously not a valid age. So, a quick google search says that the average lifespan of a human is 79 years, which we round to 80. So, we will only accept ages between 13 and 80. For that, we can do:
That's a lot to take in! But we can break it down, line by line. One important point, an if/else is related by the level of indention. That's why the else
at the same indention level corresponds to the if
at the same level.
So, our code means, if age is greater than or equal to 13, continue to the next line in the code block. If not, print "too young" and exit. If age is smaller than or equal to 80, print "Welcome". If not, print "Invalid age" and exit.
Nested if blocks are usually a bad idea.
So, we should generally avoid nested if blocks, we have two options. We can use elif
statements:
"Elif" means Else If. So you could achieve the same result by putting more if blocks in the else block instead of using elif.
It's a bit easier to understand, but in cases like this we would use a different approach.
Here's where some logical operators come in. They're and
, not
, is
and in
. With these, you can reduce the lines of code:
Much better!
We can use them like this too:
Remember how we "escaped" quotes with a backslash in Print function, strings, variables and development environment.
Some more examples of If/Elif/Else statements:
Or a simple calculator:
Awesome! You've learnt some quite impressive python stuff there!
Last updated
Was this helpful?