'TypeError: '>' not supported between instances of 'str' and 'int' in python OOP
Im creating a simple guessing game that involves 2 players in Python OOP. Im trying to make the code print lower if the guess is higher than the number but it puts an error under the number variable
code
import random
class Players:
def __init__(self, user1, user2):
self.user1 = user1
self.user2 = user2
self.user1_score = 0
self.user2_score = 0
def users(self):
print(f"""Users:
User 1: {self.user1}
User 2: {self.user2}""")
class Guess(Players):
def guess(self):
number = random.randint(0, 100)
print(f"{self.user1}'s turn")
user1_guesses = 0
while user1_guesses < 3:
guess = input("Enter guess: ")
if guess > number:
print("lower")
user1_guesses += 1
if guess == number:
print(f"{self.user1} won!")
self.user1_score += 1
print(f"{self.user1}'s score: {self.user1_score} points")
game = Guess("luke", "yoda")
game.users()
game.guess()
error
if guess > number:
print("lower")
user1_guesses += 1
the error is under number, it says "TypeError: '>' not supported between instances of 'str' and 'int'" can someone help me?
Solution 1:[1]
When you take an input on python, it is taken as a string. So yes, you're actually comparing if str > int. You may want to parse the input to int before continuing and you can also do it in one line.
Change this:
guess = input("Enter guess: ")
To this:
guess = int(input("Enter guess: "))
Take in consideration doing just this won't handle errors and will crash if user inputs something that is not a number.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
