循环不会在我想要的时候停止重复吗?

时间:2019-10-09 00:15:01

标签: python while-loop

此代码应询问用户输入,如果他们未输入五个字符串之一,则应继续询问直到输入。但是,当我添加while循环来完成此操作时,它无法识别有效输入,但仍会继续循环输入

def main():
    print('----- AVATAR -----')

    avatar = input('Select an Avatar or create your own:\n')
    #if input is not one of these V then it should keep asking
    #if input is one of these, go to if statements
    while (avatar != 'exit' or avatar != 'Jeff' or 'custom' or 'Chris' or 'Adam'):
        avatar = input('Select an Avatar or create your own:\n')

    if avatar == 'exit':
        return avatar
    elif avatar == 'Jeff':
        hat('both')
        face("True", "0")
        arm_style("=")
        torso_length(2)
        leg_length(2)
        shoe_style("#HHH#")
    elif avatar == 'Adam':
.....

然后有用于所有5个有效输入的elif语句

2 个答案:

答案 0 :(得分:0)

这可能是因为在您的while子句中,您停止检查'avatar!='而只是具有'或'custom'和'或'Chris'等。

这等效于说“或字符串”。布尔检查中的非空字符串本身的计算结果为“ true”。因此,您的while循环具有恒定的'true'值,这是因为您没有检查字符串是否等于某个东西,而仅仅是一个字符串。

答案 1 :(得分:-1)

您的循环代码不正确。它必须是以下内容:

while (avatar != 'exit' and avatar != 'Jeff' and avatar !='custom' and avatar !='Chris' and avatar !='Adam'):