'Python newbie does not understand why his comparison doesnt work
So i've set myself the goal of learning programming with Python. I've started about 3 days ago and decided to start with a random number generating game as a starting Project. The problem i have with my code is that my make_try method isn't giving me the right outputs. It just always goes with the else statement, even if the comparison in the if statement should be right. I personally am very frustrated right now and i hope you can help me. Greetings Marc
import random
class Test:
def __init__(self):
self.number1 = random.randrange(1, 20)
self.score = 100
def first_tip(self):
print(self.number1)
if(self.number1 % 2 == 0 and self.number1 <= 10):
print("Your number is even and smaller than 10")
elif(self.number1 % 2 == 0 and self.number1 >= 10):
print("Your number is even and bigger than 10")
elif(self.number1 % 2 != 0 and self.number1 <= 10):
print("Your number is uneven and smaller than 10")
elif(self.number1 % 2 != 0 and self.number1 >= 10):
print("Your number is uneven and bigger than 10")
def make_try(self):
print("My guess would be:")
testguess = input()
if(self.number1 == testguess):
new_score = self.score + 100
print("*****************")
print("*Congratulations*")
print("*****************")
print(f"Your final score: {new_score}")
else:
new_score = self.score -10
print("Wrong!")
print(f"Your new score: {new_score}")
x = input("Try again?(Yes/No)")
print(x)
if __name__ == "__main__":
T1 = Test()
T1.first_tip()
T1.make_try()
Solution 1:[1]
You have different types in your comparison
testguess = input() means that testguess is a string
self.number1 = random.randrange(1, 20) means that self.number1 is an integer
simplest way to fix this is by: testguess = int(input())
Solution 2:[2]
Problem is input types, thats why as a newbie I would probably recommend C# or C++ bc you have more or total control over your types,
To fix this problem of your I simply added a cast to this line, and it works properly
if(self.number1 == int(testguess)):
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 | |
| Solution 2 | Josip Juros |
