Python - 为什么我的随机数生成器不工作?

Python - why is my random number generator not working?

我已经尝试了很多年如何让它发挥作用。它应该选择一个带有 'from random import randrange' 的随机数,后跟行 'x = randrange(1,3)。我在其他时候使用过那个生成器并且它当时可以工作但是它不能用于这个:/。 这是代码:

from random import randrange
numberboy == randrange(7,9)
if numberboy == "7":
    print ("You unluckily fall into a pit!")
    health -= 1
    if health == "1":
        print ("You drop to your knees and lie, filled with pain in the pit. You drop to the floor. Your quest is over.")
        print ("Your health has fallen to " + str(health) + ". ")



if numberboy == "8" or "9":
    print ("You could have fallen into a pit but you luckily didn't!")
    print ("You find a path leading of to another room.")

print ("You walk down the path and find a light illuminating an elvish sword!")
print ("You walk out of an escape path and find youself coming out of a secret entrance at the clearing.")
import time

顺便说一句,之前使用 'numberboy = 0' 使其工作(numberboy 是变量,x)

您正在将数字与字符串进行比较...

使用:

if numberboy == 7:

而不是:

if numberboy == "7":

健康也一样,用这个比较:

if health == 1:

另外,这是错误的:

if numberboy == "8" or "9":

改用这个:

if numberboy == 8 or numberboy == 9:

希望对您有所帮助

我注意到的几件事:

  1. numberboy == randrange(7,9) 应该是 numberboy = randrange(7,9)
  2. 你永远不会用一个值来定义健康,你只是想从中减去它。那会抛出 NameError
  3. 您正在将整数与字符串进行比较。应该是 numerboy == 7 而不是 numberboy == '7'
numberboy == randrange(7,9)

是你的问题。只需将其替换为

numberboy = randrange(7,9)

randrange(x,y)会给你这种数字x <= nb < y 所以不可能是y

您需要对整数使用 random.randint(floor,ceil),并且 random.random(floor,ceil) 小数

所以一些注意事项:请参阅我在代码中的注释。 你需要申报健康,你有 numberboy 评估不等同。这两件事是您代码中最大的问题。我的建议是下载 pycharm 并学习如何更好地调试代码。有了更多的经验,这些错误就不会犯了。

from random import randrange
import time #this is unused


numberboy = randrange(7,9)  # you had this evaluating not declared
print numberboy
health = 10  #you did not declare health 
if numberboy == 7:  # numberboy is a int type no need for making it a string
    print ("You unluckily fall into a pit!")
    health -= 1
    if health == 1:
        print ("You drop to your knees and lie, filled with pain in the pit. You drop to the floor. Your quest is over.")
        print ("Your health has fallen to " + str(health) + ". ")

if numberboy == 8 or 9:
    print ("You could have fallen into a pit but you luckily didn't!")
    print ("You find a path leading of to another room.")

print ("You walk down the path and find a light illuminating an elvish sword!")
print ("You walk out of an escape path and find youself coming out of a secret entrance at the clearing.")