True and False
A condition has a value, just like a calculation. A comparison is either true or false, and Python has two values for that: True and False. They are called Boolean values, after the mathematician George Boole, and their type is bool:
>>> 5 > 3
True
>>> 5 == 3
False
>>> type(5 > 3)
<class 'bool'>Code whose value is True or False, such as a comparison, is called a Boolean expression. Every condition you've written so far is one: the if runs its block when the value is True and skips it when it's False.
A condition in a variable
The value of a comparison can be stored in a variable like any other value, and the variable can then be the condition of an if:
age = int(input("Age: "))
is_adult = age >= 18
print(is_adult)
if is_adult:
print("You can vote.")
20Age: 20
True
You can vote.is_adult = age >= 18 works out the comparison first and stores its value, True, in is_adult. Then if is_adult: reads almost like English. A good name for a Boolean variable answers a yes-or-no question: is_adult, has_ticket, game_over.
Writing True and False yourself
You can also write True and False straight into the code. A setting at the top of a program is a typical use:
show_tips = True
print("Welcome!")
if show_tips:
print("Tip: the Tab key indents a line.")
Welcome!
Tip: the Tab key indents a line.Change the first line to show_tips = False, and the tip disappears. Both values start with a capital letter. In small letters, true is just a name that Python doesn't know:
show_tips = true
Traceback (most recent call last):
File "main.py", line 1, in <module>
show_tips = true
^^^^
NameError: name 'true' is not defined. Did you mean: 'True'?