elif chains extra conditions between if and else. Python checks each condition from the top and runs the block of the first one that is True:
def ticket_price(age):
if age < 6:
return 0
elif age < 18:
return 50
else:
return 100
print(ticket_price(3))
print(ticket_price(12))
print(ticket_price(40))
Output:
0
50
100
Order matters. For age = 3, both age < 6 and age < 18 are True, but only the first matching block runs. That is why age < 18 does not need to say "and at least 6" — earlier conditions already handled everything below 6.
A chain can have any number of elif blocks. The else at the end is optional; without it, a value that matches nothing falls through and no block runs.
shipping_zone with one parameter, weight (kilograms).1: "letter"10: "parcel"30: "freight""pallet"shipping_zone(0.4) returns "letter". shipping_zone(10) returns "freight".
Run your code to see the output, then press Submit.
import unittest
class TestShippingZone(unittest.TestCase):
def test_under_1_kg_is_a_letter(self):
self.assertEqual(shipping_zone(0.4), "letter")
def test_5_kg_is_a_parcel(self):
self.assertEqual(shipping_zone(5), "parcel")
def test_exactly_1_kg_is_a_parcel(self):
self.assertEqual(shipping_zone(1), "parcel")
def test_exactly_10_kg_is_freight(self):
self.assertEqual(shipping_zone(10), "freight")
def test_75_kg_is_a_pallet(self):
self.assertEqual(shipping_zone(75), "pallet")
def shipping_zone(weight):
if weight < 1:
return "letter"
elif weight < 10:
return "parcel"
elif weight < 30:
return "freight"
else:
return "pallet"
print(shipping_zone(0.4))
print(shipping_zone(5))
print(shipping_zone(10))
print(shipping_zone(75))
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.