Your Own while/else: 1 question


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!'
    guesses_left -= 1
    print "You lose."


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


Actually 1 will compare as equal to True

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

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


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


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


Thanks again for clarifying this.


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