Python Arena
Step 4 of 5

Ranges and longer conditions

Checking that a value is between two limits is so common that Python has a shorter way to write it. Instead of grade >= 4 and grade <= 10, you can write 4 <= grade <= 10, as in mathematics:

grade = int(input("Grade (4 to 10): "))
if 4 <= grade <= 10:
    print("Grade saved.")
else:
    print("That's not a valid grade.")
Input
11
Output
Grade (4 to 10): 11
That's not a valid grade.

This is called a chained comparison. Python reads 4 <= grade <= 10 as 4 <= grade and grade <= 10, so the value in the middle is compared with both limits. Any comparison operators can be chained:

In the Python interpreter
>>> x = 7
>>> 0 < x < 10
True
>>> 1 <= x <= 5
False
>>> a = 3
>>> b = 3
>>> a == b == 3
True

The two ways mean exactly the same, and you'll meet both in Python code. The chained one is shorter, and it shows the variable between its two limits, the way you'd write it in a math class.

Longer conditions

A condition can combine as many parts as it needs, and conditions with and and or work in an elif like anywhere else. In this quiz game, a player who scores at least 90 points within 60 seconds wins gold, a player who manages one of the two wins silver, and 50 points are enough for bronze:

points = int(input("Points: "))
seconds = int(input("Time in seconds: "))
if points >= 90 and seconds <= 60:
    print("Gold medal")
elif points >= 90 or seconds <= 60:
    print("Silver medal")
elif points >= 50:
    print("Bronze medal")
else:
    print("No medal this time")
Input
95
75
Output
Points: 95
Time in seconds: 75
Silver medal

Notice the order. The and condition comes first, because it is the strictest one: it needs both parts. A result that has both parts also has at least one of them, so if the or condition came first, it would catch every gold result too, and nobody would ever win gold. The order of conditions matters just as much with and and or as without them.

Your task

Challenge 1 of 3

Fill in the blank with a chained comparison, so the program accepts the days of a month, 1 to 31:

Day of the month: 31
OK

Challenge 2

Write a program that asks for the hours and the minutes of a time on a 24-hour clock and tells whether the time is valid. The hours must be from 0 to 23 and the minutes from 0 to 59. Use two chained comparisons.

Hours: 23
Minutes: 59
That's a valid time.

Otherwise the program prints That's not a valid time.

Challenge 3

Write a program that asks for the lengths of the three sides of a triangle and tells what kind of triangle it is: Equilateral when all three sides are equal, Isosceles when exactly two are equal, and Scalene when all are different.

Side 1: 5
Side 2: 3
Side 3: 5
Isosceles