In the last tutorial, you learnt about Python3: Python files, Printing and Inputting. In this tutorial, you'll learn about if-statements, using which you can do certain things only if certain conditions are met. In plain English, if-statements correspond to “Do this; then do that.” or “If this condition is true, perform this action; otherwise, do that action.”
A good way to visualize if-statements is flow charts. If-statements represent the yes / no questions in the flowchart below.
Before getting into if-statements, you'll first learn how to compare things in Python as well as the Boolean data type (values True and False). At the end of the lesson, you'll also see comments, which are useful for making your code more readable and easy to follow.
A big part of programming involves comparing things. What's the easiest thing to compare? Numbers, of course. Let's see how that works:
>>> 5 > 2True>>> 3 < 1False>>> 5 > 2 * 2True>>> 1 == 1True>>> 5 != 2True
We gave Python some numbers to compare. Not only can Python compare numbers, but it can also compare method results.
>>> len("Commonlounge") > 10True>>> len("David") > 10False
Do you wonder why we put two equal signs == next to each other to compare if numbers are equal? We use a single = for assigning values to variables. You always, always need to put two of them – ==– if you want to check if things are equal to each other. We can also state that things are unequal to each other. For that, we use the symbol !=, as shown in the example above.
Give Python two more tasks:
>>> 6 >= 12 / 2True>>> 3 <= 2False
We've seen > and <, but what do >= and <= mean? Read them like this:
- x > y means: x is greater than y
- x < y means: x is less than y
- x <= y means: x is less than or equal to y
- x >= y means: x is greater than or equal to y
We've summarized the list of comparison operators in Python in a table at the end of the article.
Awesome! Wanna do one more? Try this:
>>> 6 > 2 and 2 < 3True>>> 3 > 2 and 2 < 1False>>> 3 > 2 or 2 < 1True
You can give Python as many numbers to compare as you want, and it will give you an answer! Pretty smart, right?
- and – if you use the and operator, both comparisons have to be True in order for the whole command to be True
- or – if you use the or operator, only one of the comparisons has to be True in order for the whole command to be True
As we've done with examples before, let's see the step-by-step evaluation of one of the above expressions to make sure everything is crystal clear.
3 > 2 and 2 < 1=> True and 2 < 1=> True and False=> False
Have you heard of the expression "comparing apples to oranges"? Let's try the Python equivalent:
>>> 1 > 'django'Traceback (most recent call last):File "", line 1, inTypeError: '>' not supported between instances of 'int' and 'str'
Here you see that just like in the expression, Python is not able to compare a number (int) and a string (str). Instead, it shows a TypeError and tells us the two types can't be compared together.
Incidentally, you just learned about a new type of object in Python. It's called Boolean.
There are only two Boolean objects:
But for Python to understand this, you need to always write it as True (first letter uppercase, with the rest of the letters lowercased). true, TRUE, and tRUE won't work – only True is correct. (The same applies to False as well, of course.)
Booleans can be variables, too! See here:
>>> a = True>>> aTrue
You can also directly assign the value of a comparison:
>>> a = 2 > 5>>> aFalse
Practice and have fun with Booleans by trying to run the following commands:
- True and True
- False and True
- True or 1 == 1
- 1 != 2
Congrats! Booleans are one of the coolest features in programming, and you just learned how to use them!
We're going to need more than one line of code for the next few tasks. So, as you did for the last tutorial, exit the Python interpreter with the exit() function. Then, open a new file in your Code Editor.
You can now move on to an essential tool in programming:
Lots of things in code should be executed only when given conditions are met. That's why Python has something called if statements.
Add this code in your file and save it as python_intro.py:
if 3 > 2:
If we were to save and run this, we'd see an error like this:
$ python3 python_intro.pyFile "python_intro.py", line 2^SyntaxError: unexpected EOF while parsing
Python expects us to give further instructions to it which are executed if the condition 3 > 2 turns out to be true (or True for that matter). Let’s try to make Python print “It works!”. Change your code in your python_intro.py file to this:
if 3 > 2:print('It works!')
Notice how we've indented the next line of code by 4 spaces? We need to do this so Python knows what code to run if the result is true. You can do one space, but nearly all Python programmers do 4 to make things look neat. A single tab will also count as 4 spaces.
Save it and give it another run:
$ python3 python_intro.pyIt works!
Note: Remember that on Windows, 'python3' is not recognized as a command. From now on, replace 'python3' with 'python' to execute the file.
What if a condition isn't True?
In the previous example, code was executed only when the condition was True. But Python also has elif and else statements:
if 5 > 2:print('5 is indeed greater than 2')else:print('5 is not greater than 2')
When this is run it will print out:
$ python3 python_intro.py5 is indeed greater than 2
If 2 were a greater number than 5, then the second command would be executed. Let's see how elifworks:
name = 'Dave'if name == 'Commonlounge':print('Hey Commonlounge!')elif name == 'Dave':print('Hey Dave!')else:print('Hey anonymous!')
$ python3 python_intro.pyHey Dave!
See what happened there? elif lets you add extra conditions that run if the previous conditions fail.
You can add as many elif statements as you like after your initial if statement. For example:
volume = 57if volume < 20:print("It's kinda quiet.")elif 20 <= volume < 40:print("It's nice for background music")elif 40 <= volume < 60:print("Perfect, I can hear all the details")elif 60 <= volume < 80:print("Nice for parties")elif 80 <= volume < 100:print("A bit loud!")else:print("My ears are hurting! :(")
Python runs through each test in sequence and prints:
$ python3 python_intro.pyPerfect, I can hear all the details
Note that in chained if ... else if ... else statements, only the first condition that is met gets executed. As soon as the first condition is met, none of future else (or elif) conditions will be considered. Hence, the above code could be written more concisely as:
volume = 57if volume < 20:print("It's kinda quiet.")elif volume < 40:print("It's nice for background music")elif volume < 60:print("Perfect, I can hear all the details")elif volume < 80:print("Nice for parties")elif volume < 100:print("A bit loud!")else:print("My ears are hurting! :(")
We're making use of the fact that, when we compare volume < 60 (for example), all the previous conditions must have been False. This automatically implies that volume >= 40 (since the first two conditions were False). The code might be slightly harder to read, but it is equivalent to the previous one.
Comments are lines beginning with #. You can write whatever you want after the # and Python will ignore it. Comments can make your code easier for other people to understand.
Let's see how that looks:
# Change the volume if it's too loud or too quietif volume < 20 or volume > 80:volume = 50print("That's better!")
You don't need to write a comment for every line of code, but they are useful for explaining why your code is doing something, or providing a summary when it's doing something complex.
In the last few exercises you learned about:
- comparing things – in Python you can compare things by using >, >=, ==, <=, < and the and, or operators
- Boolean – a type of object that can only have one of two values: True or False
- Saving files – storing code in files so you can execute larger programs.
- if … elif … else – statements that allow you to execute code only when certain conditions are met.
- comments - lines that Python won't run which let you document your code
The following is a list of all comparison operations supported by Python.
Operator | Example | Result | Description---------|---------|--------|--------------------------------== | 4 == 5 | False | is equal to!= | 4 != 5 | True | is not equal to> | 4 > 5 | False | is greater than< | 4 < 5 | True | is less than>= | 4 >= 5 | False | is greater than or equal to<= | 4 <= 5 | True | is less than or equal to
The following is a list of all boolean operations supported by Python.
Operator | Examples | Result | Description=========|=================|========|====================================and | 3 < 4 and 5 < 4 | False | True if both values are True| 3 < 4 and 5 > 4 | True |---------|-----------------|--------|------------------------------------or | 3 < 4 or 5 < 4 | True | True if at-least one value is True| 3 > 4 or 5 < 4 | False |---------|-----------------|--------|------------------------------------not | not False | True | inverts the value| not True | False |
Time for a quiz and then the last part of this section!
Based on content from https://tutorial.djangogirls.org/en/python_introduction/