程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

0 basic learning python (14)

編輯:Python

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.

for example

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 .

for example

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 .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved