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

Can I use random choice to choose between 2 functions

Hey guys I’m trying to create a function that randomly picks a number and then randomly adds or subtracts 1 from the chosen number but it seems that the random.choice function isn’t working the way it is supposed to do I’m getting output but it’s not the result of adding or subtracting (I visualized it on Thonny)
Here is my code

import random
def addsubone(x):
 result=0
 n= [1,2,3,4,5,6]
 x=random.choice(n)
 def adding(x):
   x=x+1
 def substracting(x):
   x=x-1
 random.choice([adding,substracting])
 return(x)
print(addsubone(0))

>Solution :

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

Functions are objects that can be assigned to variables like any other object. To randomly chose one, make a random choice from a list of functions. See below.

Your function ignores its argument x, I removed it entirely.

Recommendation: do not define constants in a function. Each time you call the functions they will be uselessly re-defined.

import random

NUMBERS = [1,2,3,4,5,6]

def adding(x):
    return x+1

def substracting(x):
    return x-1

FUNCTIONS = [adding, substracting]

def addsubone():
    n = random.choice(NUMBERS)
    f = random.choice(FUNCTIONS)
    return f(n)

print(addsubone())
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