1、for循環
字符串就是一個有序的字符序列
for i in range(5):
print(i)
定義一個死循環
while True:
pass
2、break和continue
肯定需要和循環配合使用
while-break/for-break
在一個循環中如果某個條件成立后 執行了break 那么這個循環將停止(跳出循環)
而且在break后面的代碼將不再執行
while-continue/for-break
在一個循環中如果某個條件成立后 執行了continue 那么提前結束本次勛魂
而且在continue后面的代碼將不再執行
if嵌套應用
chePiao = 1 # 用1代表有車票,0代表沒有車票 daoLenght = 9 # 刀子的長度,單位為cm if chePiao == 1: print("有車票,可以進站") if daoLenght < 10: print("通過安檢") print("終於可以見到Ta了,美滋滋~~~") else: print("沒有通過安檢") print("刀子的長度超過規定,等待警察處理...") else: print("沒有車票,不能進站") print("親愛的,那就下次見了") if猜拳游戲 import random player = input('請輸入:剪刀(0) 石頭(1) 布(2):') player = int(player) # 產生隨機整數:0、1、2 中的某一個 computer = random.randint(0,2) # 用來進行測試 #print('player=%d,computer=%d',(player,computer)) if ((player == 0) and (computer == 2)) or ((player ==1) and (computer == 0)) or ((player == 2) and (computer == 1)): print('獲勝,哈哈,你太厲害了') elif player == computer: print('平局,要不再來一局') else: print('輸了,不要走,洗洗手接着來,決戰到天亮')
while循環應用
計算1~100的累積和(包含1和100)
#encoding=utf-8 i = 1 sum = 0 while i <= 100: sum = sum + i i += 1 print("1~100的累積和為:%d" % sum)
九九乘法表
i = 1 while i<=9: j=1 while j<=i: print("%d*%d=%-2d " % (j, i, i*j), end = '') j+=1 print('\n') i+=1
for循環應用
for 臨時變量 in 列表或者字符串等可迭代對象:
循環滿足條件時執行的代碼
for x in name: print(x) if x == 'l': print("Hello world!")