Python Problems Guess the Number Game

Question:

I have made a guess the number python game for the terminal, but the game does not recognize when the player wins and i dont understand why. here is my code:

from random import randint

import sys

def function():

    while (1 == 1):

        a = raw_input('Want to Play?')

        if (a == 'y'):

            r = randint(1, 100)

            print('Guess the Number:')
            print('The number is between 1 and 100')

            b = raw_input()

            if (b == r):

                print(r, 'You Won')

            elif (b != r):

                print(r, 'You Lose')    

        elif (a == 'n'):

            sys.exit()  

        else:

            print('You Did Not Answered the Question')          

function()
Asked By: Andrea

||

Answers:

raw_input() returns a string which you are comparing with the int returned by randint

Answered By: FujiApple

This is the correct version of code that I wrote for your question.

import random
while (1 == 1):
   a = raw_input('Want to Play?')
   if (a == 'y'):
     r = random.randint(1, 100)
     print('Guess the Number:')
     print('The number is between 1 and 100')
     b = int(raw_input()) 
     if (b == r):
        print(r, 'You Won')
     elif (b != r):
        print(r, 'You Lose')    
  elif (a == 'n'):
    break   
else:
    print('You Did Not Answered the Question')

Hope this helps.

Answered By: Annapoornima Koppad

As mentioned in FujiApple’s answer:
The type of input by default is a string.

So :

>>>b = raw_input("Enter a number : ")
Enter a number : 5
>>>print b
'5'
>>>type(b)
<type 'str'>

You need to convert the string into an integer, in order it to evalute equal to the randint number :

if int(b) == r:
Answered By: user6568562
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.