Python - 为什么我的随机数生成器无法正常工作?

时间:2015-02-13 17:03:24

标签: python random

我已经尝试了多年如何让它发挥作用。它应该从随机导入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)

5 个答案:

答案 0 :(得分:3)

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

使用:

if numberboy == 7:

而不是:

if numberboy == "7":

与健康相同,请使用此比较:

if health == 1:

另外,这是错误的:

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

请改用:

if numberboy == 8 or numberboy == 9:

希望这有帮助

答案 1 :(得分:0)

我发现了一些事情:

  1. numberboy == randrange(7,9)应为numberboy = randrange(7,9)
  2. 您永远不会使用值定义运行状况,您只会尝试从中减去运算符。这将抛出NameError
  3. 您正在将整数与字符串进行比较。应该是numerboy == 7而不是numberboy == '7'

答案 2 :(得分:0)

numberboy == randrange(7,9)

是你的问题。只需用

替换它
numberboy = randrange(7,9)

randrange(x,y)会为您提供此类号码x <= nb < y,因此不能y

答案 3 :(得分:0)

你需要对整数使用random.randint(floor,ceil) random.random(floor,ceil)代表小数

答案 4 :(得分:0)

以下几点说明:请在代码中查看我的评论。 你需要声明健康,你有数字评估不等于。这两件事是你代码中最大的问题。我的建议是下载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.")