用Python写一段用户登录的程序代码

yipeiwu_com5年前Python基础

如下所示:

#!/usr/bin/env python
#coding: utf8
import getpass
db = {}
def newUser():
 username = raw_input('username: ')
 if username in db:
 #添加打印颜色
 print "\033[32;1m%s already exists![0m" % username
 else:
 #屏幕不显示密码,调用getpass.getpass()
 password = getpass.getpass()
 db[username] = password #字典k-v赋值
def oldUser():
 username = raw_input('username: ')
 password = getpass.getpass()
 if username in db:
 if db.get(username) == password:#判断输入的用户名和密码是否和字典的k-v匹配
  print '\033[32;1mlogin successful!\033[0m'
 else:
  print '\033[32;1mpassword not match username\033[0m'
 else:
 print '\033[32;1musername does not exist\033[0m'
CMDs = {'n':newUser,'o':oldUser}
def showMenu():
 prompt = """(N)ew user
(O)ld user
(Q)uit
input your choice: """
 while True:
 try:#捕获ctrl+c ctrl+d的异常
  choice = raw_input(prompt).strip().lower()[0]
 except (KeyboardInterrupt, EOFError):
  choice = 'q'
 if choice not in 'noq':
  continue
 if choice == 'q':
  break
 CMDs[choice]()#这种方法相当于shell和c里面的case,很实用
if __name__ == '__main__':
 showMenu()

以上这篇用Python写一段用户登录的程序代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

利用soaplib搭建webservice详细步骤和实例代码

最近在搞基于python的webservice项目,今天为把环境给配好,折腾了不少时间,还是把配的过程记录下来,以后备用:首先你系统上要有python,这个不必说啦,我系统上用的是2.7...

python 使用socket传输图片视频等文件的实现方式

在开发一些需要网络通信的应用中,经常会用到各种网络协议进行通信,博主在开发实验室的机器人的时候就遇到了需要把机器人上采集到的图片传回服务器进行处理识别,在python下的实现方式如下(只...

python cx_Oracle模块的安装和使用详细介绍

python cx_Oracle模块的安装 最近需要写一个数据迁移脚本,将单一Oracle中的数据迁移到MySQL Sharding集群,在linux下安装cx_Oracle感觉还是有一...

python zip文件 压缩

从简单的角度来看的话,zip格式会是个不错的选择,而且python对zip格式的支持够简单,够好用。1)简单应用 如果你仅仅是希望用python来做压缩和解压缩,那么就不用去翻文档了,这...

Python函数的默认参数设计示例详解

在Python教程里,针对默认参数,给了一个“重要警告”的例子: def f(a, L=[]): L.append(a) return L print(f(1)) prin...