Home and Learn: Free Python Course
There is a problem with the code we wrote in the previous section. It's going to be very impractical to test a range of ages using the techniques outlined. Instead, we can use something called Conditional Operators. These allow you to ask if something is greater than or less than a value. There are also Conditional Operators for greater than or equal to and less than or equal to. You can also test for not equal to. Here are the symbols used for conditional operators in python.
Operator | Meaning |
---|---|
== | Has a value of |
> | Greater than |
< | Less than |
>= | Greater than or equal to |
<= | Less than or equal to |
!= | Does not have a value of |
Let's see how to use them.
If you want to test if the value inside of one python variable is greater than another, use the > symbol:
if int(age) > 21:
print("You are older than 21)
Try the code out. In the statement above, if you enter a number higher than 21 then the print line will get executed.
Add an else part:
if int(age) > 21:
print("You are older than 21")
else:
print("You're not older than 21.")
Now switch the symbol to this one <. Change the message, as well:
if int(age) < 21:
print("You are younger than 21")
else:
print("You are older than 21.")
When you test the code above out, you'll notice that you can't enter exactly 21 without the output window insisting that you are older than 21.
You can use two equals sign to solve that (or the is keyword):
if int(age) < 21:
print("You are younger than 21")
elif int(age) > 21:
print("You are older than 21")
elif int(age) == 21:
print("You are 21")
The last one could have just been:
else:
print("You are 21")
But with two equal signs you can test for an exact value.
An example of the >= and <= symbols is this:
if int(age) <= 0:
print("Enter a value greater than zero")
elif int(age) >= 21:
print("You are old enough to enter")
else:
print("You are not old enough to enter")
We're now testing the variable for values that are greater than or equal to a number, and values that are less than or equal to a number. The else part at the end catches values that are greater than zero and less than 21.
In the next lesson, you'll learn about the Logic Operators and how to use them with If statements.