I'm relatively new to Python, but I have a lot of experience in languages like C++ and Java. I am trying to parse a string to a function with parameters. This is what I got so far:
def DimLights(percent = 1.0):
print 'Dimming lights to ' + "{:.2f}".format(percent * 100) + ' percent'
def TurnOffLights():
print 'Turning off lights'
function_mappings = {'DimLights': DimLights,
'TurnOffLights': TurnOffLights}
def select_function():
while True:
try:
return function_mappings[raw_input('Please input the function you want to use')]
except:
print 'Invalid function, try again.'
while True:
function = select_function()
function()
It's working as long as I don't use any parameters, but I can't think of a solution that would work with parameters. Is there any way I can accomplish this?
select_function()that would be in turn passed into the function you select?except:to catch all errors. You probably wantKeyErrorand some select others here. But you probably don't wantSyntaxErroret al.