日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達者為師

網(wǎng)站首頁 編程語言 正文

Python語言中的if語句詳情_python

作者:程序員涵涵2021 ? 更新時間: 2022-04-30 編程語言

1.簡單介紹

每條if語句的核心都是一個值為TrueFalse的表達式,這種表達式被稱為條件測試。Python 根據(jù)條件測試的值為True還是False來決定是否執(zhí)行if語句中的代碼。如果條件測試的值為True,Python就執(zhí)行緊跟在if語句后面的代碼;如果為False,Python就忽略這些代碼。

要判斷是否相等,我們可以使用==來進行判斷:

car = 'Audi'
car.lower() == 'audi'

輸出的結(jié)果為:

true

比如說我們在測試用戶的用戶名是否與他人重合的時候我們可以使用到這個判斷。

要判斷兩個值是否不等,可結(jié)合使用驚嘆號和等號(!=),其中的驚嘆號表示不,在很多編程語言中都如此:

requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
? print("Hold the anchovies!")

輸出的結(jié)果為:

Hold the anchovies!

如果需要對多個條件進行比較,則可以使用and和or兩個符號:

num1 = 15
num2 = 20
?
num3 = 25
num4 = 30
?
if num1 == 15 and num2 == 20:
? print("All Right")
?
if num3 == 25 or num4 == 40:
? print("One of them is right")

and需要多個條件同時成立才能夠成立,而or只需要一個條件成立就能夠成立。

2.if-else語句

最簡單的if語句只有一個測試和一個操作,但是使用了if-else語句之后便可以有兩個操作:

num = 50
?
if num < 60:
? print("不及格")
else:
? print("及格了")

輸出的結(jié)果為:

不及格

if-else語句可以演變?yōu)閕f-elif-else語句,用來執(zhí)行2個以上的條件判斷對執(zhí)行對應(yīng)的操作:

num = 85
?
if num < 60:
? print("不及格")
elif 60<=num and num<=80:
? print("及格")
else:
? print("優(yōu)秀")

運行的結(jié)果為:

優(yōu)秀

3.用if語句來處理列表

我們可以把if語句和列表相結(jié)合:

food_list = ['apple', 'banana','orange']
?
for food in food_list:
? if food == 'apple':
? ? print("Apple is here")
? elif food == 'bana':
? ? print("Banana is here")
? else:
? ? print("Orange is here")

輸出的結(jié)果為:

Apple is here
Orange is here
Orange is here

或者我們可以用來檢測列表是否為空:

requested_toppings = []
if requested_toppings:
? for requested_topping in requested_toppings:
? ? print("Adding " + requested_topping + ".")
? print("\nFinished making your pizza!")
else:
? print("Are you sure you want a plain pizza?")

運行結(jié)果為:

Are you sure you want a plain pizza?

Python語言會在列表至少包含一個元素的時候返回True,而列表為空的是否返回False

當(dāng)我們有著多個列表的時候,我們可以:

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!")

行結(jié)果為:

Adding mushrooms.
?
Finished making your pizza!
Sorry, we don't have french fries.
?
Finished making your pizza!
Adding extra cheese.
?
Finished making your pizza!

原文鏈接:https://blog.csdn.net/weixin_56659172/article/details/123042350

欄目分類
最近更新