在Python中使用json模块的入门问题

 #coding:GBK
import json
def getstoredname():
    filename = 'username.json'
    try:
        with open(filename) as f:
            username = json.load(f)
    except:
        return None
    else:
        return username
        
def getnewname():
    username = input("What is your name? ")
    filename = 'username.json'
    with open(filename,'a+') as f:
        json.dump(username,f)
    return username
    
def greetuser():
    username = getstoredname()
    if username:
        print("Welcome back, " + username + "!")
    else:
        username = getnewname()
        print ("We'll remember you when you come back, " + username + 
            "!")

greetuser()

图片描述
这个问题应该怎么改代码?

阅读 3k
2 个回答
def greetuser():
    username = getstoredname()
    if username and input("Is that your name: " + username + " (y/n)")=="y":       
        print("Welcome back, " + username + "!")
    else:
        username = getnewname()
        print ("We'll remember you when you come back, " + username + 
            "!")

我回答過的問題: Python-QA

import json
'''
如果以前存储了用户名,就加载它,并询问是否为该用户的用户名,否则,
就提示用户输入用户名并存储它 。
'''
filename = 'username.json'
try:

with open(filename) as f_obj:
    username = json.load(f_obj)
    if input('Is that your name: ' + username +'?' + ' (y/n) \n')=='y':
        print("Welcom back,%s!" %username)
    else:
        username = input('What is your name?\n')
        with open(filename,'w') as f_obj:
            json.dump(username,f_obj)
            print("We'll remember you when you come back,%s!" % username)

except FileNotFoundError:

username = input('What is your name?\n')
with open(filename,'w') as f_obj:
    json.dump(username,f_obj)
    print("We'll remember you when you come back,%s!" % username)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题