[Tutor] comparison on Types

Steven D'Aprano steve at pearwood.info
Wed Apr 29 13:14:06 CEST 2015


On Wed, Apr 29, 2015 at 09:44:28AM +0000, Ian D wrote:

> I was looking at the example code below. I am using python 2.7.
> 
> I am wondering why when I substitute the while n! = "guess" to while 
> n!= guess (<-- no quotes) I get a problem?

Really? What sort of problem? It looks okay to me, although I haven't 
run it.


> The Type string is used for the first conditional comparison in the 
> outer While loop, but afterwards the Type is an int.
> 
> I would have expected the guess variable to be used as Type int as it 
> seems to be cast in the raw_input statement and would be comparable to 
> another int that's stored in variable n. Thanks

I'm having difficulty understanding your question. It might help if you 
explain what you think the code should do, versus what it actually does. 
Do you get an error? Then post the full error traceback, starting from 
the line "Traceback" to the end.

It also might help to understand that in Python, *variables* don't have 
types, but values do. Variables can take any value, and take on the type 
of that value until such time as they change to a different value:

py> x = "Hello"
py> type(x)
<type 'str'>
py> x = 23
py> type(x)
<type 'int'>




Looking at your code, I can see only one obvious (to me) problem:

> import random
> n = random.randint(1, 99)
> guess = int(raw_input("Enter an integer from 1 to 99: "))
> while n != "guess":

By using the string "guess", you guarantee that n is *never* equal on 
the first test. That means that the loop will be entered. If you remove 
the quotation marks, and compare n != guess (here guess is the variable, 
not the literal string) then if your guess happens to be correct on the 
first time, the while loop will not be entered and the program will just 
end.

     print
>     if guess < n:
>         print "guess is low"
>         guess = int(raw_input("Enter an integer from 1 to 99: "))
>     elif guess> n:
>         print "guess is high"
>         guess = int(raw_input("Enter an integer from 1 to 99: "))
>     else:
>         print "you guessed it!"
>         break
>     print  		 	   		  


Try this instead:


import random
n = random.randint(1, 99)
guess = 0  # Guaranteed to not equal n.
while n != guess:
    guess = int(raw_input("Enter an integer from 1 to 99: "))
    print
    if guess < n:
        print "guess is too low"
    elif guess > n:
        print "guess is too high"
    else:
        print "guessed correctly!"




Does that help?



-- 
Steve


More information about the Tutor mailing list