创造石头,纸,剪刀游戏

时间:2019-05-11 11:59:20

标签: python python-3.x

我不知道为什么我编写的程序不起作用,我真的很想知道。

我看过很多有效的代码,但是我仍然想知道为什么我编写的代码不起作用

user1_input = input(" User 1 choose your pick: Rock = 1, Scissor = 2, paper = 3 \n:")
user2_input = input(" User 2 choose your pick: Rock = 1, Scissor = 2, paper = 3 \n:")

def compare(user1_input,user2_input):
    if user1_input == user2_input:
        return("It is a tie!")

    elif user1_input == 1:
        if user2_input == 2:
            return("User 1 Wins")
        else:
            return("User 1 lose")

    elif user1_input == 2:
        if user2_input == 1:
            return("User 1 loses")
        else:
            return("User 1 wins")

    elif user1_input == 3:
        if user2_input == 1:
            return("User 1 wins")
        else:
            return("User 1 loses")

    else:
        return("Invalid input!")


print(compare(user1_input,user2_input))

如果您为用户1输入3,为用户2输入1,则应该说用户1输了,但一直在说无效输入。

3 个答案:

答案 0 :(得分:1)

因为您的输入是字符串,并且将字符串与整数进行比较,所以它返回无效的输入:

您可以使用int()将字符串转换为int,或者仅将其与字符串进行比较,就像我在下面的代码中所做的那样,选择是您自己的。

    user1_input = input(" User 1 choose your pick: Rock = 1, Scissor = 2, paper = 3 \n:")
    user2_input = input(" User 2 choose your pick: Rock = 1, Scissor = 2, paper = 3 \n:")

    def compare(user1_input,user2_input):
        if user1_input == user2_input:
            return("It is a tie!")

        elif user1_input == '1':
            if user2_input == '2':
                return("User 1 Wins")
            else:
                return("User 1 lose")

        elif user1_input == '2':
            if user2_input == '1':
                return("User 1 loses")
            else:
                return("User 1 wins")

        elif user1_input == '3':
            if user2_input == '1':
                return("User 1 wins")
            else:
                return("User 1 loses")

        else:
            return("Invalid input!")


    print(compare(user1_input,user2_input))

答案 1 :(得分:0)

问题在于user1_inputuser2_input是字符串,您将它们与int进行比较,因此您FalseInvalid input!

要解决此问题-

user1_input = int(input(" User 1 choose your pick: Rock = 1, Scissor = 2, paper = 3 \n:"))
user2_input = int(input(" User 2 choose your pick: Rock = 1, Scissor = 2, paper = 3 \n:"))

答案 2 :(得分:0)

input()返回一个字符串值。您需要将其转换为整数才能进行比较。

所以代替:

user1_input = input(" User 1 choose your pick: Rock = 1, Scissor = 2, paper = 3 \n:")
user2_input = input(" User 2 choose your pick: Rock = 1, Scissor = 2, paper = 3 \n:")

尝试以下方法:

user1_input = int(input(" User 1 choose your pick: Rock = 1, Scissor = 2, paper = 3 \n:"))
user2_input = int(input(" User 2 choose your pick: Rock = 1, Scissor = 2, paper = 3 \n:"))