python学习第一天(循环)

python学习第一天(循环),第1张

while循环

基本形式:
while 判断条件:
执行语句
else:
while循环结束后执行该语句(非break语句引起)

eg:(一个判断用户名和用户密码的简单程序)

# edited by Lyu 
#仅供学习使用,禁止一切商业用途

passname="Lyu Zhiyu"
password="Lyu123"
count=3

while count>0:
    _passname=input("enter your passname:")
    _password=input("enter your passsword:")
    if password==_password and passname==_passname:
        print("congratulations!")
        print("WELCOME,", passname, "!")
        break
    else:
        print(f"passname or password invalid!\nyou have only {count-1} chances.")
    count-=1
else:
    print("Your chance has run out!!\nTry late again.")

运行结果1:(三次全错)

enter your passname:jak
enter your passsword:af
passname or password invalid!
you have only 2 chances.
enter your passname:af
enter your passsword:afa
passname or password invalid!
you have only 1 chances.
enter your passname:af
enter your passsword:faf
passname or password invalid!
you have only 0 chances.
Your chance has run out!!
Try late again.

运行结果2:(输入正确)

enter your passname:Lyu Zhiyu
enter your passsword:Lyu123
congratulations!
WELCOME, Lyu Zhiyu !

进程已结束,退出代码为 0

使用while循环较为直观,但是需要自己计数,有较多的判断语句。


for循环

基本形式:
for i range (循环次数): #循环次数也可看作i执行完循环后的数字大小
执行语句
else:
for循环结束后执行该语句(非break语句引起)

eg:(第一个小程序改为for循环后)

# edited by Lyu
#仅供学习使用,禁止一切商业用途

passname="Lyu Zhiyu"
password="Lyu123"
COUNT=2                       #取补集计数
for i in range (3):
    _passname=input("enter your passname:")
    _password=input("enter your passsword:")
    if password==_password and passname==_passname:
        print("congratulations!")
        print("WELCOME,", passname, "!")
        break
    else:
        print(f"passname or password invalid!\nyou have only {COUNT-i} chances.")
else:
    print("Your chance has run out!!\nTry late again.")

运行结果同while循环。

值得注意的是,for循环采用了正序计数,要输出剩余次数,需要设置一个计数常量。
本人尝试采用for循环倒序计数:
将for i in range (3):改为for i in range (3,0):以避免设置计数常量,但是结果非所愿:

Your chance has run out!!
Try late again.

出现上述结果。

若有大神知道原因欢迎指出。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/868348.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-13
下一篇 2022-05-13

发表评论

登录后才能评论

评论列表(0条)

保存