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()
Answers:
raw_input()
returns a string which you are comparing with the int returned by randint
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.
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:
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()
raw_input()
returns a string which you are comparing with the int returned by randint
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.
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: