if-else语句
#10-12&13 记住用户喜欢的数字(与10-13大意相同,将用户名改为喜欢的数字)
import json
def 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 None
else:
return num
def 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 num
def 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 json
def get_stored_num():
'''如果数字已存储,就获取它'''
filename='favortite_number.json'
try:
with open(filename) as f_obj:
num=json.load(f_obj)
except FileNotFoundError:
return None
else:
return num
def 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 num
def 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)
break
else:
break
if favorite_num==None or ans=="No":
favorite_num=get_new_num()
print("Now, I know your favorite number.")
greet_users()