Opening the book…
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.
This page titled 22.7: Returning True or False was last modified on Sun, 18 Sep 2022 02:06:25 GMT and is shared under a not declared license and was authored, remixed, and/or curated by Stephen Davies (allthemath.org) via source content that was edited to the style and standards of the LibreTexts platform.
The book could not be loaded just now.