【python】练习 10.14:验证⽤户 最后⼀个 remember_me.py 版本假设⽤户要么 已输⼊其⽤户名,要么是⾸次运⾏该程序。

练习 10.14:验证⽤户 最后⼀个 remember_me.py 版本假设⽤户要么 已输⼊其⽤户名,要么是⾸次运⾏该程序。我们应修改这个程序,以 防当前⽤户并⾮上次运⾏该程序的⽤户。

要求

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


代码

from pathlib import Path
import json


def get_stored_username(path):
    """如果存储了⽤户名,就获取它"""
    if path.exists():
        contents = path.read_text()
        username = json.loads(contents)
        return username['username']
    else:
        return None


def get_new_username(path):
    """获取用户名以判断是否相符"""
    username = input("What is your name?: ")
    return username


def get_new_user_info(path):
    """提⽰⽤户输⼊用户信息"""
    user_info = {}
    username = input("What is your name?: ")
    user_info['username'] = username
    age = input("How old are you?: ")
    user_info['age'] = age
    fav_food = input("What food you like?: ")
    user_info['favorite food'] = fav_food

    contents = json.dumps(user_info)
    path.write_text(contents)
    return username


def greet_user():
    """问候⽤户,并指出其名字"""
    path = Path('username.json')
    new_name = get_new_username(path)
    username = get_stored_username(path)
    if new_name == username:
        print("it's right")
        if username:
            print(f"Welcome back, {username}!")
        else:
            username = get_new_user_info(path)
            print(f"We'll remember you when you come back, {username}!")
    else:
        print("username is wrong")
        greet_user()


def get_info():
    """获取用户信息"""
    path = Path('username.json')
    contents = path.read_text()
    infos = json.loads(contents)
    for key, value in infos.items():
        print(f"{key}:{value}")
    return infos


def judgment_user(path):
    """判断用户是谁"""
    path = Path('username.json')
    username = get_stored_username(path)


greet_user()
get_info()

打印

请添加图片描述

  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值