Python练习题 10-11~10-12喜欢的数字

10-11 喜欢的数字:编写一个程序,提示用户输入他喜欢的数字,并使用
json.dump()将这个数字存储到文件中。再编写一个程序,从文件中读取这个值,并打
印消息“I know your favorite number! It’s _.”。
10-12 记住喜欢的数字:将练习 10-11 中的两个程序合而为一。如果存储了用户喜
欢的数字,就向用户显示它,否则提示用户输入他喜欢的数字并将其存储到文件中。运
行这个程序两次,看看它是否像预期的那样工作。

#coding:utf-8
import json
string="please enter your favorite number: "
Number=input(string.title())
filename='Favorite_number.json'
with open(filename,'w') as f_obj:
    json.dump(int(Number),f_obj)
with open(filename) as f_obj:
    User_number=json.load(f_obj)
    print("I know your favorite number is "+str(User_number))

运行结果:

Please Enter Your Favorite Number: 2
I know your favorite number is 2


------------------
(program exited with code: 0)

请按任意键继续. . .

之前我犯了个错误,在string="please enter your favorite number: "这一步里面我最开始用的是str="please enter your favorite number: ",结果就出现了异常= =

Please Enter Your Favorite Number: 2
Traceback (most recent call last):
  File "喜欢的数字.py", line 10, in <module>
    print("I know your favorite number is "+str(User_number))
TypeError: 'str' object is not callable


------------------
(program exited with code: 1)

请按任意键继续. . .

你可能感兴趣的:(python练习题,python)