Comparison Operators
The symbols < and > that you've used in conditions are comparison operators: they compare two values, and the result is either true or false. Python has six of them:
==equal to:5 == 5!=not equal to:5 != 3>greater than:5 > 3<less than:3 < 5>=greater than or equal to:5 >= 5<=less than or equal to:3 <= 5
All the examples in the list are true. In !=, >= and <=, the equals sign always comes second, with no space in between. Watch the difference between > and >= at the boundary: 18 > 18 is false, but 18 >= 18 is true. “18 or older” is therefore age >= 18.
“Equal” is written with two equals signs, ==, because a single one already has a job. price = 100 assigns: it stores 100 in the variable price. price == 100 compares: it asks whether price is 100, and changes nothing. Writing = instead of == in a condition is one of the most common mistakes, and Python reports it right away:
price = 100
if price = 100:
print("It costs exactly 100")Traceback (most recent call last):
File "<exec>", line 2
if price = 100:
^^^^^^^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?The last line even suggests the fix: ==. (:= is something else, which you won't need in this course.)
You can compare text as well as numbers:
password = "kitten42"
if password == "kitten42":
print("Welcome back")
else:
print("Wrong password")This prints:
Welcome backTwo texts are equal only if they match exactly, character by character. Upper and lower case letters are different characters, so "Anna" == "anna" is false. "kitten42 " with a space at the end is a different text, too. And text is never equal to a number: "5" == 5 is false. Don't forget the quotes around the text you compare with. Without them, password == kitten42 makes Python look for a variable called kitten42, and the program ends with NameError: name 'kitten42' is not defined.
Instructions
- 1
Run the program: it ends with a
SyntaxError. Fix the condition so that it comparescountrywith"Czechia". Then the program printsDelivery in 3 days. - 2
An online shop offers free shipping on orders of 1500 or more. At the end of the program, write another
ifstatement that printsFree shippingiforder_totalis greater than or equal to1500.