您的位置:首页 > 编程语言 > Python开发

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

2018-01-15 23:04 886 查看

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!")
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐