51学通信论坛2017新版
标题:
1.4 if else流程判断
[打印本页]
作者:
admin
时间:
2017-12-11 21:47
标题:
1.4 if else流程判断
1 隐藏输入的用户密码
需要导入getpass模块。
源码:
import getpass #这个模块可以隐藏用户输入的密码
username = input("username:")
password = getpass.getpass("pls input your password:")
print(username,password)
复制代码
执行结果:
username:aiweisheng
pls input your password:
aiweisheng aaa
复制代码
2 基本的if else判断:
判断输入的密码是否正确,正确显示欢迎,不正确显示不欢迎。
源码:
import getpass #这个模块可以隐藏用户输入的密码
_username = 'aiweisheng'
_password = '51xuetongxin'
username = input("username:")
password = getpass.getpass("pls input your password:")
print(username,password)
if _username == username and _password == password:
print("welcome user {name} login.".format(name=username))
复制代码
执行结果:
密码输入正确时的结果:
username:aiweisheng
pls input your password:
aiweisheng 51xuetongxin
welcome user aiweisheng login.
密码输入错误时的结果:
username:aiweisheng
pls input your password:
aiweisheng 111
invalid user
复制代码
如果看到IndentationError就代表缩进错误,if后边跟的执行条件要加4个空格。如果不需要缩进,代码就必须要顶格写。
3 难一点的if else
3.1)猜年龄:一次命中
源码
age_of_aiweisheng = 30
guess_age = int(input("guess age:"))
if guess_age == age_of_aiweisheng:
print("you are right")
复制代码
执行结果:
guess age:30
you are right
复制代码
3.2)完善猜年龄程序,增加猜大猜小的检测:源码
age_of_aiweisheng = 30
guess_age = int(input("guess age:"))
if guess_age == age_of_aiweisheng:
print("you are right.")
elif guess_age>age_of_aiweisheng:
print("try smaller")
else:
print("try bigger")
复制代码
执行结果:
guess age:29
try bigger
复制代码
欢迎光临 51学通信论坛2017新版 (http://bbs.51xuetongxin.com/)
Powered by Discuz! X3