带变量的random.randint |如何

时间:2019-01-24 18:43:17

标签: python python-3.x

我正在尝试使用由变量设置的参数来生成随机数,但是出现无效的语法错误。

我重新编写了代码,并确保我的变量相同。

import random

Run = ("Yes")
while Run == ("Yes"):
  Number_1 = (input("What is the lowest possible number? > "))
  Number_2 = (input("What is the largest possible number? > ")
  Answer = random.randint(int(Number_1), int(Number_2))
  print(int(answer))

我希望它得到变量Number_1和Number_2的值之间的数字的答案,但是我遇到语法错误

1 个答案:

答案 0 :(得分:0)

回答问题

解决方案应该是

import random

Run = ("Yes")
while Run == ("Yes"):
  number_1 = (input("What is the lowest possible number? > "))
  number_2 = (input("What is the largest possible number? > "))
  answer = random.randint(int(number_1), int(number_2))
  print(int(answer))

另一个pythonic解决方案是将while循环更改为while True:

import random

while True:
  number_1 = (input("What is the lowest possible number? > "))
  number_2 = (input("What is the largest possible number? > "))
  answer = random.randint(int(number_1), int(number_2))
  print(int(answer))