【问题标题】:Using random library functions in my own functions python 3 [closed]在我自己的函数python 3中使用随机库函数[关闭]
【发布时间】:2014-10-10 14:16:16
【问题描述】:

为什么我不能在这个函数中使用 randrange?

import random

print (random.randrange(0,4))

def random(dice):
    dice_one = random.randrange(1,3)
    return (dice_one)


print (random(4))

这是错误

    line 6, in random
    dice_one = random.randrange(1,3)
    AttributeError: 'function' object has no attribute 'randrange'

感谢您的帮助

【问题讨论】:

  • 因为你已经用你自己的函数替换了模块random,也叫random - 为什么?
  • 我明白了,我没有意识到我会随机替换。我以为我会添加它。我明白我现在做错了什么。谢谢你

标签: python function random


【解决方案1】:

Python 认为您正在尝试调用您自己的随机函数的方法,因为您将其命名为与随机模块相同的名称。将您的函数名称更改为其他名称,应该没问题。

def chance(dice):
    dice_one = random.randrange(1,3)
    return dice_one

print (chance(4))

另外,不确定您要使用“骰子”参数做什么。如果这意味着骰子的面数,请尝试:

def chance(dice):
    dice_one = random.randrange(1,dice)
    return dice_one

【讨论】:

    【解决方案2】:

    有趣的是,实际上我无法理解您期望哪种输出,但是根据我所理解的程序的解决方案是这样的!

      import random
    
      print random.randrange(0,4)
    
      def random_number(dice):
          dice_one = random.randrange(1,3)
          return dice_one
    
      print random_number(4)
    

    【讨论】:

      猜你喜欢
      • 2012-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-10
      • 2010-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多