python循环中嵌套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循环应⽤
random在python中的意思计算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!")