[prog] why doesn't this program work? (python)
Elizabeth Barham
lizzy at soggytrousers.net
Wed Dec 18 23:36:58 EST 2002
"Guru -" <haunter03 at hotmail.com> writes:
> I'm just a little confused on why this program does not work? (python)
> The print functions are there to help me work out what is going wrong, it
> has to be something very simple that I'm missing...
>
> #Plays the higher or lower game
> #uses the time, seconds as the random no.
> #the aim is to have a random no. assigned and have someone guess it....with
> #them getting hints of higher and lower
> #prob. is it doesn't exit the while loop when the correct no. is guessed....
> from time import strftime
> number = strftime("%S")
> print number
> guess = 0
>
> while guess != number:
> guess = input("Guess a number: ")
> if guess < number:
> print "Too low"
> elif guess > number:
> print "Too high"
>
> print "Just right :)"
Hi,
I have not programmed in python before but I was able to fix your
code by modifying the 'number' assignment to:
number = int(strftime("%S"))
My guess as to the reason why the origiras did not work is because
'number' appears to the python interpreter as a string, and so
internally it is classified as a string and not a number.
From:
<http://www.python.org/doc/current/ref/comparisons.html>
Strings are compared lexicographically using the numeric
equivalents (the result of the built-in function ord()) of
their characters. Unicode and 8-bit strings are fully
interoperable in this behavior.
I also guess that the "input" function expects a number, so
'guess' is assigned a number and 'guess' is compared with the string
'number', which is going to be unequal and *less* than the string
because the string is stored internally as ASCII characters.
By insuring that the variable 'number' is assigned a number and
not a string using the int() function, we guarantee that the
comparisons later on are number-to-number comparisons.
Elizabeth
More information about the Programming
mailing list