python基礎之條件和迴圈 十一

2021-09-18 07:06:43 字數 2274 閱讀 2467

格式

if 判斷條件:

執行語句……

else:

執行語句……

chepiao =

1# 用1代表有車票,0代表沒有車票

if chepiao ==1:

print

("有車票,可以上火車"

)print

("終於可以見到ta了,美滋滋~~~"

)else

:print

("沒有車票,不能上車"

)print

("親愛的,那就下次見了,一票難求啊~~~~(>_<)~~~~"

)

格式

if 判斷條件1:

執行語句1……

elif 判斷條件2:

執行語句2……

elif 判斷條件3:

執行語句3……

else:

執行語句4……

score =

77if score>=

90and score<=

100:

print

('本次考試,等級為a'

)elif score>=

80and score<90:

print

('本次考試,等級為b'

)elif score>=

70and score<80:

print

('本次考試,等級為c'

)elif score>=

60and score<70:

print

('本次考試,等級為d'

)elif score>=

0and score<60:

print

('本次考試,等級為e'

)

格式

while 判斷條件:

執行語句……

i = 0

while i<10000:

print("媳婦兒,我錯了")

i+=1

i = 1

while i<=5:

j = 1

while j<=i:

print("* ",end='')

j+=1

print("\n")

i+=1

格式

for iterating_var in sequence:

statements(s)

name =

'xiaoyu'

for x in name:

print

(x)

迴圈控制語句可以更改語句執行的順序。python支援以

控制語句

描述break 語句

在語句塊執行過程中終止迴圈,並且跳出整個迴圈

continue 語句

在語句塊執行過程中終止當前迴圈,跳出該次迴圈,執行下一次迴圈。

pass 語句

pass是空語句,是為了保持程式結構的完整性。

name = 'xiaoyu'

for x in name:

print('----')

if x == 'o':

break

print(x)

name = 'xiaoyu'

for x in name:

print('----')

if x == 'o':

continue

print(x)

#!/usr/bin/python

# -*- coding: utf-8 -*-

# 輸出 python 的每個字母

for letter in 'python':

if letter == 'h':

pass

print '這是 pass 塊'

print '當前字母 :', letter

print "good bye!"

當前字母 : p

當前字母 : y

當前字母 : t

這是 pass 塊

當前字母 : h

當前字母 : o

當前字母 : n

good bye!

python基礎之條件判斷和迴圈

計算機之所以能做很多自動化的任務,因為它可以自己做條件判斷。比如,輸入使用者年齡,根據年齡列印不同的內容,在python程式中,可以用if語句實現 age 20 if age 18 print your age is age print adult print end 注意 python 的縮排規則...

Python基礎 條件和迴圈

4.1 if語句 if expression expr true suite 只有條件表示式expression結果為真時才執行expr true suite 塊,否則繼續執行緊跟在該 塊後面的語句。單個if語句中的expression條件表示式可以通過布林操作符and,or,not實現多重條件判斷...

Python基礎 條件判斷和迴圈

age 20 if age 18 print your age is age print adult else print youth your age is 20 adult注意 python 的縮排規則.具有相同縮排 被視為 塊,上面的3 4 行就構成了乙個 塊 縮排請嚴格按照python的習慣...