Python:for循环语句

目录


一、for循环语法

for i in range(10):
    print(i)

上面代码会从0-9,共循环10次,这个range(10),其实是相当于产生一个从0-9的列表,每循环一次,就会把列表里的下一个元素取出来给临时变量i。

执行结果:

Python:for循环语句

二、循环的使用 

2.1、循环猜年龄

需求:最多允许猜三次,猜对了就退出程序

age = 38
for i in range(3):
    guess = int(input("猜测的年龄:"))
    if (guess>age):
        print("猜大了")
    elif (guess<age):
        print("猜小了")
    else:
        print("猜对了")

Python:for循环语句

2.2、打印奇偶数

打印50-100间的奇数

for i in range(50,100):
    if (i%2 == 1):
        print(i)

Python:for循环语句

 打印偶数

for i in range(50,100):
    if (i%2 == 0):
        print(i)

Python:for循环语句

 2.3、循环嵌套

这里写了一个不是很灵活的冒泡排序,本质也是使用嵌套循环去完成的

number = [6,7,4,2,1,3,5]
for i in range(5):
    for j in range(6):
        if (number[j] > number[j+1]):
            tmp=number[j]
            number[j]=number[j+1]
            number[j+1]=tmp
print(number)

Python:for循环语句

 三、break & continue

我们这里写一个打印楼层的小程序

需求:一栋楼有5层,每层2间房,要求把本楼所有的房间号都打印一遍。

for i in range(1,6):
    for j in range(1,3):
        print(f"{i}层-{i}0{j}室")

Python:for循环语句

 我们现在需求改一下,遇到第三层时,不打印任何房间号,其他层都打印

3.1、continue

continue的语法作用是,只要程序一遇到continue,本次循环就不继续了,直接进入下一次循环

for i in range(1,6):
    for j in range(1,3):
        if i==3:
            continue
        print(f"{i}层-{i}0{j}室")

Python:for循环语句

 3.2、break

break的语法作用是,只要程序遇到break,就会结束当前这个循环,注意如果是多层嵌套循环,只结束当前这一层的循环。

for i in range(1,6):
    for j in range(1,3):
        if i==3:
            continue   #跳过第三层,从第四层开始
        if i==2 and j==2:
            break      #当dao2层2室的时候直接退出二层循环。从三层开始走
        print(f"{i}层-{i}0{j}室")

Python:for循环语句

 四、打印三角形

打印这样的三角形

*

**

***

****

*****

****

***

**

*

#一种方法
for i in range(1,6):
    print("*" * i)
for i in range(4,0,-1):
    print("*" * i)
#第二种方法
n=10
for i in rang(n):
    if i<5:
        print(i*"*")
    else:
        print((n-i)*"*")

Python:for循环语句

五、while循环

与for必须指定循环多少次不一样的是,while循环的次数可以是不定的,只要条件满足就可以永远循环下去。

5.1、while语法

while 条件:   #只要条件为真,就不断循环
    print(xxxxx)

5.2、死循环

count = 0
while True:
    print(f"第{count}次循环")
    count +=1

5.3、循环10次

count = 0
while count < 10:
    print(f"第{count}次循环....")
    count+=1

5.4、python写99乘法表

for i in range(1,10):
    print()
    for j in range(1,i+1):
        print(f"{i}*{j}={i*j}",end=" ")

Python:for循环语句

5.5、用while实现循环猜年龄

需求:允许用户猜三次,若还不对,钙塑它,你真笨,还想继续猜吗?如果用户选择yes,就让他继续,如果选择no就退出

guess_age = 30
guess_num=0
while True:
    guess_num += 1
    if guess_num<=3:
        guess = int(input("请输入猜的数字:"))
        if guess < guess_age:
            print("数字猜小了")
        elif guess > guess_age:
            print("数字猜大了")
        else:
            print("恭喜猜对了")
    else:
            choice = str(input("错三次了,你还想继续猜吗?[yes/no]"))
            if choice == "":
                continue
            elif choice == "yes":
                print("游戏继续")
                guess_num = 0
            else:
                break

Python:for循环语句

 六、random和string模块(随机数)

6.1、random模块

可以残生指定范围内的随机数,字符串等

import random #导入random模块
a = random.choice("abcdefghigk") #参数也可以是一个列表
print(a)
s = "asdfghjklzxcv"
s = random.sample(s,5) #从数据源s中随机取出5个值
print(s)
i = random.randint(1,100) #打印一个随机数
print(i)

Python:for循环语句

 6.2、string模块

import string
a = string.ascii_letters  #大小写全部字符
print(a)
s = string.ascii_uppercase #大写字符
print(s)
i = string.ascii_lowercase #小写字符
print(i)
j = string.punctuation #打印特殊字符
print(j)
g = string.digits #打印数字
print(g)

Python:for循环语句

 6.3、京牌摇号小程序

需求:允许用户最多选3次

        每次放出20个车牌公用户选择

        3车牌[A-Z]-[xxxxx],可以是数字和字母在组合

import random
import string
num_lsit = []
tmp = (string.digits+string.ascii_uppercase)
print(random.sample(tmp,5))
count = 3
while count > 0:
    count-=1
    num_lsit = []
    for i in range(20):
        car_code = random.choice(string.ascii_uppercase)
        car_num = f"京{car_code}-{''.join(random.sample(tmp,5))}"
        num_lsit.append(car_num)
        print(i,car_num)
    choice = input("choice:").strip()
    if choice in num_lsit:
        exit(f"恭喜你选购成功,您的车牌为{choice}")
    else:
        print(f"未选中,还有{count}次机会")

Python:for循环语句

 6.4、年会抽奖程序

需求:张三公司有300员工,年会抽奖,奖项如下

一等奖3名,泰国五日游

二等奖6名,iphon手机

三等奖,小玩具一个

每个员工只能限一次。

import random
import string
a = []
for j in range(1,301):
    a.append(j)            #建立一个员工的地址池
###########抽一等奖##############
print("抽一等奖,三等奖是泰国五日游")
print("得奖员工:",end="")
for yi in range(3):
    tmp = random.choice(a)   #随机去一个员工
    print(tmp,end=" ")
    a.remove(tmp)           #因为每个员工只能拿一个奖,所以删除员工池以得奖的用户
print("")                   #另起一行
###########抽二等奖###############
print("抽二等奖,二等奖是一部iphon手机")
print("得奖员工:",end="")
for er in range(7):
    tmp = random.choice(a)
    print(tmp,end=" ")
    a.remove(tmp)
print("")
############抽三等奖##############
print("抽三等奖,三等奖是小玩具一个")
print("得奖员工:",end="")
for san in range(11):
    tmp=random.choice(a)
    print(tmp,end=" ")
    a.remove(tmp)

Python:for循环语句

 

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
乘风的头像乘风管理团队
上一篇 2023年3月5日 下午1:59
下一篇 2023年3月5日 下午2:02

相关推荐