[英]Error when making random errors in Python
import random import time loop = [1,2,3,4,5,6,7,8,9,10] queenstrength = 100 queendamagenum = 1,20 print "The queens health is currently: ",queenstrength while queenstrength > 0: queendamage = random.randint((queendamagenum)) print"" print "queen damage:", queendamage queenstrength = queenstrength - queendamage print queenstrength time.sleep(1) print"" print"finished"
I'm trying to use this code in a game I am making, but I keep getting the error: 我正在尝试在正在制作的游戏中使用此代码,但我不断收到错误消息:
**Traceback (most recent call last):
File "Untitled.py", line 9, in <module>
queendamage = random.randint((queendamagenum))
TypeError: randint() takes exactly 3 arguments (2 given)**
what does it mean 3 arguments (2 given)? 3个参数(给定2个)是什么意思? I thought it only needed a min and a max?
我以为只需要一个最小值和最大值?
randint accepts a min and a max, like this: randint接受最小值和最大值,如下所示:
>>> import random
>>> random.randint(0,10)
1
but you're passing a tuple: 但是您正在传递一个元组:
>>> random.randint((0, 10))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: randint() takes exactly 3 arguments (2 given)
You can use argument unpacking ( the * operator) to turn your tuple into a series of arguments for randint, if you like: 您可以使用参数拆包( *运算符)将元组变成randint的一系列参数,如果您喜欢:
>>> queendamagenum = 1, 20
>>> random.randint(*queendamagenum)
8
As for the fact that the error message says "3 arguments (2 given)", that's because randint is actually a method living in an instance of random.Random, and not a function. 至于错误消息说“ 3个参数(给定2个)”的事实,这是因为randint实际上是一个生活在random.Random实例中的方法,而不是一个函数。 methods automatically get an argument passed to them (traditionally called "self") which is the instance itself.
方法自动获取传递给它们的参数(传统上称为“ self”),该参数是实例本身。 So you should translate "3 arguments (2 given)" into "2 non-self arguments (1 given)", and you only passed it 1 tuple, so that make sense.
因此,您应该将“ 3个参数(给定2个)”转换为“ 2个非自身参数(给定1个)”,并且只将其传递给1个元组,这样才有意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.