我正在尝试构建的程序需要检查用户的输入是否与列表中的值相对应。这是我的代码:
def find_val(val, seq):
for ele in seq:
if val == ele:
return True
return False
def get_input(possible_vals, day_or_time_string):
if day_or_time_string == "day":
answer = input("What day would you like your appointment? ")
else:
answer = input("What time would you like your appointment? ")
answer = answer.strip()
valid_entry = find_val(answer, possible_vals)
if valid_entry == True:
count = 0
while False:
second_answer = input("Invalid entry. Please enter a valid day: ")
count = count + 1
if count == 3:
print("This is getting silly - still not a valid entry")
if second_answer in possible_vals:
return second_answer
else:
return answer
day_list = ["Monday", "Tuesday", "Wednesday"]
res = get_input( day_list, "day" )
print("The funtion returned", res)
这是我应该得到的输出类型:
What day would you like your appointment? saturday
Invaild entry. Please enter a valid day: Monday
The funtion returned Monday
但是,似乎无论我输入什么,该函数都会返回它,并且不会检查输入是否与列表中的字符串匹配:
What day would you like your appointment? akw
The function returned akw
我的代码有什么问题,不允许检查用户的输入是否在列表day_list中?
答案 0 :(得分:2)
首先
valid_entry = find_val(answer, possible_vals)
if valid_entry == True:
可以简化为
if answer in possible_vals:
(您的find_val
功能完全没必要)
然后你的问题是那个
while False:
...
根本就不会执行......你的意思是while True
吗?如果是这样你需要以某种方式使用break
语句以某种方式突破这个(现在)无限循环。
最后,正如A.G.建议的那样,当你的程序不是“有效”时,你明确告诉你的程序返回answer
,那你为什么不这么想呢?