On 23/06/13 16:18, Jack Little wrote:
I am trying to use random.choice for a text based game. I am using windows 7, 
64-bit python. Here is my code:

def lvl2():
     print "COMMANDER: Who should you train with?"
     trn=random.choice(1,2)
[...]

Here is my error:

  File "C:\Users\Jack\Desktop\python\skye.py", line 20, in lvl2
     trn=random.choice(1,2)
TypeError: choice() takes exactly 2 arguments (3 given)


Alas, here you have stumbled over one of those corners of Python where things do not work 
*quite* as well as they ought to. Even though random.choice looks like a function, it is 
actually a method, and methods have an extra argument, automatically generated by Python, 
called "self".

So when you call random.choice(1, 2) Python provides three, not two, arguments:

self, 1, 2

hence the error message about "3 given". Since random.choice takes two 
arguments, and Python provides one of them, that only leaves one argument for you to 
provide. What should that be? Well, if you read the documentation, it tells you. At the 
interactive interpreter, you can enter

help(random.choice)


which will give you:

Help on method choice in module random:

choice(self, seq) method of random.Random instance
    Choose a random element from a non-empty sequence.


Ignoring "self", you have to give a *sequence* of values. A list is a good 
sequence to use:

# Incorrect:
random.choice(1, 2)


# Correct:
random.choice([1, 2])



--
Steven
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to