import jsonfile = 'favnum.json'def save_fav(): number = input('Type your favourite number: ') with open(file, 'w') as f: num = json.dump(number, f) return numdef get_stored_number(): try: with open(file) as f: number_fav = json.load(f) except FileNotFoundError: return None else: return number_favdef main_number(): num = get_stored_number() if num: print('your favourite number is: ') print(num) else: print('the number had not saved before\nthus you have to save it') numbers = save_fav() print('your number is saved') print(numbers)main_number()输出:the number had not saved beforethus you have to save itType your favourite number: 3.14your number is savedNone
3 回答
largeQ
TA贡献2039条经验 获得超7个赞
我认为你的功能:
def save_fav():
number = input('Type your favourite number: ')
with open(file, 'w') as f:
num = json.dump(number, f)
return num
应该是这样的:
def save_fav():
number = input('Type your favourite number: ')
with open(file, 'w') as f:
json.dump(number, f)
return number
在您的版本中,json.dump返回None,这就是您从函数返回的内容,然后稍后打印。
慕田峪4524236
TA贡献1875条经验 获得超5个赞
因为json.dump
除了 None 之外不会返回任何内容,并且您将其保存在 num 中,并返回 num 所以函数也返回 num 。因此,返回任何有意义的其他内容,例如空字符串。
添加回答
举报
0/150
提交
取消