首页 > 解决方案 > 仅当一个或多个项目时,我如何使 for 循环工作!='是'

问题描述

我正在做一个硬件任务,在那里我创建一个带有入门问题的假俱乐部。如果任何问题的回答为“否”,则不允许此人加入。

我试过回到关于列表和循环的 og 课程,但我找不到我想要在那里做的事情。

到目前为止,这是我的代码。

# Purpose: Create a fake club that has certain requirements, ask user to
# fill out the application, and print out their answers + results.

def main():
    display = input('Hi! This is your application to The Aqua Project...')
    display2 = input('Read the following questions and just type y or n')

# Weird list format...
    user = [input('Are you at least 18 yrs old? '),
    input('Can you work with other people? '),
    input('Do you like animals? '),
    input('Are you okay with getting dirty sometimes? ')]



# Here's the problem, I want to print 'sorry you cant join' once...

    for i in range(4):
        if user[i] != 'y':
            print('Sorry, but you can\'t join our club')
            justToShowInCMD = input('')
            i += 1
        else:
            print('')
            print('Congratulations, you have met all of our requirements!')
            print('We will send an email soon to discuss when our team')
            print('will meet up to help save some animals!')
            print('In the meantime, visit our website at 
            TheAquaProject.com')
            justToShowInCMD = input('')

main()

当您为某些问题添加“n”时,它表示您可以加入,但对于其他问题,它表示您不能加入。我不知道为什么有时当你在面试中拒绝时它说你可以,但不应该。

标签: pythonpython-3.x

解决方案


执行此操作的常用方法是带有 a和子句的for循环:breakelse

for answer in user:
    if answer != 'y':
        print('Sorry')
        break
else:
    print('Congratulations')

any()功能:

if any(answer != 'y' for answer in user):
    print('Sorry')
else:
    print('Congratulations')

推荐阅读