Home > Enterprise >  using random to choose a function to run (50/50 chance needed)
using random to choose a function to run (50/50 chance needed)

Time:07-19

code being run(apart from modules and functions)

random.choice(frontright(),frontleft())

error raised:

TypeError: Random.choice() takes 2 positional arguments but 3 were given 

CodePudding user response:

random.choice expects a sequence to choose from. That's not what you passed it.

Functions are objects, so you can put them in a sequence and then choose from that. But if you use parens you aren't using the function itself; you are actually calling all of the functions, then passing their return values to random.choice

This code might demonstrate the difference.

import random

def frontright():
    print ('frontright was called')
    return 'frontright result'

def frontleft():
    print ('frontleft was called')
    return 'frontleft result'

my_functions = (frontright, frontleft)
fn = random.choice(my_functions)
print('calling one function')
fn()

print()
print('collection of results')
my_choice = random.choice((frontright(), frontleft()))
print('chosen result was:', my_choice)

You're actually passing 2 when it expects 1 sequence, but internally it is calling an instance method, and at that point it's really 3 instead of 2, if you include self.

CodePudding user response:

You might need to do this random.choice([frontright(), frontleft()])

https://www.w3schools.com/python/ref_random_choice.asp

  • Related