python学习之流程控制

python流程控制跟其他语言一样,主要有if else elif,语法相当简单。

一、if else 学习: 

_username = "chenbin"
_password = "chenbin"


username = input("username:")
password = input("password:")

if _username == username and _password == password:
    print("Welcome user {name} login...".format(name = username))
else:
    print("Invalid username or password")

猜数字小游戏:输入的年龄大于指定的年龄,提示猜大了,反之亦然,在python3里input输入的是str类型的,如果跟int类型相比较,需要类型转换:int(input("age"x))。

age_of_oldbody = 56

gusee_age = int(input("guess age:"))

if age_of_oldbody == gusee_age:
    print("yes,you got it...")
elif gusee_age > age_of_oldbody:
    print("think smaller...")
else:
    print("think bigger!")

二、while循环:

count = 0
while True:
    print("count:" + count)
    count = count + 1

猜数字小游戏只能猜三次,如果三次内没猜对,直接结束程序;

age_of_oldbody = 56
count = 0
while True:
    if count == 3:
        break
    age = int(input("age:"))
    if age_of_oldbody == age:
        print("ok!")
        break
    elif age > age_of_oldbody:
        print("bigger!")
    else:
        print("smaller!")
    count+=1

优化后的猜数字小游戏代码:

age_of_oldbody = 56
count = 0
while count < 3:
    age = int(input("age:"))
    if age_of_oldbody == age:
        print("ok!")
        break
    elif age > age_of_oldbody:
        print("bigger!")
    else:
        print("smaller!")
    count+=1
else:
    print("fuck off...")

三、for循环实现猜数字小游戏:

age_of_oldbody = 56
for i in range(3):
    guess_age = int(input("age:"))
    if age_of_oldbody == guess_age:
        print("ok!")
        break
    elif guess_age > age_of_oldbody:
        print("bigger!")
    else:
        print("smaller!")
else:
    print("guck off!")

使用for循环打印奇偶数,之前使用别的语言打印奇偶数,判断是否能被2整数打印,现在使用python语言,使用步长直接打印,代码如下:

for i in range(0,10,2):
    print("loop i is:",i)
    loop i is: 0
loop i is: 2
loop i is: 4
loop i is: 6
loop i is: 8

猜数字小游戏进一步优化,如果在三次之内都没有才对,问是否继续猜,如果继续猜,重置计数器,反之结束程序,代码如下:

count = 0
age_oldbody = 56
while True:
    guess_age = int(input("age:"))
    if guess_age == age_oldbody:
        print("ok!")
        break
    elif guess_age > age_oldbody:
        print("bigger!")
    else:
        print("smaller!")
    count+=1
    if count == 3:
        continue_confirm = input("do you want to keep guessing..?")
        if continue_confirm != 'n':
            count = 0
#else:
#    print("fuck off!")

四、总结:

python的循环相当简单,根据自己的业务场景选择合适的循环处理,这里说明一下break和continue的区别,break结束循环操作,continue结束本次循环执行下一次循环操作,本篇文字简单明了,仅供初学者学习入门。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sunshineAndAlways

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值