I am experimenting with how to condense if statements within my code. I have a project I am working on that has several "if" statements (too many to keep track of) and want to figure out a way to condense them. Obviously this involves a for loop, but I am having trouble adding additional operations within this loop.
I came up with the following working example to demonstrate my issue:
num=6
if_options = [num==5, num==6]
for i in range(len(if_options)):
if if_options[i]:
print(num)
I want to add an additional piece to the code. This additional piece will execute an operation within the if statement. See following non-working example as a framework for what I am trying to accomplish:
num=6
if_options = [num==5, num==6]
operations = [num=num 1, num=num-1]
for i in range(len(if_options)):
if if_options[i]:
operations[i]
print(num)
For whatever reason, it will not execute the operation portion of the code and fails with a syntax error. It does not let me declare the command "num=num 1" (without quotes) within a list, however this declaration is necessary for executing the command. I feel like I am missing one little thing and it should be an easy fix. Thank you in advance!!
CodePudding user response:
The problem here is that the operations are evaluated when you create the list of them. You want to write them as strings, and then eval
/exec
them in the loop. I will assume you also want the conditions evaluated in the loop.
num = 6
if_options = ['num==5', 'num==6']
operations = ['num=num 1', 'num=num-1']
for i in range(len(if_options)):
if eval(if_options[i]):
exec(operations[i])
print(num)
CodePudding user response:
why not functions?
def check(inp):
#you can do some logic and type checking here
return type(inp)==int # for example, or return arguments to pass to the operatiins
def operation(inp2):
if inp2: # check if true or not empty, as an example
#do some operations
# and then you do something like
for x in input_of_things:
operation( check( x ) )
CodePudding user response:
You could use lambda expressions too.
num = 6
if_option_checks = [lambda x: x == 5, lambda x: x == 6]
operations = [lambda x: x 1, lambda x: x - 1]
for check, operation in zip(if_option_checks, operations):
if check(num):
num = operation(num)
Or you could use dictionaries and lambda expressions
num = 6
if_option_checks = {"add": lambda x: x == 5, "sub": lambda x: x == 6}
operations = {"add": lambda x: x 1, "sub": lambda x: x - 1}
for key, check in if_option_checks.items():
if check(num):
num = operations[key](num)