Python--基础学习--流程控制

本文介绍了Python中的流程控制,包括使用getpass获取不可见输入,while和for循环的基本应用,以及break和continue的控制作用。通过一个密码验证的例子展示了if、elif和else的条件判断,并提到了三元运算符的简洁写法。
摘要由CSDN通过智能技术生成

这篇来简单说说python的流程控制


获取输入的值


类似于linux中输入密码不可见,可以通过getpass 类来实现


当然如果仅仅是想要隐藏内容的话,不局限于用在获取密码


while  条件

循环内容

判断为True,则执行1

判断为False,则执行2


break &continue

break:退出当前循环;

continue:不执行下面的内容,直接进入下一个循环


def test():
    i = 0
    result = []
    while True:
        i = i + 1
        result.append(i)
        print(result)
        if i>5:
            break
        else:
            continue
test()
执行结果:

[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6]


if  elif  else 条件判断

def test():
    reg = input('input your choice:1.login;2.register;3.exit:')
    ret = reg.strip()
    if ret == "1":
        print('Welcome to our family')
    elif ret == "2":
        print("You cannot register to our family,just be a visitor")
    elif ret == "3":
        exit()
    else:
        print('you must type 1 or 2 or 3')
        exit()
test()


for  循环

实现密码输入错误后,给多次机会重试

username='Meta'
password='hao'
user=input('Username:')
if user == username:
    for i in range(3):
        pw=input('Password:')
        if pw == password:
            print('Welcome to our family')
            break
        else:
            print('your password is not right')
            continue
else:
    print('You r not our member,Sorry')

运行结果:

Username:Meta
Password:123
your password is not right
Password:123
your password is not right
Password:123
your password is not right


三元运算 or三目运算


条件判断的简写方式

ret=a if 条件判断 else b     

#条件判断为True,则 ret原值不变,False,则ret重新赋值为b





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值