1. 程式人生 > >Python(13)_if語句

Python(13)_if語句

epp for循環語句 不為 不包含 neapp ice extra code 代碼塊

#  if 語句與for循環語句,這個模式在實際編程中經常用
cars = [audi,bmw,subaru,toyota]
for car in cars:
    if car == bmw:
        print(car.upper())
    else:
        print(car.title())

技術分享圖片


程序2 :if語句

# if語句
age =7;
if age>=18:
    print("You are old enough to vote!")
# if與else
if age>=18:
    print("You are old enough to vote!
") else: print("Sorry,you are too young to vote.")

技術分享圖片


程序3 :使用多個elif代碼塊

# 使用多個elif代碼塊
age = 12
if age<4:
    price = 0
elif age<18:
    price = 5
elif age<65:
    price=10
else:
    price =5

print("Your admission cost is $"+str(price)+".")

技術分享圖片


程序:4:省略else代碼塊

‘‘‘else 是一條包羅萬象的語句,只要不滿足任何if 或elif 中的條件測試,其中的代碼就會執行,這可能會引入無效甚至惡意的數據。如果知道最終要測試的條件,應考慮使用
一個elif 代碼塊來代替else 僅當滿足相應的條件時,你的代碼才會執行。
‘‘‘ # 省略else代碼塊 age = 98 if age<4: price = 0 elif age<18: price = 5 elif age<65: price=10 elif age>=65: price =5 print("Your admission cost is $"+str(price)+".")


程序6:if語句下嵌套for循環

‘‘‘在這裏,我們首先創建了一個空列表,其中不包含任何配料。在處我們進行了簡單檢查,而不是直接執行for 循環。在if 語句中將列表名用在條件表達式中
時,Python將在列表至少包含一個元素時返回True ,並在列表為空時返回False 。如果requested_toppings 不為空,就運行與前一個示例相同的for 循環;否則,就打印
一條消息,詢問顧客是否確實要點不加任何配料的普通比薩
‘‘‘ requests =[] if requests: for request in requests: print("Adding "+request+".") print("\nFinished making your pizza") else: print("Are you sure you want a plain pizza")

技術分享圖片


程序7:多個列表,這種形式的在實際編碼中也常見

# 多個列表,這種形式的在實際編碼中也常見
available_toppings = {mushrooms,olives,green peppers,pepperoni,pineapple,extra cheese}
requested_toppings = {mushrooms,french fries,extra cheese}
for requested_topping in requested_toppings:
    if requested_topping in available_toppings:
        print("Adding "+requested_topping+".")
    else:
        print("Sorry,we don‘t have "+requested_topping)
print("\nFinished making your pizza")

技術分享圖片

Python(13)_if語句