iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 14
0
自我挑戰組

30天學會Python系列 第 14

Python - Condition 條件式

  • 分享至 

  • xImage
  •  

Conditions

比較式 Comparisons:

描述 運算子
等於(Equal) ==
不等於(Not equal) !=
大於(Greater than) >
小於(Less than) <
大於等於(Greater or Equal) >=
小於等於(Less or Equal) <=
物件相等(Object Identity) is
物件不相等(Negated Object Identity) is not

Comparision

language = 'Python'
if language == 'Python':
    print('Language is Python')
elif language == 'Java':    
    print('Language is Python')
else:    
    print('No match')

PS: Python doesn't have a switch case
值得一提的是,Python中並沒有switch的語法,所有case的判斷可以用if elif else代替

參考:
https://docs.python.org/3/library/stdtypes.html#comparisons

布林運算 Boolean operations

  • and
  • or
  • not
user = 'Admin'
logged_in = True
# if user == 'Admin' and logged_in:
# if user == 'Admin' or logged_in:
if not logged_in:    
    print('Admin page')
else:
    print('Bad Creds')

參考:
https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not

False Values:

在Python中能表達False功能的有下列幾項:

  • False
  • None
  • Zero of any numeric type 任何為零的數值
  • Any empty sequence. For example: '', (), []. 任何為空的序列
  • Any empty mapping. For example, {}. 任何空的map類型
condition = False
# condition = 10
# condition = []
# condition = {}
# condition = ''
if condition:
    print('Evaluated to True')
else:
    print('Evaluated to False')

is/== difference
is 是物件間的相等,==為值相等,可透過查看物件id得知

# is/ ==
a = [1,2,3]
b = [1,2,3]
print(a is b)
print(a == b)
print(id(a) == id(b))
print(id(a))
print(id(b))
'''b is reference of a'''
a = [1,2,3]
b = a
print(a is b)
print(a == b)
print(id(a) == id(b))
print(id(a))
print(id(b))

Reference

Boolean operations
https://docs.python.org/3/library/stdtypes.html#comparisons

id() Built-in function - 官網 document
https://docs.python.org/3/library/functions.html#id

Identity comparisons - 官網 document
https://docs.python.org/3/reference/expressions.html#is

補充

"is" operator behaves unexpectedly with integers - stackoverflow
不是很確定Python中內部運作的情形,不過大致上理解為Python實作中保留了一個陣列,裡面存放了 [-5, 256] 範圍中的所有整數物件,當你創造了一個在此範圍內的整數,則會得到陣列中已存在的整數物件的reference,大家可以試試看下列程式碼:

a = -5
b = -5
print(a is b)
print(a == b)
print(id(a) == id(b))
print(id(a))
print(id(b))

a = -6
b = -6
print(a is b)
print(a == b)
print(id(a) == id(b))
print(id(a))
print(id(b))

會發現當令a = -5,b = -5時,兩者為同一物件(a is b -> True)、且值也相等(a == b -> True)、兩者的id也指向同一個位置(id(a) == id(b) -> True),但當令a = -6, b = -6時卻有了相反的結果,雖然值相等,但兩者並非同一物件、id位置也不一樣

有趣的發現,歡迎討論,如果文中敘述有誤還請邦友們不吝指教~~
https://stackoverflow.com/questions/306313/is-operator-behaves-unexpectedly-with-integers
https://stackoverflow.com/a/1085656


上一篇
Python - for loop/ while loop 迴圈
下一篇
Python - 迴圈流程控制
系列文
30天學會Python30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言