Example:
def calculator(operator, x, y):
if operator == 'add':
return x + y
elif operator == 'sub':
return x - y
elif operator == 'mul':
return x * y
elif operator == 'div':
return x / y
else:
return None
print(calculator('add',2,3))
print(calculator('div',6,2))
print(calculator('mod',4,2))
Output:
5
3.0
None
Example: by using dict
def calculator(operator, x, y):
return {
'add': lambda: x + y,
'sub': lambda: x - y,
'mul': lambda: x * y,
'div': lambda: x / y,
}.get(operator, lambda: None)()
print(calculator('add',2,3))
print(calculator('div',6,2))
print(calculator('mod',4,2))
Output:
5
3.0
None
def calculator(operator, x, y):
if operator == 'add':
return x + y
elif operator == 'sub':
return x - y
elif operator == 'mul':
return x * y
elif operator == 'div':
return x / y
else:
return None
print(calculator('add',2,3))
print(calculator('div',6,2))
print(calculator('mod',4,2))
Output:
5
3.0
None
Example: by using dict
def calculator(operator, x, y):
return {
'add': lambda: x + y,
'sub': lambda: x - y,
'mul': lambda: x * y,
'div': lambda: x / y,
}.get(operator, lambda: None)()
print(calculator('add',2,3))
print(calculator('div',6,2))
print(calculator('mod',4,2))
Output:
5
3.0
None
No comments:
Post a Comment