AI智能
改变未来

JSON格式保存和读取用户数据 | 程序重构

if-else语句

#10-12&13 记住用户喜欢的数字(与10-13大意相同,将用户名改为喜欢的数字)import jsondef get_stored_num():\'\'\'如果数字已存储,就获取它\'\'\'filename=\'favortite_number.json\'#文件名后不加.json扩展名,创建的不是JSON格式文件;但程序也可运行try:with open(filename) as f_obj:num=json.load(f_obj)#加载存储在文件f_obj中数据except FileNotFoundError:return Noneelse:return numdef get_new_num():\'\'\'若未存储,提示用户输入\'\'\'num=input(\"Please enter your favorite number: \")filename=\'favortite_number.json\'with open(filename,\'w\') as f_obj:json.dump(num,f_obj)#在文件f_obj中写入num数据return numdef greet_users():\'\'\'问候用户,输出其最喜欢的数字\'\'\'favorite_num=get_stored_num()if favorite_num:ans=input(\"Is your favorite number is \" + favorite_num +\" ? (Yes or No)\\n\")#若存储数字是用户喜欢的数字,则输出,否则重新输入if ans==\"Yes\":print(\"So your favorite number is \" + favorite_num)else:favorite_num=get_new_num()print(\"Now, I know your favorite number.\")else:favorite_num=get_new_num()print(\"Now, I know your favorite number.\")greet_users()

While-if-else语句

#10-12&13 记住用户喜欢的数字(与10-13大意相同,将用户名改为喜欢的数字)import jsondef get_stored_num():\'\'\'如果数字已存储,就获取它\'\'\'filename=\'favortite_number.json\'try:with open(filename) as f_obj:num=json.load(f_obj)except FileNotFoundError:return Noneelse:return numdef get_new_num():\'\'\'若未存储,提示用户输入\'\'\'num=input(\"Please enter your favorite number: \")filename=\'favortite_number.json\'with open(filename,\'w\') as f_obj:json.dump(num,f_obj)return numdef greet_users():\'\'\'问候用户,输出其最喜欢的数字\'\'\'favorite_num=get_stored_num()while favorite_num:ans=input(\"Is your favorite number is \" + favorite_num +\" ? (Yes or No)\\n\")#若存储数字是用户喜欢的数字,则输出,否则重新输入if ans==\"Yes\":print(\"So your favorite number is \" + favorite_num)breakelse:breakif favorite_num==None or ans==\"No\":favorite_num=get_new_num()print(\"Now, I know your favorite number.\")greet_users()
赞(0) 打赏
未经允许不得转载:爱站程序员基地 » JSON格式保存和读取用户数据 | 程序重构