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:
type=codeblock|id=py3_comparisons|autocreate=python3print(5 > 2) # Output: Trueprint(3 < 1) # Output: Falseprint(5 > 2 * 2) # Output: Trueprint(1 == 1) # Output: Trueprint(5 != 2) # Output: True
We gave Python some numbers to compare.
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.
Not only can Python compare numbers, but it can also compare method results.
type=codeblock|id=py3_compare_method_results|autocreate=python3print(len("Commonlounge") > 10)# Output: Trueprint(len("David") > 10)# Output: False
Give Python two more tasks:
type=codeblock|id=py3_compare_expressions|autocreate=python3print(6 >= 12 / 2)# Output: Trueprint(3 <= 2)# Output: False
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:
type=codeblock|id=py3_and_or|autocreate=python3print(6 > 2 and 2 < 3) # Output: Trueprint(3 > 2 and 2 < 1) # Output: Falseprint(3 > 2 or 2 < 1) # Output: True
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:
type=codeblock|id=py3_compare_int_and_str|autocreate=python3print(1 > 'python')
Traceback (most recent call last):File "", line 1, inTypeError: unorderable types: int() > 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:
type=codeblock|id=py3_boolean|autocreate=python3a = Trueprint(a)# Output: True
You can also directly assign the value of a comparison:
type=codeblock|id=py3_boolean_2|autocreate=python3a = 2 > 5print(a)# Output: False
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!
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.
Take a look at the following code.
type=codeblock|id=py3_if|autocreate=python3if 3 > 2:print('It works!')
In the first line, we have the if statement. In the next line, we give further instructions to Python which are executed if the condition 3 > 2 turns out to be true (or True for that matter).
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.
Go ahead and click Try it now! on the code above, and then click Run.
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:
type=codeblock|id=py3_if_else|autocreate=python3if 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:
5 is indeed greater than 2
If 2 were a greater number than 5, then the second command would be executed. Let's see how elif works:
type=codeblock|id=py3_elif|autocreate=python3name = 'Dave'if name == 'Commonlounge':print('Hey Commonlounge!')elif name == 'Dave':print('Hey Dave!')else:print('Hey anonymous!')
and the output:
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:
type=codeblock|id=py3_chained_elif|autocreate=python3volume = 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:
Perfect, 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:
type=codeblock|id=py3_chained_elif_concise|autocreate=python3volume = 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:
type=codeblock|id=py3_comments|autocreate=python3volume = 100# 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
- 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/