Python问题猜数字游戏

时间:2016-08-20 15:48:41

标签: python

我已经猜到了终端的数字python游戏,但游戏无法识别玩家何时获胜并且我不明白为什么。这是我的代码:

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()

3 个答案:

答案 0 :(得分:2)

FujiApple's answer中所述: 默认情况下,输入的类型是字符串。

所以:

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

您需要将字符串转换为整数,以便评估等于randint数字:

if int(b) == r:

答案 1 :(得分:1)

raw_input()返回一个字符串,您要与randint

返回的int进行比较

答案 2 :(得分:0)

这是我为您的问题编写的正确代码版本。

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')

希望这有帮助。