1. 程式人生 > 其它 >Python控制流程語句

Python控制流程語句

'''
1.if判斷語句

1.1單分支語句

if 表示式:
程式碼塊

user = input("使用者名稱>>")
pwd = input("密碼>>")
if user == "root" and pwd == "123": # 返回一個布林值
print("登入成功") # 強烈建議使用四個縮排

print("程式結束")

1.2雙分支語句

if 表示式:
程式碼塊 1
else:
程式碼塊 2

user = input("使用者名稱>>")
pwd = input("密碼>>")

if user == "root" and pwd == "123": # 返回一個布林值
print("登入成功") # 強烈建議使用四個縮排
print("祝賀你")
else:
print("登入失敗")
print("不好意思")

1.3多分支語句


if 表示式 1:
程式碼塊 1
elif 表示式 2:
程式碼塊 2
elif 表示式 3:
程式碼塊 3
...# 其它elif語句
else:
程式碼塊 n

score = input("請輸入您的成績>>") # "100"
# 當成績大於90的時候顯示優秀,否則顯示一般
# 將數字字串,比如"100",轉換成一個整型數字的時候,需要int轉換
score = int(score) # 100

if score > 100 or score < 0:
print("您的輸入有誤!")
elif score > 90:
print("成績優秀")
elif score > 70: # else if
print("成績良好")
elif score > 60:
print("成績及格")
else:
print("成績不及格")

1.4if巢狀


score = input("請輸入您的成績>>") # "100"

if score.isdigit():
score = int(score) # 100
if score > 100 or score < 0:
print("您的輸入有誤!")
elif score > 90:
print("成績優秀")
elif score > 70: # else if
print("成績良好")
elif score > 60:
print("成績及格")
else:
print("成績不及格")
else:
print("請輸入一個數字")
==============================

2.while迴圈語句


while 表示式:
迴圈體

2.1無限迴圈

# 案例1
while 1:
print("OK") # 無限迴圈列印OK,這樣使用沒有什麼意義

# 案例2
while 1:

score = input("請輸入您的成績>>") # "100"

if score.isdigit():
score = int(score) # 100
if score > 100 or score < 0:
print("您的輸入有誤!")
elif score > 90:
print("成績優秀")
elif score > 70: # else if
print("成績良好")
elif score > 60:
print("成績及格")
else:
print("成績不及格")
else:
print("請輸入一個數字")

2.2限定次數迴圈

迴圈列印十遍"hello world”

count = 0 # 初始化語句
while count < 10: # 條件判斷
print("hello world")
count+=1 # 步進語句
print("end")
==============================

3.for迴圈語句

for 迭代變數 in 字串|列表|元組|字典|集合:
程式碼塊

for i in "hello world":
print(i)

for name in ["張三",'李四',"王五"]:
print(name)

for i in range(10): # [1,2,3,4,5,6,7,8,9] range函式: range(start,end,step)
print(i)
==============================

4.退出迴圈

如果想提前結束迴圈(在不滿足結束條件的情況下結束迴圈),可以使用break或continue關鍵字。

break
當 break 關鍵字用於 for 迴圈時,會終止迴圈而執行整個迴圈語句後面的程式碼。break 關鍵字通常和 if 語句一起使用,即滿足某個條件時便跳出迴圈,繼續執行迴圈語句下面的程式碼。

continue
不同於break退出整個迴圈,continue指的是退出當次迴圈。
==============================

5.迴圈巢狀
在一個迴圈體語句中又包含另一個迴圈語句,稱為迴圈巢狀

5.1獨立巢狀

在控制檯上列印一個如下圖所示的正方形

*****
*****
*****
*****
*****

程式碼:
for i in range(5):
for j in range(5):
print("*",end="")
print("")

5.2關聯巢狀

在控制檯上列印一個如下圖所示的三角形

*
**
***
****
*****

程式碼:
for i in range(5):
for j in range(i+1):
print("*",end="")
print("")
==============================
'''