1.概述
通過條件語句來判斷,條件成立執行某些代碼,條件不成立則不執行這些代碼
2.if語句
if條件:條件成立執行的代碼......
下方代碼沒有縮進到if語句塊,所以和if條件無關
if…else
if條件:條件成立執行的代碼......
else:條件不成立執行的代碼
userName = input('請輸入賬號:')
password = input('請輸入密碼:')
if userName == '張三' and password == '123456':print('登入成功')
else:print('賬號或密碼錯誤')age = int(input('請輸入您的年齡:'))
if age < 18:print(f'年齡為{age},不可上網')
多重判斷
if條件:條件1成立執行的代碼......
elif 條件2:條件2成立執行的代碼
else:條件不成立執行的代碼
age = int(input('請輸入您的年齡:'))
print(f'您的年齡為{age}', end = '')
if age < 18:print('童工')
elif 18 <= age <= 60:print('正常工')
else:print('退休工')
if嵌套
if 條件1:條件1成立執行的代碼if 條件2:條件2成立執行的代碼
3.三目運算符
三目運算符也叫三元運算符或三元表達式
條件成立執行的表達式 if 條件 else 條件不成立執行表達式
案例:猜拳游戲
your = int(input('請出拳:0-石頭,1-剪刀,2-布'))
computer = random.randint(0, 2)
if computer == 0:if your == 0:print('平局', end='')if your == 1:print('你輸了', end='')if your == 2:print('你贏了', end='')
if computer == 1:if your == 1:print('平局', end='')if your == 2:print('你輸了', end='')if your == 0:print('你贏了', end='')
if computer == 2:if your == 2:print('平局', end='')if your == 0:print('你輸了', end='')if your == 1:print('你贏了', end='')
computerStr = '石頭' if computer == 0 else '剪刀' if computer == 1 else '布'
print(f'電腦為{computerStr}')
4.while循環
循環的作用:讓代碼更高效的重復執行
循環的分類:在Python中,循環分為while和for兩種,最終實現效果想通過
while 條件:條件成立重復執行的代碼
案例: 1-100累加
a = 1
total = 0
while a <= 100:total += aa += 1
print(total)
案例:1-100偶數和
a = 1
total = 0
while a <= 100:if a % 2 == 0:total += aa += 2
print(total)
break: 當某些條件成立退出整個循環
a = 10
while a < 100:a += 1if a == 20:break
print(a)
continue: 退出當前一次循環而執行下一次循環
注: 如果使用continue,在continue之前一定要修改金屬漆,否則進入死循環
a = 10
total = 0
while a <= 100:if a % 10 == 0:a += 1continuetotal += aa += 1
print(total)
while循環嵌套
while 條件1:條件1成立執行的代碼while 條件2:條件2成立執行的代碼
案例,每個月有4周,每周上5天班,打印一個月的上班情況
week = 1
while week <= 4:day = 1while day <= 7:if day >= 6:day += 1continueprint(f'第{week}周的星期{day}')day += 1week+= 1
案例:打印正方形
line = 0
while line < 5:col = 0while col < 5:print('*', end='')col += 1line += 1print()
案例:打印三角形
while line < 5:col = 0while col <= line:print('*', end='')col += 1line += 1print()
案例:九九乘法表
line = 1
while line <= 9:col = 1while col <= line:print(f'{col}*{line}={col*line}', end=',')col += 1line += 1print()
5.for循環
for 臨時變量 in 序列重復執行的代碼
str1 = 'hello word'
for str in str1:if str == 'w':breakif str == 'l':continueprint(str)
6.else
循環可以和else 配合使用,else下方縮進的代碼指的是當循環正常結束之后要執行的代碼
i = 0
while i < 10:print(i)i += 1if i == 5:# 執行elsecontinueif i == 6:# 不執行elsebreak
else:print('else執行')
print('正常執行')
i = '123456789'
for num in i:print(num)if i == '4':# els 執行continueif i == '6':# else不執行break
else:print('else執行')