[Tutor] comparison on Types

Peter Otten __peter__ at web.de
Wed Apr 29 12:51:54 CEST 2015


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?

What is that problem? The only thing I see is that the

>     else:
>         print "you guessed it!"
>         break

branch is never executed. You remove it and instead put the 

>         print "you guessed it!"

statement after the loop.
 
> The Type string is used for the first conditional comparison in the outer
> While loop, but afterwards the Type is an int.

Not even that. The guess name is bound to an integer before the loop is 
entered:

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

> 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

You have that right.

> import random
> n = random.randint(1, 99)
> guess = int(raw_input("Enter an integer from 1 to 99: "))
> while n != "guess":
>     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




More information about the Tutor mailing list