石头,剪刀,纸游戏无法找出问题所在

时间:2019-07-26 15:07:24

标签: python-3.x

我是新手,正在尝试制作岩石,剪刀纸游戏,但是根据以下代码,即使我输入“ rock”,例如输入进入第一个条件,并给我“ invalid input”输出,但不应如果我正确编写代码会发生这种情况,那么我的错误在哪里?预先感谢

while True:
        u1 = input("do yo want to choose rock, paper or scissors?")
        u2 = input("do you want to choose rock, paper or scissors?")
        if u1 != ('quit' or 'scissors' or 'rock' or 'paper'):
                print("Invalid input! You have not entered rock, paper or scissors, try again.\n")
        elif u2 != ('quit' or 'scissors' or 'rock' or 'paper'):
                print("Invalid input! You have not entered rock, paper or scissors, try again.\n")
        elif u1 == 'quit' or u2 == 'quit':
                break
        elif u1 == u2:
                print("It's a tie!\n")
        elif u1 == 'rock':
                if u2 == 'scissors':
                    print("Rock wins!\n")
                else:
                    print("Paper wins!\n")
        elif u1 == 'scissors':
                if u2 == 'paper':
                    print("Scissors win!\n")
                else:
                    print("Rock wins!\n")
        elif u1 == 'paper':
                if u2 == 'rock':
                    print("Paper wins!\n")
                else:
                    print('Scissors wins!\n'        )

2 个答案:

答案 0 :(得分:1)

您误解了Python的or的工作原理。

u1 != ('quit' or 'rock')u1 != 'quit'相同。这是因为or使用对象的布尔值,并且任何非空字符串都被视为true。因此'quit' or 'rock'等于'quit'

如果要进行此类检查,最好使用列表或使用in设置并检查其存在。

# Using a set
answers = {'quit', 'rock', 'paper', 'scissors'}
while True:
    u1 = ...
    u2 = ...
    if u1 not in answers:
        print('Invalid input:', u1)
    if u2 not in answers:
        print('Invalid input:', u2)

答案 1 :(得分:0)

您使用“或”时应使用“与”。如果满足任何条件,则将返回true,而如果满足所有条件,则将仅返回true。在这种情况下,这就是您想要的,以便仅当u1和u2输入不等于“ rock”和“ paper”,“ scissors”和“ quit”时,输入才无效。使用“或”,即使您输入的内容是“ rock”,由于“ rock”不等于“ paper”或“ scissors”或“ quit”,因此该语句仍会评估为true。尝试将这两个语句用于if测试。

if (u1 != 'quit') and (u1 != 'scissors') and (u1 != 'rock') and (u1 != 'paper'):
elif (u2 != 'quit') and (u2 != 'scissors') and (u2 != 'rock') and (u2 != 'paper'):