Your Own while/else: 1 question


#1

This is my code, and the system gave me a green light. Console works fine

However, most people use

if guess == random_number:

but mine is

if guess == True:

Instruction says: If they guess correctly, print 'You win!'
When it says guess correctly, can I really use "True" ?

from random import randint

# Generates a number from 1 through 10 inclusive
random_number = randint(1, 10)

guesses_left = 3
# Start your game!
while guesses_left > 0:
    guess = int(raw_input("Your guess: "))
    if guess == True:
        print 'You win!'
        break
    guesses_left -= 1
else:
    print "You lose."


#2

No. It will never occur. Match to the number as the program is intended to.


#3

Actually 1 will compare as equal to True

>>> isinstance(True, int)
True
>>> 1 == True
True
>>> True == 1
True

But the comparison guess == True does indeed not make sense and one will need to reconsider what comparison is supposed to happen at that moment and that decision isn't really related to code but to the rules of the game


#4

D'oh! Yes, 1 or any other number. What was I thinking? Thanks for the nudge.


#5

Noo just 1! and False is an int with the value 0. No other ints will compare as equal to those.
bool inherits int and its two instances (there are always exactly two, there are no duplicates) have the integer values 0 and 1 which also allows testing for True but not 1 with the is-operator, since 1 and True are separate objects but There is always only one True so True is always the same object as True


#6

Thanks again for clarifying this.


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.