Python的循环与判断语句

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

在这里插入图片描述

扫描二维码关注公众号,回复: 6400092 查看本文章

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

# 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

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Micky_Yang/article/details/87990182