Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
495 views
in Technique[技术] by (71.8m points)

python - '>' not supported between instances of 'str' and 'int' in my guess the number game

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...