1 案例1:判断合法用户
1.1 问题
编写login2.py脚本,实现以下目标:
提示用户输入用户名和密码
将用户名和密码分别保存在变量中
如果用户名为bob并且密码为123456,则输出Login successful,否则输出Login inorrect
1.2 方案
本题主要是复合的判断语句,写法有如下两种:
1.使用两个判断语句,先判断用户名,如果用户名正确再判断密码是否正确
2.在一个判断语句中,同时判断两个条件是否全部成立
1.3 步骤
实现此案例需要按照如下步骤进行。
步骤一:编写脚本
在很多语言中,if后面的判断条件需要使用圆括号或方括号,但是python并不强制,可以直接将判断条件写在if后面,并不会产生错误。
有些时候,判断条件可能有多个(使用and或or连接),为了更好的可读性,建议在这种环境下,将多个条件分别用圆括号括起来。
[root@localhost day02]# vim login2.py
#!/usr/bin/env python3
username = input('username: ')
password = input('password: ')
if username == 'bob':
if password == '123456':
print('Login successful')
else:
print('Login incorrect')
else:
print('Login incorrect')
或将上面的代码改为以下写法:
[root@localhost day02]# vim login2.py
#!/usr/bin/env python3
username = input('username: ')
password = input('password: ')
if username == 'bob' and password == '123456':
print('Login successful')
else:
print('Login incorrect')
步骤二:测试脚本执行
[root@localhost day02]# python3 login2.py
username: bob
password: 123456
Login successful
[root@localhost day02]# python3 login2.py
username: bob
password: abcd
Login incorrect
[root@localhost day02]# python3 login2.py
username: tom
password: 123456
Login incorrect
步骤三:改进脚本
脚本程序在运行时,应该将敏感的密码隐藏,不要显示在屏幕上。为了实现这个功能,可以使用getpass模块中的getpass方法。
getpass可以像Linux处理密码一样,屏幕上不出现任何字符,但是用户的输入可以保存到相应的变量中。
上面的代码可以改写为:
[root@localhost day02]# vim login2.py
#!/usr/bin/env python3
import getpass #调用该函数可以在命令行窗口里面无回显输入密码
username = input('username: ')
password = getpass.getpass('password: ')
if username == 'bob' and password == '123456':
print('\033[32;1mLogin successful!\033[0m') #绿色粗体显示
else:
print('\033[31;1mLogin incorrect!\033[0m') #红色粗体显示
测试脚本执行:
[root@localhost day02]# python3 login2.py
username: bob
password: 123456 #此处所填写的密码将不在屏幕上显示
Login successful
[root@localhost day02]# python3 login2.py
username: tom
password: 123456 #此处所填写的密码将不在屏幕上显示
Login incorrect!