[Tutor] random.choice() problem
Peter Otten
__peter__ at web.de
Sun Jun 23 13:19:11 CEST 2013
Dave Angel wrote:
> On 06/23/2013 02:18 AM, 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)
>> if trn==1:
>> lvl2_1()
>> print "Squad One!"
>> elif trn==2:
>> lvl2_2()
>> print "Squad Nine!"
>> 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)
> Steven's answer is correct, but here's another option:
>
> trn = random.randint(1,2)
>
> Here, the 1 and 2 are separate arguments delimiting a range of integer
> values. Note that it includes both end points, unlike the xrange
> function.
Here's yet another option: if you move the print statements into the
lvl2_...() functions you can simplify your code by choosing the function
directly:
>>> import random
>>> def level2_1():
... # ...
... print "Squad One!"
...
>>> def level2_2():
... # ...
... print "Squad Nine!"
...
>>> def level2():
... print "COMMANDER: Who should you train with?"
... level2_x = random.choice([level2_1, level2_2])
... level2_x()
...
>>> level2()
COMMANDER: Who should you train with?
Squad One!
>>> level2()
COMMANDER: Who should you train with?
Squad Nine!
>>> level2()
COMMANDER: Who should you train with?
Squad Nine!
More information about the Tutor
mailing list