Can I use random choice to choose between 2 functions

Question:

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))
Asked By: Sskatx

||

Answers:

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())
Answered By: VPfB
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.