• python 从入门到实践 练习10-13 验证用户


    练习10-13 验证用户

    最后一个remember_me.py 版本假设用户要么已输入用户名,要么是首次运行该程序。我们应该修改这个程序,以防当前用户并非上次运行该程序的用户。

    为此,在 greet_user() 中打印欢迎用户回来的消息前,询问他用户名是否正确。如果不对,就调用 get_new_username() 让用户输入正确的用户名。

     1 import json
     2 
     3 def get_stored_username():
     4     '''如果存储了用户名,就获取它'''
     5     filename = 'username.json'
     6     try:
     7         with open(filename) as f:
     8             username = json.load(f)
     9     except FileNotFoundError:
    10         return None
    11     else:
    12         return username
    13 
    14 def get_new_username():
    15     '''提示用户输入用户名'''
    16     username = input("Please enter your username: ")
    17     filename = 'username.json'
    18     with open(filename, 'w') as f:
    19         json.dump(username, f)
    20     return username
    21 
    22 def greet_user():
    23     """基于用户名问候用户"""
    24     username = get_stored_username()
    25     if username:
    26         correct = input(f"Are you {username}? (y/n)")
    27         if correct == 'y':
    28             print(f"Welcome back, {username}!")
    29         else:
    30             username = get_new_username()
    31             print(f"We'll remember you when you come back, {username}!")
    32     else:
    33         username = get_new_username()
    34         print(f"We'll remember you when you come back, {username}!")
    35 
    36 greet_user()
  • 相关阅读:
    web.config配置错误的后果
    重装VS.NET碰到:IDE 未能加载 Dte.olb
    初次使用Wix
    typedef
    [WTL] Accelerator
    在浏览器中粘贴时替换剪贴板数据
    自定义浏览器
    关于MSHTML
    [WTL] STLport安装指南
    [WTL] WTL7.5中CFileDialog用'\0'过滤
  • 原文地址:https://www.cnblogs.com/hanyu1995/p/14528547.html
Copyright © 2020-2023  润新知