Python自动化之循环与判断语法

本文探讨了Python中的for循环和if判断语句。详细介绍了for循环的使用,包括break和continue的控制流程,强调了缩进的重要性。接着讲解了if判断语句在用户认证和猜年龄游戏中的应用,展示了如何结合while循环控制游戏流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、for循环
1)实现循环打印操作
代码段:

# Author:JiangYiyang
for i in range(0,10):
    print("Hello,World",i)

在这里插入图片描述
跳出循环:
break 跳出整个循环语句
continue 跳出此轮循环语句

先循环i的值,再循环j的值,当j<5时就会打印i和所以j的值,当j>5时,就会跳出第二个for循环

for i in range(0,3):
    print("---------",i)
    for j in range(0,10):
        if j < 5:
            print(j)
        else:
            break

在这里插入图片描述
注意:事实上行首的空白是重要的。它称为缩进。在逻辑行首的空白(空格和制表符)用来决定逻辑行的缩进层次,从而用来决定语句的分组。同一层次的语句必须要有相同的缩进。

先循环i的值,然后再循环j的值,并打印hehe字段,当j大于5的时候,便不会再打印第二轮循环里的hehe

for i in range(0,3):
    print("---------",i)
    for j in range(0,10):
        if j > 5:
            continue
        print("hehe")

在这里插入图片描述

2、if判断语句
通过if判断语句来实现用户名和密码的认证登录

if…else

# Author:JiangYiyang
_username='jyy'
_password='python'
username = input("Please input  your name:")
password = input("Please input your password:")

if _password == password and _username == username:
    print("Welocme user {name} login.....".format(name=username))
else:
    print("Your user ro password input error")

在这里插入图片描述

if…elif…else
通过while循环加if判断语句来实现猜年龄的游戏,控制循环的次数为3次。

# Author:JiangYiyang\
aaa = 0
age_of_jyy = 19
while aaa < 2:
    guess_age = int(input("Please input age:"))
    if age_of_jyy > guess_age:
        print("This number is bigger")
    elif age_of_jyy == guess_age:
        print("yes,you input success")
        break
    else:
        print("This number is samller")
        aaa = aaa +1

在这里插入图片描述

通过循环来判断用户是否要继续玩

# Author:JiangYiyang
age_of_jyy = 19
count = 0
while count <3:
    guess_age = int(input("Please input guess age:"))
    if guess_age == age_of_jyy:
        print("Input successful")
        break
    elif guess_age > age_of_jyy:
        print("That's a big number.")
    else:
        print("That's a small number.")
    count +=1
    if count ==3:
        countine_confirm = input("do you want to keep guessing...?")
        if countine_confirm != 'n':
            count=0

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值