有没有办法在random.randint中使用raw_input变量?
我正在制作一个游戏,里面的“电脑”会尝试猜测你心里想的数字。
这里有几段代码:
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
这些范围数字是以字符串的形式存储的。你可以试试这个:
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)) + '?'
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
正如你所提到的,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
。