循环的应用

打印矩形

i=1
while i<=5:
    j=1
    while j<=5:
        print('*',end='')
        j+=1
    print()
    i+=1

刚开始我以为答案是330,其实是错的,答案是210,a=a*(50-30+10)

打印三角形

i=1
while i<=5:
    j=1
    while j<=i:
        print('*',end='')
        j+=1
    print()
    i+=1

九九乘法表

i=1
while i<=9:
    j=1
    while j<=i:
        print('%s*%s=%s	'%(j,i,j*i),end='')#反斜杠t表示一个tab键
        j+=1
    print()
    i+=1

石头剪刀布

import random

player=int(input('请输入:石头0 剪刀1 布2'))
computer=random.randint(0,2)

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('你输了')

打印1到100之间的偶数

# 打印1到100之间的偶数
#for循环实现
for i in range(1,101): if i%2==0: print(i)
#while 循环实现
n=1
while n<=100:
if n%2==0:
print(n)
n += 1

打印1到100之间的前20个偶数

n=1
num=0
while n<=100:
    if n%2==0:
        print(n)
        num+=1
    n+=1
    if num == 20:
        break

continue结束本次循环,不执行continue下面的代码

break结束整个循环,也就是跳到了循环外

while循环嵌套作用范围,break在哪个while循环里就退出哪个循环,从内向外找,continue同理

原文地址:https://www.cnblogs.com/z-x-y/p/10145047.html