0

I have a really simple code here. But the problem is really bothering me. In line no 7, there is a if-condition; astonishingly this if condition is never addressed! I ran the program and checked multiple times using python version 2.7. It behaves as if the if-condition and its statements (along with break) is inside the comment and is simply ignored.

from random import randint
random_number = randint(1, 10)
guesses_left = 3
while (guesses_left>=1):
    print (random_number)
    guess = raw_input('Guess ?')      
    if guess == random_number: #this statement is never checked?
        print ('You win!')
        break
    guesses_left -= 1 
else:
    print ('You lose.')
madhur
  • 101
  • 2
  • 7
  • 2
    `guess` is a string and `random_number` is an integer. They will never be equal. Use `guess = int(raw_input('Guess ?'))`. – Matthias Sep 30 '15 at 13:06
  • Thank you for rectifying such silly mistake. Yes, now the code runs perfectly – madhur Sep 30 '15 at 13:10
  • @Matthias Wouldn't it be better to convert `random_number` to a string, then there can't be an exception thrown? – Peter Wood Sep 30 '15 at 13:12
  • @PeterWood: In my opinion it should throw an exception. Based on that knowledge one can start to expand the code to handle that. – Matthias Sep 30 '15 at 13:23

2 Answers2

2
if guess == random_number: #this statement is never checked?

It is being checked, but it’s just always false.

guess is a string since it comes from raw_input but random_number is an int coming from randint. Since a string can never be equal to an int, the expression is always false.

You need to convert the input into an int first: int(guess). But make sure you check for errors when the user does not enter a number.

poke
  • 369,085
  • 72
  • 557
  • 602
1

Have you considered that random_number is an integer, while raw_input() returns a string? This means guess is also a string. Try converting the variables to the same type!

Since the types differ, the values are not equal, even though they may appear to be so when printed. In other words 3 != "3".

Jonatan
  • 2,734
  • 2
  • 22
  • 33