首页 > 解决方案 > 我如何获得具有 2 个变量的随机整数?

问题描述

我试图建立一个小数字猜谜游戏。我试图将 2 个变量传递给 random.randint 函数,但无法使其工作。我试图让用户输入我将在特定游戏中使用的最低密码和最高密码。然后在两个输入之间取一个随机数

这就是我的代码的样子。

 lower_limit_sn = int(input('Decide the lowest possible secret number: '))
print(f'{lower_limit_sn}')

upper_limit_sn = int(input('Decide the highest possible secret number: '))
print(f'{upper_limit_sn}')

secret_number = random.randint({lower_limit_sn}, {upper_limit_sn})

这是我得到的错误:

Traceback (most recent call last):
  File PycharmProjects/HelloWorld/While_loops.py", line 26, in <module>
    secret_number = random.randint({lower_limit_sn}, {upper_limit_sn})
  File AppData\Local\Programs\Python\Python37-32\lib\random.py", line 222, in randint
    return self.randrange(a, b+1)
TypeError: unsupported operand type(s) for +: 'set' and 'int'

标签: pythonrandom

解决方案


你使用的语法有点奇怪......

请检查我的更正版本:

import random

lower_limit_sn = int(input('Decide the lowest possible secret number: '))
print(lower_limit_sn)

upper_limit_sn = int(input('Decide the highest possible secret number: '))
print(upper_limit_sn)

secret_number = random.randint(lower_limit_sn, upper_limit_sn)
print(secret_number)

推荐阅读