Practice: Comparison Operators
Q1. Is it adult?
Store age = 20 and print True if the age is 18 or more.
Goal: Use >= to test a limit.
Q2. Equal or not
Print whether 15 is equal to 15.0 on one line and whether it is not equal on the next.
Goal: Use == and !=.
Q3. In range
For n = 42 print True if n is between 1 and 100 inclusive, using a chained comparison.
Goal: Write a chained comparison.
Q4. Longer word
Print the longer of the two words "python" and "code" using a comparison of their lengths and an if statement.
Goal: Combine len() with comparison.
Q5. Case-free compare
Print True if the strings "Hello" and "HELLO" are equal when case is ignored.
Goal: Compare text safely.
Q6. Float equality
Print the result of checking 0.1 + 0.2 against 0.3 safely using math.isclose.
Goal: Compare floats safely.
Q7. Leap year test
Print True if 2024 is a leap year: divisible by 4 and not by 100, or divisible by 400.
Goal: Combine comparisons with and/or.
Q8. Basic results
What does this print?
print(5 > 3)
print(5 < 3)
print(5 == 5)
print(5 != 5)Goal: Evaluate comparisons.
Q9. String order
What does this print?
print("cat" < "dog")
print("Cat" < "cat")
print("b" > "apple")
print("abc" < "abcd")Goal: Predict string comparisons.
Q10. List order
What does this print?
print([1, 5] < [2, 0])
print([3, 1] > [3])
print((1, 2) == (1, 2))
print([1, 2] == (1, 2))Goal: Predict sequence comparisons.
Q11. Chain results
What does this print?
x = 7
print(1 < x < 10)
print(10 > x > 8)
print(x == 7 < 9)
print(3 < 5 > 4)Goal: Evaluate chained comparisons.
Q12. Equal or same
What does this print?
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b, a is b, a is c)
c.append(4)
print(a == b, a)Goal: Understand == versus is.
Q13. Mixed types
What does this print?
print(3 == "3")
print(3 == 3.0)
print(True == 1)
print("" == 0)Goal: Compare mixed types.
Q14. Not a number
What does this print?
nan = float("nan")
print(nan == nan)
print(nan != nan)
print(nan < 1)Goal: Know NaN behaviour.
Q15. Assignment bug
This code should print True when x is 5, but it is a syntax error. Fix it.
x = 5
if x = 5:
print(True)Goal: Fix = vs ==.
Q16. Input compare bug
This code should print Adult for input 20 but raises a TypeError. Fix it (the text "20" stands for typed input).
age = "20" # pretend this came from input()
if age >= 18:
print("Adult")Goal: Convert input before comparing.
Q17. Float equality bug
This code should print Equal but prints Different. Fix it.
a = 0.1 + 0.2
if a == 0.3:
print("Equal")
else:
print("Different")Goal: Fix float comparison.
Q18. Meaning of is
Explain the difference between == and is in one or two sentences.
Goal: Distinguish == and is.
Q19. Chain meaning
Explain what 5 < x < 10 means and why it is useful.
Goal: Explain chained comparison.
Q20. Ticket price
A ticket costs 5 for ages under 12, 10 for ages 12 to 59, and 7 for 60 and over. Print the price for age 65.
Goal: Use comparisons in decisions.