天天看點

python for循環中嵌套if_python中for、while循環、if嵌套的使用

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!")