I am learning python and i can\'t figure out why the following program is printing your number is greater than what i thought even when the guessed number is sm
Here datatype of guess is string where as datatype of number is integer,
guess = raw_input ("Guess:")
so both are not same, hence if statement is executed every time
if guess > number:
as string datatype is considered greater than integer datatype in python.
Therefor you need to change the datatype of guess to int.
Following code will help you do this
guess = int(raw_input ("Guess:"))
Catching an exception might help as well if you are guessing a large number and you accidentally hit a letter you don't really want your program to bail out.
while guess != number:
if guess > number:
print("Your guess is greater than i thought")
else:
print("Your guess is smaller than i thought")
try:
guess = int(raw_input ("Another Guess:"))
tries = tries+1
except ValueError:
print "Input must be numeric"
print "You guess it right in %d turns." %tries
I didn't know this until just now, but as it turns out, a string will always be "greater than" an integer in Python:
>>> "0" > 1
True
All you need to do is replace
guess = raw_input ("Guess:")
with
guess = int(raw_input ("Guess:"))
I think this is because raw_input is considered a string, so Python assigns it a value based on the char values. Try writing int(raw_input("text")) and see if it solves your problem.
raw_input
will return a string. You need to parse it into a number for the compare to work properly. I think that's just int(raw_input(...))