Python-AttributeError:"int"对象没有属性"randint" [英] Python - AttributeError: 'int' object has no attribute 'randint'

查看:693
本文介绍了Python-AttributeError:"int"对象没有属性"randint"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为python课程的一部分,我正在执行的任务之一是生成1到10 100,000次之间的随机数,并计算每个数字出现多少次.这是我为此任务编写的代码:

As part of a python course I am doing one of the tasks is to generate a random number between 1 and 10 100,000 times and count how many times each number occurs. Here is the code I have written for this task:

    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说:

However I get an AttributeError saying:

    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(随机)一词,并且仍然不起作用,我花了比寻找健康无济于事的时间更长的时间.

I've tried changing the title so that it doesn't include the word random and it still doesn't work, I've spent much longer than is healthy looking for solution to no avail.

推荐答案

您已将变量之一命名为random,这正掩盖您要使用的模块的名称:

You have named one of your variables random, which is shadowing the name of the module you're trying to use:

random = random.randint(1, 10)

在此行之后,random是您的随机数,而不是random模块.为该变量使用其他名称!

After this line, random is your random number, not the random module. Use a different name for this variable!

这篇关于Python-AttributeError:"int"对象没有属性"randint"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆