'>' not supported between instances of 

2020-02-06 18:09发布

In my guess the number program it gives me the error: '>' not supported between instances of 'str' and 'int' on line 26 in main. I would be grateful if someone helped me with this, Thank you.

import random
guesses = 0


def higher(guesses):
    print("Lower")
    gueeses += 1


def lower(guesses):
    print("Higher")
    guesses += 1


def correct(guesses):
    print("You got it correct!")
    print("It was {0}".format(number))
    guesses += 1


def _main_(guesses):
    print("Welcome to guess the number")
    number = random.randint(1, 100)
    while True:
        guess = input("Guess a number: ")
        if guess > number:
            lower(guesses)
        elif guess < number:
            higher(guesses)
        elif guess == number:
            correct(guesses)
            while True:
                answer = input("Would you like to play again? Y or N: ")
                if answer == "Y":
                    break
                elif answer == "N":
                    exit()
                else:
                    exit()


_main_(guesses)

标签: python input
1条回答
SAY GOODBYE
2楼-- · 2020-02-06 18:54

By default, input returns a string. You need to convert your input to a numeric type, in this case integer.

Replace:

guess = input("Guess a number: ")

With:

guess = int(input("Guess a number: "))

You may also wish to validate user input to ensure that you have actually been provided with a valid integer. For this you should see Asking the user for input until they give a valid response.

查看更多
登录 后发表回答