dr jerry
dr jerry

Reputation: 10026

python comparing integers in conditions

As a Java programmer I'm going to teach some kids Python. I tasked myself with creating a number guess game, to introduce after a few lessons.

from random import randrange

print("hi I've a number below 100 can you guess??");
theNumber = randrange(100)
theAnswer = raw_input("your first guess >")
while theNumber != theAnswer :
    print (str(theAnswer) + " .. " + str(theNumber) + str(theAnswer > theNumber))
    if theAnswer > theNumber:
        print ("you answer is too large")
    else :
        print ("you answer is too small")

    theAnswer = raw_input("your next guess >")

print ("You guessed!")

It looks like my number comparison goes wrong. Because after my first guess I see:

hi I've a number below 100 can you guess??
your first guess >50
50 .. 64True
you answer is too large

So in the example above 50 is greater than 64. I'm probably overlooking something terrible stupid, but at the moment I don't catch it.

Upvotes: 0

Views: 34

Answers (1)

chepyle
chepyle

Reputation: 996

A fun program! The problem was that raw_input captured the number as text, using int will convert it to a number:

from random import randrange

print("hi I've a number below 100 can you guess??");
theNumber = randrange(100)
theAnswer = int(raw_input("your first guess >"))
while theNumber != theAnswer :
    print (str(theAnswer) + " .. " + str(theNumber) + str(theAnswer > theNumber))
    if theAnswer > theNumber:
        print ("you answer is too large")
    else :
        print ("you answer is too small")

    theAnswer = int(raw_input("your next guess >"))

print ("You guessed!")

Upvotes: 2

Related Questions