python的randint没有定义,Python-AttributeError:“ int”对象没有属性“ randint”

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")

However I get an AttributeError saying:

Traceback (most recent call last):

File "J:/Python/Extension Task - Random Numbers.py", line 19, in

random = random.randint(1, 10)

AttributeError: 'int' object has no attribute 'randint'

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.

解决方案

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)

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值