6.1 if else
In Python, just like in many programming languages, commands can be executed not only linearly but also selectively based on a certain condition. Such a construction is called a conditional operator. The general form of a conditional operator looks like this:
if condition:
command1
else:
command2
If condition is true (True
), then command1 is executed. If false (False
), then command2 is executed. The commands never execute simultaneously: it's either one or the other.
Important! The child command or commands must(!) be indented by 4 spaces relative to the if
and else
commands. I'll tell you more about this in the next lecture "Block of Commands".
Examples:
|
The condition y > 5 is false, so the else branch will execute, and the program will print "y is not greater than 5". |
Another example:
|
If the user inputs a number 18 or more, the program will print "you are an adult", otherwise it will print "go do your homework". |
6.2 if without else
There are 2 other forms of the conditional operator – shorthand and extended.
In the shorthand form, the else
part is missing.
if condition:
command
If the condition is true, the command will execute. If it's not true, nothing happens – the program just moves on to execute the rest of the commands, if there are any.
Example:
|
If the user inputs a number 21 or more, the program will print "Here's your beer". If the number is less than 21 – nothing will be printed. |
6.3 if elif else
The extended form of the if
else
operator allows you to chain several if
else
operators together.
Suppose you want to determine which quadrant of the coordinate plane a point with coordinates x
and y
belongs to. Here's how you can do it using the if
and else
operators:
|
If x > 0 and y > 0, it will print "first quadrant". If x < 0 and y > 0, it will print "second quadrant". If x < 0 and y < 0, it will print "third quadrant". If x > 0 and y < 0, it will print "fourth quadrant". |
Since not adding indents is not allowed and you want the code to be readable, a special operator elif
was created, which turns such if chains into something more readable. It looks like this:
if condition1:
command1
elif condition2:
command2
elif conditionN:
commandN
else:
commandElse
The keyword elif
is a contraction of else
if
. And the code from the example above can now be written as:
|
If x > 0 and y > 0, it will print "first quadrant". If x < 0 and y > 0, it will print "second quadrant". If x < 0 and y < 0, it will print "third quadrant". If x > 0 and y < 0, it will print "fourth quadrant". |
GO TO FULL VERSION