Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use call the random function

I have a code which has functions, which should be called randomly. However, when I am running the code:

def print1():
    print(1)
def print2():
    print(2)
def print3():
    print(3)
l=(print1(), print2(), print3())
x=random.choice(l)
x()

it doesn’t work properly. It is outputting everything (1,2,3)
and gives an error:

”NoneType’ object is not callable’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How to fix that?

>Solution :

def print1():
    print(1)
def print2():
    print(2)
def print3():
    print(3)
l=(print1, print2, print3)
x=random.choice(l)
x()

placing the functions without the brackets place the function inside the list. Writing the function with the brackets calls the function.

Btw u need not store the function into a variable, just do random.choice(l)()

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading