Boolean Values
Every comparison has an answer: yes or no. In Python, these answers are the values True and False, and you can print them:
print(10 < 20)
print("cat" == "dog")This prints:
True
FalseTrue and False are called boolean values, or booleans, after the mathematician George Boole. They are a new type of value, next to numbers and text; Python calls this type bool. Write them with a capital first letter and without quotes: "True" in quotes is just text, and true with a small t ends with NameError: name 'true' is not defined. Did you mean: 'True'?
You can store a boolean in a variable like any other value, and then use the variable as a condition:
age = 20
is_adult = age >= 18
print("Adult:", is_adult)
if is_adult:
print("You can vote")This prints:
Adult: True
You can voteRead the second line from right to left: Python first compares age >= 18, which gives True, and then = stores that value in is_adult. The condition if is_adult: means the same as if is_adult == True:. It's just shorter, and that's how Python programmers write it.
The names of boolean variables usually start with is_ or has_ (is_adult, has_ticket), so that they read like a yes-or-no question.
Instructions
- 1
A number is even when the remainder after dividing it by 2 is 0. Create a variable
is_evenwith the result of the comparisonnumber % 2 == 0: Python first computes the remaindernumber % 2, and then compares it with0. Then print the variable:print("Even:", is_even). The program printsEven: True. - 2
Write an
ifstatement withis_evenas its condition that printsThe number is even.