Python实现简易用户登录与注册系统

慢慢来
慢慢来
发布时间:2026-10-13 | 3人浏览过
原创

本文介绍如何使用Python编写一个简易的用户登录与注册程序。代码利用getpass模块隐藏密码输入,通过字典结构存储用户信息,并实现新用户注册、老用户登录及退出功能。程序包含基本的异常处理机制,适合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 相关产品和应用

全部下载

专题列表