简体   繁体   中英

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)? I thought it only needed a min and a max?

randint accepts a min and a max, like this:

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

>>> 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. methods automatically get an argument passed to them (traditionally called "self") which is the instance itself. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM