日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

3.Booleans and Conditionals

發布時間:2023/12/10 编程问答 19 豆豆
生活随笔 收集整理的這篇文章主要介紹了 3.Booleans and Conditionals 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Booleans

Python有bool類型數據,有兩種取值:True 和 False.

[1]

x = True print(x) print(type(x)) True <class 'bool'>

我們通常從布爾運算符中獲取布爾值,而不是直接在我們的代碼中放入True或False。 這些是回答yes或no的運算符。 我們將在下面介紹其中一些運算符。

Comparsion Operations

OperationDescription?OperationDescription
a == ba equal to b?a != ba not equal to b
a < ba less than b?a > ba greater than b
a <= ba less than or equal to b?a >= ba greater than or equal to b

[2]

def can_run_for_president(age):"""Can someone of the given age run for president in the US?"""#The US constitution says you must "have attained to the Age of the thirty-five years"return age >= 35print("Can a 19-year-old run for president?", can_run_for_president(19))print("Can a 45-year-old run for president?", can_run_for_presidnet(45)) Can a 19-year-old run for president? False Can a 45-year-old run for president? True

比較運算有點聰明......

[3]

3.0 == 3 True

但不是很聰明...

[4]

'3' == 3 True

比較運算符可以與我們已經看到的算術運算符組合,以表達無限的數學測試范圍。 例如,我們可以通過模2運算來檢查數字是否為奇數:

[5]

def is_odd(n):return (n % 2) == 1print("Is 100 odd?", is_odd(100)) print("Is -1 odd?", is_odd(-1)) Is 100 odd? False Is -1 odd? True

在進行比較時,請記住使用==而不是=。 如果你寫n == 2,你會問n的值是否與2相等。 當你寫n = 2時,你正在改變n的值。

Combining Boolean Values

Python使用“and”,“or”和“not”的標準概念組合布爾值的運算符。 事實上,相應的Python運算符只使用這些單詞:and,or ,not。
有了這些,我們可以使我們的can_run_for_president函數更準確。

[6]

def can_run_for_president(age, is_natural_born_citizen):"""Can someone of the given age and citizenship status run for president in the US?"""# The US Constitution says you must be a natural born citizen *and* at least 35 years oldprint(can_run_for_president(19, True))print(can_run_for_president(55, False))print(can_run_for_president(55, True)) False False True

你能猜出這個表達式的值嗎?

[7]

True or True and False Ture

Python具有優先級規則,用于確定在上述表達式中運算的順序。 例如,and優先級高于or,這就是上面第一個表達式為True的原因。 如果我們從左到右對它進行運算,我們首先計算True或True(即True),然后計算and False,得到最終值為False。
您可以嘗試記住優先順序,但更安全的選擇是使用自由括號。 這不僅有助于防止錯誤,還可以使您的意圖更清晰,任何人都可以閱讀您的代碼。
例如,請考慮以下表達式:

prepared_for_weather = have_umbrella or rain_level < 5 and have_hood or not rain_level > 0 and is_workday

我會說今天的天氣很安全....

  • ???? 如果我有一把傘......
  • ???? 或者雨下的不是很大,我有一個帽子.....
  • ???? 否則,我仍然很好,除非正在下雨,這但是一個工作日

但不僅僅是我的代碼很難閱讀,還有一個問題,我們可以通過添加一些括號來解決這兩個問題。

prepared_for_weather = have_umbrella or (rain_level < 5 and have_hood) or not (rain_level > 0 and is_workday)

你還可以添加更多的括號,如果你認為這有助于可讀性:

prepared_for_weather = have_umbrella or ((rain_level < 5) and have_hood) or (not (rain_level > 0 and is_workday))

我們也可以將它拆分成多行來強調上面描述的3部分結構:

prepared_for_weather = (have_umbrella or ((rain_level < 5) and have_hood) or (not (rain_level > 0 and is_workday)) )

Conditionals

雖然它們本身就足夠有用,但是當與條件語句結合使用時,使用關鍵字if,elif和else,布爾語句真的開始閃耀。
條件語句(通常稱為if-then語句)允許程序員根據某些布爾條件執行某些代碼段。 Python條件語句的基本示例是:

[8]

def inspect(x):if x == 0:print(x, "is zero")elif x > 0:print(x, "is positive")elif x < 0:print(x, "is negative")else:print(x, "is unlike anything I've ever seen...")inspect(0) inspect(-15) 0 is zero -15 is negative

Python采用經常用于其它語言的if和else; 它更獨特的關鍵詞是elif,是“else if”的縮寫。 在這些條件子句中,elif和else塊是可選的; 此外,您可以包含任意數量的elif語句。

請特別注意使用冒號(:)和空格來表示單獨的代碼塊。 這與我們定義函數時發生的情況類似 - 函數頭以:結尾,后面的行用4個空格縮進。 所有后續的縮進行都屬于函數體,直到我們遇到一條未縮進的行,結束函數定義。

[9]

def f(x):if x > 0:print("Only printed when x is positive; x = ", x)print("Also only printed when x is positive; x = ", x)print("Always printed, regardless of x's value; x = ", x)f(1) f(0) Only printed when x is positive; x = 1 Also only printed when x is positive; x = 1 Always printed, regardless of x's value; x = 1 Always printed, regardless of x's value; x = 0

Boolean conversion

我們已經看到了int(),它將事物變成了int,而float()將事物變成了浮點數,所以你可能不會驚訝于Python有一個bool()函數可以將事物變成bool。

[10]

print(bool(1)) # all numbers are treated as true, except 0 print(bool(0)) print(bool("asf")) # all strings are treated as true, except the empty string "" print(bool("")) # Generally empty sequences (strings, lists, and other types we've yet to see like lists and tuples) # are "falsey" and the rest are "truthy" True False True False

如果條件語句和其他需要布爾值的地方,我們可以使用非布爾對象。 Python將隱式將它們視為相應的布爾值:

[11]

if 0:print(0) elif "spam":print("spam") spam

Conditional expressions(aka 'ternary')

根據某些條件將變量設置為兩個值中的任何一個是一種常見的模式。

[12]

def quiz_message(grade):if grade < 50:outcome = 'failed'else:outcome = 'passed'print('You', outcome, 'the quiz with a grade of', grade)quiz_message(80) You passed the quiz with a grade of 80

Python有一個方便的單行“條件表達式”語法來簡化這些情況:

[13]

def quiz_message(grade):outcome = 'failed' if grade < 50 else 'passed'print('You', outcome, 'the quiz with a grade of', grade)quiz_message(45) You failed the quiz with a grade of 45

您可能會認為這類似于許多其他語言中存在的三元運算符。 例如,在javascript中,我們將上面的賦值寫為`var outcome = grade <50? 'failed':'passed'。 (說到可讀性,我認為Python在這里是贏家。)

Your turn!

轉到練習筆記本,以獲得一些boolean和conditionals的實踐練習。

?

?

?

?

?

?

?

?

?

?

?

?

?

?

?

總結

以上是生活随笔為你收集整理的3.Booleans and Conditionals的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。