在Python中使用json模块的入门问题
问题描述
#coding:GBKimport jsondef getstoredname(): filename = ’username.json’ try:with open(filename) as f: username = json.load(f) except:return None else:return usernamedef 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()
这个问题应该怎么改代码?
问题解答
回答1: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
回答2: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)
相关文章:
1. javascript - PC端微信登陆授权js多次请求问题2. 在webstorm里配置nodejs,在配置Sources of Node.js Modules时为什么找不到路径3. php工具箱配置第二个vhost主机时不生效,报错You don’t have permission4. docker绑定了nginx端口 外部访问不到5. Python列表或者字典里面的中文如何处理?6. angular.js - AngularJS如何添加的DOM元素且能绑定事件7. 同一个html页面用多个id有什么影响?8. css - 元素跟随鼠标轻微移动效果,求指教实现方法?9. javascript - ios返回不执行js怎么解决?10. python - 在github上看到一个基于卷积神经网络提高图片分辨率的小项目waifu2x??

网公网安备