Python入门习题大全——记住喜欢的数字

Python入门习题大全——索引

将练习“喜欢的数字”中的两个程序合而为一。如果存储了用户喜欢的数字,就向用户显示它,否则提示用户输入他喜欢的数字并将其存储到文件中。运行这个程序两次,看看它是否像预期的那样工作。

当没有 a.json 文件时,输如数字并保存
当有此文件时,直接读取并输出

# 记住喜欢的数字
import json

filename = 'a.json'
try:
    with open(filename) as f_obj:
        number = json.load(f_obj)
except FileNotFoundError:
    a = input("请输入你喜欢的数字:")
    with open(filename, 'w') as f_obj:
        json.dump(a, f_obj)
    print("I will remember it!")
else:
    print("I know you favorite number! It's ", end='')
    print(number + '.')
发布了340 篇原创文章 · 获赞 33 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_43479432/article/details/105565260