简体   繁体   English

代码不检查列表中的值?

[英]Code not checking values in list?

This program I am trying to build needs to check if the user's input corresponds to values in a list. 我正在尝试构建的程序需要检查用户的输入是否对应于列表中的值。 Here is the code I have: 这是我的代码:

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)

This is the type of output I should be getting: 这是我应该得到的输出类型:

What day would you like your appointment? saturday
Invaild entry. Please enter a valid day: Monday
The funtion returned Monday

However, it seems that no matter what I input, the function returns it, and doesn't check if the input matches a string in the list: 但是,似乎无论我输入什么,函数都会返回它,并且不会检查输入是否与列表中的字符串匹配:

What day would you like your appointment? akw
The function returned akw

What is wrong with my code that isn't allowing the user's input to be checked whether or not it is in the list day_list? 我的代码有什么问题,该代码不允许检查用户的输入是否在列表day_list中?

First 第一

valid_entry = find_val(answer, possible_vals)
if valid_entry == True:

can be simplified to 可以简化为

if answer in possible_vals:

(your find_val function is totally unnecessary) (您的find_val函数完全没有必要)

Then your problem is that 那你的问题是

while False: 
    ...

simply never executes... Did you mean while True ? 根本就不会执行...你是说while True吗? If so You'll need to somehow break out this (now) infinite loop using a break statement for example. 如果是这样,您将需要使用break语句以某种方式打破这个(现在)无限循环。

And finally as AG suggests, you explicitly tell your program to return answer when it's not "valid" so why do you expect otherwise? 最后,正如AG所建议的那样,您明确地告诉您的程序在“无效”时返回answer ,那么为什么还要这样呢?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM