-2

我的代码有问题,我也找不到解决方案。我询问必须有效但循环仍在继续的问题,然后让我输入。

print('Do you want to go to the store or woods?')

lists = ('woods', 'store')
while True:
    answers = input()    
    if answers == 'store':
        break
        print('Going to the store...')
    elif answers == 'woods':
        break
        print('Going to the woods...')
    while lists not in answers:
        print('That is not a valid answer')
4

3 回答 3

2

您想检查用户的答案是否不在您的有效答案列表中。你正在做的事情是相反的。尝试这个:

if answers not in lists:
    print('That is not a valid answer')

您还需要break在那个时候,或者再次打印您的提示信息。

于 2016-08-17T16:03:49.380 回答
1

首先,您的print陈述是不可访问的。您可以在此处找到更多信息。

#...
if answers == 'store':
        print('Going to the store...')
        break
    elif answers == 'woods':
        print('Going to the woods...')
        break
#...

那么,您的第二个while陈述以这种方式没有意义。如果您只是想打印That is not a valid answer以防输入与输入不同storewoods再给用户一次尝试 - 那么您可以只使用,根本else不需要:lists

print('Do you want to go to the store or woods?')

# no lists
while True:
    answers = input()
    if answers == 'store':
        print('Going to the store...')
        break
    elif answers == 'woods':
        print('Going to the woods...')
        break
    else:
        print('That is not a valid answer')

如果您想检查是否在 中遇到用户的输入lists,那么您需要从in内到外执行此技巧:

print('Do you want to go to the store or woods?')

lists = ('woods', 'store')
while True:
    answers = input()
    if answers == 'store':
        print('Going to the store...')
        break
    elif answers == 'woods':
        print('Going to the woods...')
        break
    elif answers not in lists:
        print('That is not a valid answer')
    else:
        # some default case, for example sys.exit() (needs sys to be imported)
于 2016-08-17T16:15:45.517 回答
1

尝试这个:

print('Do you want to go to the store or woods?')
places = ('woods', 'store')
while True:
    answer = input()
    if answer in places:
        print ("Going to the {0}...".format(answer))
        break
    else:
        print('That is not a valid answer')
于 2016-08-17T16:03:57.057 回答