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)

請按任意鍵繼續. . .
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章