【问题标题】:Python - AttributeError: 'int' object has no attribute 'randint'Python - AttributeError:'int'对象没有属性'randint'
【发布时间】:2013-06-13 18:13:32
【问题描述】:

作为 Python 课程的一部分,我正在做的一项任务是生成一个介于 1 到 10 100,000 次之间的随机数,并计算每个数字出现的次数。这是我为此任务编写的代码:

    import random

    one = 0
    two = 0
    three = 0
    four = 0
    five = 0
    six = 0
    seven = 0
    eight = 0
    nine = 0
    ten = 0
    count = 0

    while count < 100000:
        random = random.randint(1, 10)

        if random == 1:
            one += 1
        elif random == 2:
            two += 1
        elif random == 3:
            three += 1
        elif random == 4:
            four += 1
        elif random == 5:
            five += 1
        elif random == 6:
            six += 1
        elif random == 7:
            seven += 1
        elif random == 8:
            eight += 1
        elif random == 9:
            nine += 1
        else:
            ten += 1

    count += 1

    print("1 occured " + str(one) + " times")
    print("2 occured " + str(two) + " times")
    print("3 occured " + str(three) + " times")
    print("4 occured " + str(four) + " times")
    print("5 occured " + str(five) + " times")
    print("6 occured " + str(six) + " times")
    print("7 occured " + str(seven) + " times")
    print("8 occured " + str(eight) + " times")
    print("9 occured " + str(nine) + " times")
    print("10 occured " + str(ten) + " times")

但是我得到一个 AttributeError 说:

    Traceback (most recent call last):
      File "J:/Python/Extension Task - Random Numbers.py", line 19, in <module>
        random = random.randint(1, 10)
    AttributeError: 'int' object has no attribute 'randint'

我已尝试更改标题,使其不包含随机一词,但它仍然不起作用,我花了比健康更长的时间寻找解决方案无济于事。

【问题讨论】:

    标签: random python-3.x attributeerror


    【解决方案1】:

    您已将其中一个变量命名为 random,它隐藏了您尝试使用的模块的名称:

    random = random.randint(1, 10)
    

    在这一行之后,random 是您的随机数,而不是 random 模块。为该变量使用不同的名称!

    【讨论】:

    • 谢谢你,我刚刚意识到这一点,并为我的无知和愚蠢道歉:P
    • 由于调用了我的文件 random.py,我遇到了同样的错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-31
    • 2021-11-30
    • 2020-03-26
    • 2013-04-15
    • 2021-01-18
    • 2019-05-30
    相关资源
    最近更新 更多