在Python中使用json模块的入门问题
黄舟
黄舟 2017-04-18 10:27:47
0
2
714
 #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()


这个问题应该怎么改代码?

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(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 + 
            "!")

Questions I answered: Python-QA

黄舟

import json
'''
If the username has been stored before, load it and ask if it is the user's username, otherwise,
prompt the user to enter the username and store it.
''
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)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template