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

这篇来简单说说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





你可能感兴趣的:(Python之路,Python基础知识)