(3)Python——循环语句for,while

1.循环语句 

1)for语句

for循环使用的语法:
for 变量 in 序列:
    循环要执行的动作

range()用法:
range(stop): 0 - (stop-1)
range(start,stop): start - (stop-1)
range(start,stop,step): start -(stop-1), step(步长)

获取随机数

import random

调用随机数1-3 random.randint(1,3)

sum = 0
for i in range(1,101,2):
    sum += i

print(sum)

例如:1-100奇数和

 

跳出循环:
break:跳出整个循环,不会再循环后面的内容
continue:跳出本次循环,continue后面的代码不再执行,但是循环依然继续
exit():结束程序的运行

实例:
1)由1,2,3,4四个数字能生成多少个互不相同且无重复数字的三位数

count=0
for i in range(1,5):
     for j in range(1,5):
         for k in range(1,5):
             if i==j or i==k or j==k:
                 continue
             count +=1
             print('%d%d%d' % (i,j,k))
print('能组成的数的个数为%d个' %count)

2)用户登录:

用户登陆需求:
  1.输入用户名和密码;
  2.判断用户名和密码是否正确(name='root',passwd='westos')
  3.登陆仅有三次机会,超过三次会报错
for a in range(1,4):
    name=str(input('请输入用户名:'))
    password=str(input('请输入密码:'))
    if name == 'root' and password == 'westos':
        print('登陆成功')
        break
    else:
        print('登陆失败')
        print('你还有%d次登陆机会' % (3 - a))
else:
    print('输入超过三次,请重新登录')

3)输入两个数,求他们的最大公约数和最小公倍数

a=int(input('请输入第一个数:'))
b=int(input('请输入第二个数:'))
c = max(a, b)
d = min(a, b)
for i in range(1,d+1):
    if a % i ==0 and b % i ==0:
        gys=i
gbs=int((a*b)/gys)
print('最大公约数为%d' %gys)
print('最小公倍数为%d' %gbs)

2.while循环

1>

while 条件():
    条件满足时,做的事情1
    条件满足时,做的事情2
#1.定义一个变量,记录循环次数
i = 1
#2.开始循环
while i <= 3:
    #循环内执行的动作
    print('hello world')
    #处理计数器
    i += 1

2>while 死循环

while True:
    print('hello python')

会一直不断输出hello python,除非终止程序

3>实例1:while循环求1-100的和

i = 0
result = 0
while i <= 100:
    result += i
    i += 1

print('和为:%d' %result)

4>实例2:打印9*9乘法表

row = 1
while row <= 9:
    col = 1
    while col <= row:
        print('%d * %d = %d\t' %(col,row,col * row),end='')
        col += 1
    print('')
    row += 1

5>实例3.

在控制台连续输出五行*,每行依次递增
*****
****
***
**
*
row = 5
while row >= 1:
    col = 1
    while col <= row:
        print('*',end='')
        col += 1
    print('')
    row -= 1

 

6>实例4

"""
猜数字游戏
1. 系统随机生成一个1~100的数字;
2. 用户总共有5次猜数字的机会;
3. 如果用户猜测的数字大于系统给出的数字,打印“too big”;
4. 如果用户猜测的数字小于系统给出的数字,打印"too small";
5. 如果用户猜测的数字等于系统给出的数字,打印"恭喜",并且退出循环;
"""
while trycount < 5:
    player = int(input('Num:'))
    if player > computer:
        print('too big')
        trycount += 1
    elif player < computer:
        print('too small')
        trycount += 1
    else:
        print('恭喜你猜对了!撒花✿✿ヽ(°▽°)ノ✿')
        break

猜你喜欢

转载自blog.csdn.net/weixin_44214830/article/details/89035632
今日推荐