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

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM