Last time I learned if-elif-else structure , We can set three conditions to test the conditions , Actually elif Multiple can be used , Sure Use any number of... As required elif.
age=12
if age<4:
price=0
elif age<18
price=25
elif age<65
price=40
else:
price=20
print(f"you admissin cost is ${
price}")
We added a to the code elif It also adds a condition , The price for the elderly is $20. When our variable is greater than 65 The first three conditions will be skipped and the fourth condition will be executed , If the variable is 20 The output price will be 40.
stay Python It is not necessary to have else Code block , In some cases else It is useful to , But in other cases , Omit other use elif Will be clearer .
age=12
if age<4:
price=0
elif age<18
price=25
elif age<65
price=40
elif age>=65
price=20
print(f"you admissin cost is ${
price}")
else Is a very broad statement , When our conditions are not met, no matter what else It will be carried out . While using elif Must meet the conditions before it can run .
When we need to test a variety of conditions, we generally do not elif and else, Generally only if Statement to judge and output .
Let's introduce our classmates , Each student's personality is different
classnumber=['zhang','wang']
if 'zhang' in classnumber
print("shuai")
if 'wang' in classnumber
print("niu")
if 'su' in classnumber
print("gao")
When we need to introduce zhang and wang We can tell their characteristics separately when we are in the , When introduction is required su You can also tell his characteristics when you are .if Statement executes three independent tests , Instead of using elif perhaps else Such conditions .
If used as follows if-else-elif structure , Then the code will not work as we want .
classnumber=['zhang','wang']
if 'zhang' in classnumber
print("shuai")
elif 'wang' in classnumber
print("niu")
else 'su' in classnumber
print("gao")
If you test the first zhang If it passes, it will not perform the following tests, but directly output .
If you want to execute a code block, you can use if-elif-else structure , But if you want to execute multiple code blocks, you need to use a series of independent if sentence .