Programs make decisions all the time. Is the password correct? Has the student passed? Is the cart empty? Before you can write the if statements that make decisions → Chapter 11, you need a way to ask questions and get yes-or-no answers. That's what this chapter is about: comparisons, which ask questions, and logic, which combines the answers.
5.1 Asking a question: comparison operators
A comparison asks a question about two values and answers with a Boolean: True or False (the bool type from Chapter 2).
Operator
Question
Example
Result
==
equal to?
5 == 5
True
!=
not equal to?
5 != 5
False
<
less than?
3 < 8
True
>
greater than?
3 > 8
False
<=
less than or equal to?
8 <= 8
True
>=
greater than or equal to?
3 >= 8
False
age=19print(age>=18)print(age==21)print(age!=21)
Output
True
False
True
A comparison is an expression, so its result is a value you can print, store in a variable, or combine with other values:
Read passed = marks >= 35 as "passed gets the answer to the question is marks at least 35?". Comparisons are done before assignment, because = has the lowest priority of all.
Two-character operators must be typed without a space and in the right order: >=, not > = or =>.
True == 1 is True because, as Chapter 2 hinted, a bool is a kind of integer, with True worth 1 (section 5.12 explains).
Never test floats with ==
Remember from Chapter 2 that floats are approximate. That makes == unreliable for them:
print(0.1+0.2==0.3)print(0.1+0.2)
Output
False
0.30000000000000004
Mathematically the answer is True, but the float sum is a tiny bit more than 0.3, so == says no. The fix is to ask whether two floats are close enough: subtract them, take the size of the difference with abs, and check it's smaller than some tiny amount (called a tolerance):
print(abs((0.1+0.2)-0.3)<1e-9)
Output
True
1e-9 is 0.000000001: two floats that differ by less than that are treated as equal. The math module has a ready-made function for this, math.isclose, which picks a sensible tolerance for you → Chapter 17:
importmathprint(math.isclose(0.1+0.2,0.3))
Output
True
Practice 5.2
Multiple choice
What does this line print?
print(0.1*3==0.3)
Floats are stored in binary, and most of them are slightly off.
The product is a tiny bit more than 0.3, and == accepts only an exact match.
The answer is: False
Floats are approximate, so == is unreliable for them. Compare floats with a tolerance.
Fill in the blank
Fill in the comparison operator so that the line asks: is the difference smaller than the tolerance?
total=0.1+0.2print(abs(total-0.3)1e-9)
The finished program prints:
Target
True
abs() gives the size of the difference. 1e-9 is the tolerance.
Two floats are close enough when the difference is less than the tolerance.
total=0.1+0.2print(abs(total-0.3)<1e-9)
The difference between the two floats is far smaller than 1e-9, so they are treated as equal.
Write code
Close enough. Store 0.1 * 3 in a variable named total. Print two lines: first the result of comparing total with 0.3 using ==, then the result of a tolerance test that asks whether total and 0.3 differ by less than 1e-9. Each line is True or False.
The program prints the lines below. Your program must print exactly these lines.
Example run
False
True
Output
The tolerance test has three steps: subtract, take the size with abs(), compare with 1e-9.
The second line is print(abs(total - 0.3) < 1e-9). Write the first line yourself.
< and > on strings compare in dictionary order (also called lexicographic order). Python compares the first characters; if they're the same, it moves on to the second characters, and so on, until it finds a difference:
print("apple"<"banana")# 'a' comes before 'b'print("apple"<"apricot")# 'ap' same, then 'p' comes before 'r'print("cat"<"catch")# a prefix comes before the longer word
Output
True
True
True
Every character has a number
"Comes before" is decided by each character's Unicode code point, the number from Chapter 1. The built-in ord() shows it (you'll explore it in → Chapter 9):
Digits come before capital letters, which come before lowercase letters. That leads to two surprises:
print("Zebra"<"apple")print("10"<"9")
Output
True
True
"Zebra" comes before "apple" because Z (90) is less than a (97): every capital comes before every lowercase letter. And "10" comes before "9" because, as text, Python compares the first characters, "1" and "9", and never looks at the rest. When numbers are stored as text, they don't sort like numbers. Convert them to real numbers first → Chapter 6.
Capitals count for ==. For <, Python compares the first characters, and moves on only when they are the same.
Every capital letter comes before every lowercase letter. Text made of digits is compared like words, not like numbers.
It prints
False
True
True
True
Strings are compared character by character, by code point: digits first, then capitals, then lowercase letters.
5.4 Comparing different types
== and != work between any two values. Values of unrelated types are simply never equal:
print(5=="5")print(5!="5")print(None==0)
Output
False
True
False
5 is a number and "5" is text, so they're not equal. No error, just False. This is a common source of bugs when a number arrives as text (for example from user input), because the comparison quietly fails → Chapter 6.
Ordering comparisons (<, >, <=, >=) between unrelated types make no sense, so they're an error:
print(10<"20")
Output
Traceback (most recent call last):
File "compare.py", line 1, in <module>
print(10 < "20")
^^^^^^^^^
TypeError: '<' not supported between instances of 'int' and 'str'
Is the number 10 less than the text "20"? There's no sensible answer, so Python refuses.
Practice 5.4
Multiple choice
Three of these lines run. Which one stops with a TypeError?
== and != work between any two values.
Putting a number and a piece of text in order makes no sense, so Python refuses.
The answer is: print(3 <= "3")
Values of unrelated types are simply never equal. Ordering them with <, >, <= or >= is a TypeError.
5.5 Chained comparisons
In maths you write 0 ≤ marks ≤ 100 to say "marks is between 0 and 100". Python lets you write exactly that:
This is called a chained comparison. Python treats a < b < c as a < b and b < c: both comparisons must be true. (and is explained in the next section.) The middle value b is worked out only once. You can chain as many as you like:
print(1<2<3<4<5)print(1<2>3)
Output
True
False
The second line means 1 < 2 and 2 > 3. It's legal, but it reads strangely; keep chains to the "between" pattern.
Practice 5.5
Fill in the blank
Fill in both blanks so that the line asks: is speed between 30 and 80?
speed=60print(30speed80)
The finished program prints:
Target
True
Python lets you write the "between" pattern from maths directly.
Both operators point the same way: 30 is the low end and 80 is the high end.
speed=60print(30<=speed<=80)
A chained comparison means: 30 is at most speed, and speed is at most 80. Both parts must be true.
Fix the bug
This should print True, because the score is more than 50. It prints False. Fix the second line and keep score = 80.
The program prints the lines below. Your program must print exactly these lines.
Example run
True
Output
Chaining applies to == too. Python reads the line as score > 50 and 50 == True.
score > 50 already is a Boolean. Nothing more is needed.
score=80print(score>50)
The line is a chain, and 50 == True is False. Comparing with == True is never needed.
5.6 Combining answers: and, or, not
Real questions often have several parts. Can this person vote? They must be 18 or older and be a citizen. Is it the weekend? It's Saturday or Sunday. Python's logical operators combine Booleans in exactly this way:
A truth table lists every possible combination of inputs and the result. These three tables define the operators completely:
a
b
a and b
a or b
True
True
True
True
True
False
False
True
False
True
False
True
False
False
False
False
a
not a
True
False
False
True
In words: and is only true if everything is true. or is only false if everything is false.
or in Python is inclusive: True or True is True. (In everyday English, "tea or coffee?" often means one but not both. That "one but not both" idea is called exclusive or, or XOR; one of the practice problems builds it.)
Precedence of the logical operators
When an expression mixes them, not is done first, then and, then or. All three are lower than comparisons, which are lower than arithmetic (look back at the table in Chapter 4). So this needs no brackets:
Because and is done before or, the first line means True or (False and False). When you mix and and or, always add brackets to show what you mean.
Similarly, not is lower than ==, so not a == b means not (a == b). That's usually what you want, but a != b says the same thing more clearly.
Negating a condition: De Morgan's laws
Sometimes you need the opposite of a combined condition. "Not (A and B)" is not "(not A) and (not B)". Two rules, called De Morgan's laws, tell you how to flip them correctly:
not (a and b) is the same as (not a) or (not b)
not (a or b) is the same as (not a) and (not b)
When you push a not inside the brackets, and turns into or, and or turns into and. For example, "marks is not between 0 and 100" is:
The chain is an and of two comparisons. Its opposite is an or of the two opposite comparisons.
Write code
Free delivery. Delivery is free when the total is at least 50 dollars, or when the customer is a member. Store the total in total and the membership in member (True or False). Print one line, True or False, for each of these three customers, in this order: total 45 and not a member, total 45 and a member, total 60 and not a member.
The program prints the lines below. Your program must print exactly these lines.
Example run
False
True
True
Output
One of the two conditions is enough. Which logical operator is true when at least one side is true?
Write total >= 50 or member, print it, then store the values of the next customer and print again.
or is true when at least one side is true, so a large total or a membership is enough.
5.7 Short-circuit evaluation
Look at the truth tables again. If the left side of and is False, the answer is Falsewhatever the right side is. If the left side of or is True, the answer is True whatever the right side is. Python takes advantage of this: it doesn't even look at the right side when the left side already decides the answer. This is called short-circuit evaluation.
You can prove it. Dividing by zero is an error, but here it's never done:
print(Falseand1/0)print(Trueor1/0)
Output
False
True
In both lines, Python stopped after the left side, so 1 / 0 never ran.
This isn't just a curiosity. It lets you put a guard on the left that protects the right:
count=0total=50print(count!=0andtotal/count>10)
Output
False
If count is 0, the left side is False, so Python never reaches the division that would crash. If count isn't zero, the division is safe. Put the cheap, protective check first, and the risky or expensive one second.
Practice 5.7
Multiple choice
What does this program print?
count=0print(count!=0and10/count>2)
Work out the left side of and first. What is count != 0 here?
When the left side of and is False, Python does not look at the right side.
The answer is: False
The left side is False, so and stops there. The division on the right never runs.
Fix the bug
This should print False when there are no matches. It crashes with a ZeroDivisionError. Fix the last line and keep the two values.
The program prints the lines below. Your program must print exactly these lines.
Example run
False
Output
Python works out the left side of and first. Which side has the division now?
Put the protective check on the left and the risky division on the right.
A guard works only on the left of and. When it is False, Python never reaches the division.
5.8 Truthiness
So far, and, or and not have worked on True and False. But Python lets you use any value where a true-or-false answer is needed. Every value counts as either true or false; programmers say it's truthy or falsy.
The rule is simple: these values are falsy, and everything else is truthy.
Falsy values
False
the Boolean
None
no value
0, 0.0, 0j
zero, of any number type
""
the empty string
[], (), {}, set(), range(0)
empty collections → Chapter 25
In short: zero, empty and nothing are false. The built-in bool() shows how any value counts:
"False" and "0" are non-empty strings, so they're truthy; Python doesn't read the text inside them. " " (a single space) isn't empty either: it contains one character.
Truthiness makes conditions short and natural. Instead of asking "is the name not equal to the empty string?", you can just ask "is there a name?" You'll use this all the time with if→ Chapter 11 and while→ Chapter 13.
Zero, empty and nothing are falsy. Everything else is truthy.
A string is falsy only when it has no characters. Python does not read the text inside it.
It prints
True False True
False True False
"no" and "0" are strings that are not empty, so they are truthy. -5 is not zero, so it is truthy too.
Multiple choice
Three of these values are truthy. Which one is falsy?
Three of the four values are strings. When is a string falsy?
Zero of any number type is falsy.
The answer is: 0.0
The three strings all contain one or more characters, so they are truthy. 0.0 is zero, so it is falsy.
5.9 What and and or really give back
Here's something most beginners don't know. and and or don't always give back True or False. They give back one of their operands: the one that decided the answer.
a or b: if a is truthy, the answer is a (no need to look further). Otherwise it's b.
a and b: if a is falsy, the answer is a. Otherwise it's b.
print(3or5)print(0or5)print(3and5)print(0and5)
Output
3
5
5
0
Walk through them: 3 or 5 → 3 is truthy, so the answer is 3. 0 or 5 → 0 is falsy, so the answer depends on 5, and that's what you get. 3 and 5 → 3 is truthy, so 5 decides. 0 and 5 → 0 is falsy, so it's the answer straight away.
With real Booleans, this gives exactly the truth tables from section 5.6, so you've been using it all along. With other values, it gives a very handy idiom for default values:
"Use name, or if it's empty, use "Guest"." You'll see value or default all over real Python code.
not is different: it always gives back a real bool:
print(not0)print(not"hello")
Output
True
False
Watching short-circuiting happen
Remember from Chapter 2 that print gives back None, which is falsy. That lets you see exactly which parts of an or actually run:
print(print("left")orprint("right"))
Output
left
right
None
The left print runs, shows left and gives back None. That's falsy, so or must look at the right side: right is shown, and its None becomes the answer, which the outer print displays. Now change or to and:
print(print("left")andprint("right"))
Output
left
None
The left side gave back None, which is falsy, so and stops. right is never printed.
or gives back its left operand when that operand is truthy. Otherwise it gives back the right one.
and gives back its left operand when that operand is falsy. not always gives a real Boolean.
It prints
7
0
none given
False
and and or give back one of their operands, the one that decided the result. not always gives True or False.
Fill in the blank
Fill in the operator so that the program prints the name, or Guest when the name is empty.
name=""print(name"Guest")
The finished program prints:
Target
Guest
This is the idiom for default values from this section.
Read it out loud: use the name, ... if it is empty, use Guest.
name=""print(nameor"Guest")
The empty string is falsy, so or gives back its right side, the default value.
Write code
Default city. Store the empty string in a variable named city. Print city, or the text Unknown when city is empty, using one expression and no bool(). Then store "Lima" in city and print with the same expression again. The program prints two lines.
The program prints the lines below. Your program must print exactly these lines.
Example run
Unknown
Lima
Output
An empty string is falsy. Which operator gives back its right side when the left side is falsy?
city or "Unknown" gives back city when it has text, and the default when it is empty.
5.10 A very common bug
Here's a mistake almost every beginner makes. We want to check whether day is a weekend day:
day="Mon"print(day=="Sat"or"Sun")
Output
Sun
We expected False, but got Sun! In English, "day is Saturday or Sunday" makes sense. But Python reads it as (day == "Sat") or ("Sun"). The left part is False, so or gives back the right part, the string "Sun", which is truthy. Used in an if, this "condition" would always be true, whatever the day.
Each side of or must be a complete question:
day="Mon"print(day=="Sat"orday=="Sun")
Output
False
(There's an even neater way to write this using in and a collection of days: day in ("Sat", "Sun")→ Chapter 30.)
Practice 5.10
Multiple choice
What does this program print?
drink="tea"print(drink=="milk"or"juice")
Python reads the line as (drink == "milk") or ("juice").
The left part is False, so or gives back its right operand as it is.
The answer is: juice
The right side of or is a plain string, not a question. or gives it back, and it is truthy.
5.11 Identity: is and is not
== asks whether two values are equal. is asks a different question: are these the same object in memory? Remember the label picture from Chapter 3: two names can be tied to one object, or to two separate objects that happen to look the same.
Lists show the difference clearly. A list is a collection of values in square brackets → Chapter 25:
a and b are two different lists with the same contents: equal, but not the same object. c = a ties a second label to the very same list as a, so a is c is True. x is y is the same question as id(x) == id(y) from Chapter 3. is not is the opposite: a is not b is True here.
When to use is
Use is for exactly one common job: checking for None.
There's only ever one None object, so is None is the precise and recommended way to ask "is there no value?". PEP 8 says to always write x is None, never x == None.
For everything else, especially numbers and strings, use ==. Whether two equal numbers or strings are the same object depends on internal speed tricks (like the small-integer cache from Chapter 3), which can change between Python versions. Python even warns you if you write x is 5:
SyntaxWarning: "is" with 'int' literal. Did you mean "=="?
Practice 5.11
Multiple choice
Which line is the recommended way to ask whether result has no value?
There is only ever one None object.
Identity is the precise test here, not equality.
The answer is: print(result is None)
There is only one None object, so is None asks exactly the right question.
Like ==, it's case-sensitive: "Py" isn't in "python". in really comes into its own with collections — is this student in the list? is this word in the dictionary?→ Chapter 25.
Here's the complete set of comparison operators. They all have the same precedence and can all be chained:
Kind
Operators
Value comparisons
==!=<<=>>=
Identity
is, is not
Membership
in, not in
Practice 5.12
Fill in the blank
Fill in the membership operators so that both lines print True.
in is case-sensitive, like ==: th is inside python, and Th is not.
5.13 How Python does logic
Practice 5.13
Write code
Count the true ones. Store the result of each of these three comparisons in its own variable: is 7 greater than 3, is "b" inside "bus", is 0.5 greater than 1. Then print one line: how many of the three are true, found by adding the three variables.
The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
2
Output
A comparison can be stored: first = 7 > 3.
True is worth 1 and False is worth 0, so + counts the true ones.
bool is a kind of int. Adding Booleans counts how many of them are True.
+ Practice
Questions with a Check button are checked on this page. Use the hints when you are stuck: the last step always shows the answer. The other questions show the book's answer, so that you can compare.
Questions
Check yourself
What's the difference between x = 5 and x == 5?
Show the answer
x = 5 assigns: it makes x refer to 5. x == 5 compares: it asks whether x equals 5 and gives True or False.
Check yourself
Why does 0.1 + 0.2 == 0.3 give False? Write a comparison that correctly checks whether they're equal.
Show the answer
Floats are stored in binary and are slightly off, so the sum is 0.30000000000000004. Use abs((0.1 + 0.2) - 0.3) < 1e-9 or math.isclose(0.1 + 0.2, 0.3).
Check yourself
Why is "Zebra" < "apple" true? Why is "10" < "9" true?
Show the answer
Strings compare by code point, and every capital letter (Z is 90) comes before every lowercase letter (a is 97). As text, "10" and "9" are compared by their first characters, and "1" comes before "9".
Check yourself
What does 5 == "5" give? What does 5 < "5" give?
Show the answer
False: a number and a string are never equal. 5 < "5" is a TypeError, because Python can't order an int and a string.
Check yourself
Rewrite x >= 10 and x <= 20 as a chained comparison.
Show the answer
10 <= x <= 20.
Check yourself
Using De Morgan's laws, rewrite not (is_raining or is_cold) without brackets around an or.
Show the answer
not is_raining and not is_cold.
Check yourself
Explain what short-circuit evaluation is, and why count != 0 and total / count > 5 never divides by zero.
Show the answer
Python stops evaluating and as soon as the answer is known. If count != 0 is False, the whole and must be False, so the division on the right is never run.
Check yourself
List six falsy values. Is "0" truthy or falsy? Why?
Show the answer
False, None, 0, 0.0, "", [] (also 0j, (), {}, set()). "0" is truthy: it's a non-empty string, and Python doesn't look at what the text says.
Check yourself
What does "" or "default" give? What does "hello" and 0 give?
Show the answer
"default", because "" is falsy. 0, because "hello" is truthy, so and gives back the right side.
Check yourself
Why should you write x is None but x == 5?
Show the answer
There's only one None object, so identity is exactly the right test. Equal numbers may or may not be the same object, depending on internal details, so numbers must be compared by value with ==.
Numbers are compared by value, so the type does not matter. Is 10 different from 10.0?
Strings are compared one character at a time. Every capital letter comes before every lowercase letter.
It prints
True False False
True True True
10 != 10.0 is False because the values are equal. "Cat" < "cat" because C (67) is less than c (99). "b" > "abc" because the first characters already differ, and b comes after a.
This should print whether score_a (stored as text, "9") is a lower score than score_b ("10"). It prints False.
The program prints the lines below. Your program must print exactly these lines.
Example run
True
Output
Both scores are text, so < uses dictionary order. Which first character comes earlier, "9" or "1"?
Store the two scores as numbers, without quotes.
score_a=9score_b=10print(score_a<score_b)
As text, "9" comes after"10". Compare numbers, not strings. (Turning text into a number with int() is covered in → Chapter 6.)
score_a=9score_b=10print(score_a<score_b)
Output
True
Fix the bug
This should print True only when the age is from 13 to 19 inclusive. It crashes.
Keep age = 16 on the first line.
The program prints the lines below. Your program must print exactly these lines.
Example run
True
Output
Two things are wrong on the second line. One of them is the order of the two characters in the operator.
The right side of and has no value on its left to compare. A chained comparison with two <= is the shortest fix.
age=16print(13<=age<=19)
=< isn't an operator (it's <=), and each side of and needs its own complete comparison. A chained comparison is neatest.
age=16print(13<=age<=19)
Output
True
Coding problems
Write code · Easy
Can they vote?. Store an age and whether the person is a citizen (True/False). Print True if they can vote: at least 18 and a citizen. Test with three different people.
Test these three people, in this order: 20 years old and a citizen, 16 years old and a citizen, 30 years old and not a citizen. Print one line for each person: True or False.
The program prints the lines below. Your program must print exactly these lines.
Example run
True
False
False
Output
Two conditions must both hold. Which logical operator is true only when both sides are true?
Compare the age with 18 using >=, and join that to the citizen value with and. Store new values and print again for the next person.
Password check. Store a password and a confirm value. Print True only if they match and the password isn't empty. Use truthiness for the "not empty" part. (Checking for a minimum length needs len()→ Chapter 7.)
Test two cases, in this order: both values are "sunny123", then both values are the empty string. Print one line for each case, and wrap the expression in bool() so that each line is True or False.
The program prints the lines below. Your program must print exactly these lines.
Example run
True
False
Output
An empty string is falsy, so the name password alone can stand for the question: is the password not empty?
password and password == confirm gives back the empty string itself in the second case. bool() turns that into False.
password must be truthy (not empty) and equal to confirm. Note that password and ... gives back password itself if it's empty, so wrap the whole thing in bool() to always print True or False.
Leap years. A year is a leap year if it's divisible by 4 but not by 100, or it's divisible by 400. Print whether each of 1900, 2000, 2024 and 2026 is a leap year, using one Boolean expression.
Print four lines, in the order 1900, 2000, 2024, 2026. Each line has the year, one space, then True or False.
The program prints the lines below. Your program must print exactly these lines.
Example run
1900 False
2000 True
2024 True
2026 False
Output
A year is divisible by 4 when year % 4 == 0.
Put the part with and inside brackets, then join the test for 400 to it with or. Print the year and the expression with one print and a comma.
The brackets aren't strictly needed (and is done before or), but they make the meaning obvious.
Write code · Medium
Valid triangle. Three lengths can form a triangle only if each one is less than the sum of the other two. Store three sides and print whether they form a triangle. Test with 3, 4, 5 and with 1, 2, 10.
Test the sides 3, 4, 5 first, then 1, 2, 10. Print one line for each test: True or False.
The program prints the lines below. Your program must print exactly these lines.
Example run
True
False
Output
There are three questions, one for each side, and every one of them must be true.
Each question has the form: one side < the sum of the other two. Join the three with and.
Out of range. Print whether a temperature reading is outside the safe range of 2 °C to 8 °C (a vaccine fridge), in two ways: once with not and a chained comparison, and once using or without not.
Use the reading 9.5. Print two lines: first the version with not and a chained comparison, then the version with or.
The program prints the lines below. Your program must print exactly these lines.
Example run
True
True
Output
Inside the range is 2 <= temperature <= 8. Outside is the opposite of that.
For the second line, think of the two ways to be outside: below 2, or above 8.
not is lower than comparisons, so not 2 <= temperature <= 8 means not (2 <= temperature <= 8).
Write code · Hard
Build XOR. Python has no logical XOR operator for Booleans. Write an expression using only and, or and not that's True when exactly one of a and b is True. Print its value for all four combinations of a and b. Then show that a != b gives the same answers.
Print four lines, for the combinations in this order: True True, True False, False True, False False. On each line print four values with one print and commas: the first Boolean, the second Boolean, your expression, then the result of comparing the two with !=.
The program prints the lines below. Your program must print exactly these lines.
Prove De Morgan. For all four combinations of a and b, print not (a and b) next to (not a) or (not b), and not (a or b) next to (not a) and (not b), to show that each pair always matches.
Print four lines, for the combinations in this order: True True, True False, False True, False False. On each line print the four expressions in the order of the question, with one print and commas.
The program prints the lines below. Your program must print exactly these lines.
In every row, the first two values match and the last two values match. Testing all combinations like this, instead of trusting a rule, is a habit good programmers keep. (A loop would remove all this repetition → Chapter 15.)
Write code · Hard
Safe ratio. For each pair (goals, matches) of (10, 0), (10, 4) and (10, 2), print whether the player averages more than 2.5 goals per match. The first pair must not crash. Use short-circuiting.
Print three lines, one for each pair in the order given: True or False.
The program prints the lines below. Your program must print exactly these lines.
Example run
False
False
True
Output
Dividing by zero stops the program. Which check can stand on the left of and so that the division is skipped?
Write matches != 0 and ... with the division and the comparison with 2.5 on the right.
For (10, 4) the average is exactly 2.5, which is not more than 2.5.
Chapter project: Ride gate
Project
Who may go on the ride? A theme park ride has two rules. The rider must be from 120 to 195 cm tall, inclusive. And the rider must be 12 years old or more, or be with an adult.
Check these three riders, in this order:
name "Maya", height 150, 14 years old, not with an adult
name "" (the name was left empty), height 118, 30 years old, with an adult
name "Leo", height 125, 9 years old, with an adult
For each rider, print one line with three values, using one print and commas: the name (or the text Guest when the name is empty), whether the height is in the range, and whether the rider may go on the ride.
Keep the last value of each rider in its own variable. Finish with a fourth line: the text Riders let in: and then how many of the three riders may go, found by adding the three stored Booleans.
The program prints the lines below. Your program must print exactly these lines.
Example run
Maya True True
Guest False False
Leo True True
Riders let in: 2
Output
Store the four facts about a rider first. The height test is a chained comparison, and it is worth a variable of its own because you print it and use it again.
The second rule mixes and with or, so use brackets: the height test and (the years test or the adult value). The default name uses the value or default idiom.
True is worth 1 and False is worth 0. Adding the three stored results gives the number of riders who may go.
name="Maya"height=150years=14with_adult=Falsetall=120<=height<=195first=talland(years>=12orwith_adult)print(nameor"Guest",tall,first)name=""height=118years=30with_adult=Truetall=120<=height<=195second=talland(years>=12orwith_adult)print(nameor"Guest",tall,second)name="Leo"height=125years=9with_adult=Truetall=120<=height<=195third=talland(years>=12orwith_adult)print(nameor"Guest",tall,third)print("Riders let in:",first+second+third)
The program combines a chained comparison, and with or in brackets, a default value with or, and Booleans added like numbers.