22.7: Returning True or False
- Page ID
- 88723
It’s common for a programmer to want a function which, instead of returning a number or text, tells her whether or not something is true. This lets her use the return value of such a function as the condition of an if statement.
Here’s a trivial example:
Code \(\PageIndex{1}\) (Python):
def is_old_enough_to_vote(age):
if number >= 18:
return True
else:
return False
x = is_old_enough_to_vote(13)
if x:
print("Yes, a 13-year-old can vote!")
else:
print("Alas, a 13-year-old must wait.")
if is_old_enough_to_vote(19):
print("Yes, a 19-year-old can vote!")
else:
print("Alas, a 19-year-old must wait.")
| Alas, a 13-year-old must wait.
| Yes, a 19-year-old can vote!
The values True and False are called boolean values, after the 19th-century mathematician George Boole. Note that in Python they must begin with capital letters.
The somewhat odd-looking “if x:” line is possible because x was set to the return value of a call to is_old_enough_to_vote(), and that function returned a boolean value.