码迷,mamicode.com
首页 > 编程语言 > 详细

python的for,while及if

时间:2018-07-11 16:35:38      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:int   年龄   error   led   密码认证   use   运行   for循环   nbsp   

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

标签:int   年龄   error   led   密码认证   use   运行   for循环   nbsp   

原文地址:https://www.cnblogs.com/Arthur7/p/9295123.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!