在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()
這個(gè)問題應(yīng)該怎么改代碼?
問題解答
回答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’’’如果以前存儲(chǔ)了用戶名,就加載它,并詢問是否為該用戶的用戶名,否則,就提示用戶輸入用戶名并存儲(chǔ)它 。’’’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)
相關(guān)文章:
1. javascript - JS設(shè)置Video視頻對(duì)象的currentTime時(shí)出現(xiàn)了問題,IE,Edge,火狐,都可以設(shè)置,反而chrom卻...2. java固定鍵值轉(zhuǎn)換,使用枚舉實(shí)現(xiàn)字典?3. 如何為每個(gè)應(yīng)用程序配置tomcat 6的logs / catalina.out。(為sys.out,sys.err配置Web應(yīng)用程序特定的日志文件)4. css - ionic中的柵格布局如何讓文字內(nèi)容多少不同的每一列中的內(nèi)容都能垂直居中?5. php自學(xué)從哪里開始?6. phpstady在win10上運(yùn)行7. java - 我設(shè)置了cookie的max age,但是cookie依然在關(guān)閉游覽器后消失了8. python - flask學(xué)習(xí),user_syy添加報(bào)role is invalid keyword for User.9. 這是什么情況???10. javascript - 用jsonp抓取qq音樂總是說回調(diào)函數(shù)沒有定義
