python的for,while及if
Posted arthur7
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python的for,while及if相关的知识,希望对你有一定的参考价值。
python的循环及判断
认证账户和密码
import getpass #导入模块 username = input(‘username: ‘) password = getpass.getpass(‘password: ‘) #输入密码不显示 用户密码认证:if及else # Author:Yao Xiaodong import getpass _username = ‘Arthur‘ _password = ‘123456‘ username = input(‘username: ‘) password = input(‘password: ‘) if _username == username and _password == password: print(‘welcome {name} to python world‘.format(name=username)) else: print(‘auth filed‘)
猜测年龄
while方式
#while循环 authur_age = 500 count = 0 while count < 3: guess_age = int(input(‘guess_age: ‘)) if guess_age == authur_age : print(‘yes,you are right!‘) break elif guess_age > authur_age : print(‘It is to bigger...‘) else: print(‘It is to smaller...‘) count += 1 else: print(‘Error‘)
for方式
for循环 authur_age = 500 for i in range(3): guess_age = int(input(‘guess_age: ‘)) if guess_age == Yxd_age : print(‘yes,you are right!‘) break elif guess_age > Yxd_age : print(‘It is to bigger...‘) else: print(‘It is to smaller...‘) else: print(‘Error‘)
while+if
判断三次后是否继续
age = 21 count = 0 while count < 3: guess_count = int(input("guess_count: ")) if guess_count == age: print(‘yes‘)
break
elif guess_count > age: print(‘big‘) else: print(‘small‘) count += 1 if count == 3: paly = input(‘do you want paly agen?(y/n): ‘) if paly == ‘y‘: count = 0 elif paly == ‘n‘: print(‘all right‘)
else: print(‘(y/n)do you know?‘)
break和continue的有什么不同?
不同点
break跳出整个循环,如果循环中遇到了break,那么这个循环直接无效。
continue跳出当前循环,如果循环中遇到了continue,跳出本次循环继续下次循环。
相同点:
break和continue都是只跳出当前循环,也就是说如果是for循环套for循环的时候,只会跳出break或者continue所在的那个for循环。举个例子:
例如:
for i in range(3): print(‘---------‘,i,‘-------‘) for n in range(3): if n > 1: print(n) else: break #运行结果为 --------- 0 ------- --------- 1 ------- --------- 2 -------
#也就是说遇到了break后整个循环都没有了结果,但是外循环没有影响
再看continue
for i in range(3): print(‘---------‘,i,‘-------‘) for n in range(3): if n > 1: print(n) else: continue #运行结果为 --------- 0 ------- 2 --------- 1 ------- 2 --------- 2 ------- 2
#也就是说continue只是跳出一次循环,而不是整个循环,
但是外循环没有影响
以上是关于python的for,while及if的主要内容,如果未能解决你的问题,请参考以下文章