H a n d s o n, p r o j e c t b a s e d


Chapter 5 Using Multiple elif Blocks


Download 4.21 Mb.
Pdf ko'rish
bet93/344
Sana31.01.2024
Hajmi4.21 Mb.
#1818553
1   ...   89   90   91   92   93   94   95   96   ...   344
Bog'liq
Python Crash Course, 2nd Edition

82
Chapter 5
Using Multiple elif Blocks
You can use as many 
elif
blocks in your code as you like. For example, if the 
amusement park were to implement a discount for seniors, you could add 
one more conditional test to the code to determine whether someone quali-
fied for the senior discount. Let’s say that anyone 65 or older pays half the 
regular admission, or $20:
age = 12
if age < 4:
price = 0
elif age < 18:
price = 25
u
elif age < 65:
price = 40
v
else:
price = 20
print(f"Your admission cost is ${price}.")
Most of this code is unchanged. The second 
elif
block at u now checks 
to make sure a person is less than age 65 before assigning them the full 
admission rate of $40. Notice that the value assigned in the 
else
block at v 
needs to be changed to $20, because the only ages that make it to this block 
are people 65 or older.
Omitting the else Block
Python does not require an 
else
block at the end of an 
if
-
elif
chain. Some-
times an 
else
block is useful; sometimes it is clearer to use an additional 
elif
statement that catches the specific condition of interest:
age = 12
if age < 4:
price = 0
elif age < 18:
price = 25
elif age < 65:
price = 40
u
elif age >= 65:
price = 20
print(f"Your admission cost is ${price}.")
The extra 
elif
block at u assigns a price of $20 when the person is 65 
or older, which is a bit clearer than the general 
else
block. With this change, 
every block of code must pass a specific test in order to be executed.


if Statements
83
The 
else
block is a catchall statement. It matches any condition that 
wasn’t matched by a specific 
if
or 
elif
test, and that can sometimes include 
invalid or even malicious data. If you have a specific final condition you are 
testing for, consider using a final 
elif
block and omit the 
else
block. As a 
result, you’ll gain extra confidence that your code will run only under the 
correct conditions.

Download 4.21 Mb.

Do'stlaringiz bilan baham:
1   ...   89   90   91   92   93   94   95   96   ...   344




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling