Home > other >  How to add a conditional statement as an argument to a function in python?
How to add a conditional statement as an argument to a function in python?

Time:06-30

I have the following function:

def f(loop_condition, count):
    while loop_condition:
        count  = 1
        ...

This works with a simple True statement. But what in case I want to have my loop condition to be:

count < 3

Is there a way to achieve this?

CodePudding user response:

If I understand your question, this is the solution :

def f(count):
    loopCount=0
    while loopCount<count:
        loupCount  = 1
        ...

CodePudding user response:

You can pass the loop_condition as string and then eval():

def f(loop_condition, count):
    while eval(loop_condition):
        count  = 1
print(f('count < 3'))

Output:

3

CodePudding user response:

You can pass the condition as a string which you then evaluate within your function. For example:

def func(condition, count):
    while eval(condition):
        count  = 1
    return count

print(func('count < 3', 0))

Output:

3
  • Related