1:if語句
Python中的if語句是選擇操作來執(zhí)行,其語法形式如下:
if test1:
statements1
elif test2: # 是可選的
statements2
elif test3: # 是可選的
statements3
else: # 是可選的
statements4
"""
elif ,else 是可選的,也就是說在語法上,可有可無,依據(jù)自己實(shí)際需要而定;
statements1到statements4 中也可以包含if語句,即可以進(jìn)行if嵌套
"""
1.1:一般形式
單if:
if 1:
print('true')
score = 61
if score >= 60:
print('及格')
"""
輸出結(jié)果:
true
及格
"""
1.2:if...else :
score = 61
if score >= 60:
print('及格')
else:
print('不及格')
"""
輸出:
及格
"""
1.3:多路分支:
# score = int(input('輸入一個(gè)整數(shù):'))
score = 89
if score > 100:
print('數(shù)據(jù)異常')
elif score >= 80:
print('優(yōu)')
elif score >= 70:
print('良')
elif score >= 60:
print('及格')
else:
print('不及格')
"""
優(yōu)
"""
2:真值與布爾測試
Python中:
a:所有的對(duì)象都有一個(gè)固定的布爾真或者假值;
s = 'hello'
print(bool(s)) # 輸出 True
s = ''
print(bool(s)) # 輸出 False
b:任何非0數(shù)字,非空對(duì)象都為真;
# 整數(shù)
print(bool(123))
# 浮點(diǎn)數(shù)
print(bool(3.1415))
# 字符串
print(bool('python'))
# 列表
print(bool([1,2,3]))
# 元組
print(bool((1,2,3)))
# 集合
print(bool({1,2,3,4}))
# 字典
print(bool({'age':18}))
"""
都返回True
"""
c:數(shù)字0,空對(duì)象,特殊對(duì)象None都被認(rèn)作是假;
空對(duì)象:
字符串:''
列表:[],list()
元組:(),tuple()
字典:{},dict()
集合:set()
# 整數(shù)
print(bool(0))
# 浮點(diǎn)數(shù)
print(bool(0.0))
# 字符串,空字符串
print(bool(''))
# 列表
print(bool([]))
# 元組
print(bool(()))
# 集合
print(bool(set()))
# 字典
print(bool(dict()))
print(bool(None))
"""
全部輸出False
"""
d:比較和相等測試會(huì)遞歸地應(yīng)用到數(shù)據(jù)結(jié)構(gòu)中;
e:比較和相等測試會(huì)返回True或者False;
f:布爾and和or運(yùn)算符會(huì)返回真或假的操作數(shù)對(duì)象;
g:布爾運(yùn)算符在結(jié)果確定的時(shí)候立即停止計(jì)算;
# and :只要有一個(gè)為假,立即停止計(jì)算,并返回假的操作數(shù)對(duì)象;都為真返回最后一個(gè)操作數(shù)對(duì)象
print(10 and 20,20 and 10) # 20 10
print([] and 10) # []
print(10 and []) # []
# or :只要有一個(gè)為真,立即停止計(jì)算,并返回真的操作數(shù)對(duì)象;都為假返回最后一個(gè)操作數(shù)對(duì)象
print(10 or 20,20 or 10) # 10 20
print([] or 10) # 10
print(10 or []) # 10
print([] or {}) # {}
3:if/else三元表達(dá)式
如下if語句:
if x:
a = y
else:
a = z
可以改寫為:
a = y if x else z
score = 88
ret = ''
if score >= 60:
ret = '及格'
else:
ret = '不及格'
print(ret)
# 優(yōu)點(diǎn):1:代碼量少;2:可以把if/else 三元表達(dá)式嵌套在其他語句中
ret = '及格' if score >=60 else '不及格'
print(ret)
#
print('及格' if score >=60 else '不及格')

Online-learning-AI-1024x440.jpg