有没有办法在random.randint中使用raw_input变量?

时间:2012-01-05 03:18:52

标签: python string integer

我正在制作一款“计算机”试图猜测你想到的数字的游戏。 这里有几段代码:

askNumber1 = str(raw_input('What range of numbers do you want? Name the minimum number here.'))
askNumber2 = str(raw_input('Name the max number you want here.'))

这是为了获得他们希望计算机使用的数字范围。

print 'Is this your number: ' + str(random.randint(askNumber1, askNumber2)) + '?'

这是计算机询问它是否正确,使用random.randint生成一个随机数。问题是1)它不会让我组合字符串和整数,2)不会让我使用变量作为最小和最大数字。

有什么建议吗?

3 个答案:

答案 0 :(得分:1)

如果您创建一个包含范围内的数字的列表并随机排序,然后继续弹出,直到您猜测,否则可能会再次询问某个数字的可能性会更好。

然而,这就是你想要做的事情:

askNumber1 = int(str(raw_input('What range of numbers do you want? Name the minimum number here.')))
askNumber2 = int(str(raw_input('Name the max number you want here.')))

您将其保存为数字而不是字符串。

答案 1 :(得分:1)

正如您所建议的那样,randint需要整数参数,而不是字符串。由于raw_input已经返回一个字符串,因此无需使用str()进行转换;相反,您可以使用int()将其转换为整数。但请注意,如果用户输入的内容不是整数,例如“hello”,那么这将抛出异常并且您的程序将退出。如果发生这种情况,您可能需要再次提示用户。这是一个重复调用raw_input的函数,直到用户输入一个整数,然后返回该整数:

def int_raw_input(prompt):
    while True:
        try:
            # if the call to int() raises an
            # exception, this won't return here
            return int(raw_input(prompt))
        except ValueError:
            # simply ignore the error and retry
            # the loop body (i.e. prompt again)
            pass

然后,您可以将其替换为raw_input的来电。

答案 2 :(得分:0)

范围编号存储为字符串。试试这个:

askNumber1 =int(raw_input('What range of numbers do you want? Name the minimum number here.'))
askNumber2 =int(raw_input('Name the max number you want here.'))

这是为了获得他们希望计算机使用的数字范围。

print 'Is this your number: ' + str(random.randint(askNumber1, askNumber2)) + '?'
相关问题