Using User Input to Call Functions - Python
Last Updated :
16 Dec, 2024
Improve
input()
function allows dynamic interaction with the program. This input can then be used to call specific functions based on the user's choice .
Let’s take a simple example to call function based on user's input .
Example:
def add(x, y):
return x + y # Add
def sub(x, y):
return x - y # Subtract
a = input() # Input
if a == "add":
res = add(5, 3)
elif a == "sub":
res = sub(5, 3)
else:
res = "Invalid operation" # Error
print("Result:", res)
Explanation:
This code
t
akes user input to determine the desired operation .- Based on the input, the corresponding function is called.
- It outputs the result of the operation or an error message if the input is invalid.
Using Dictionary for Function Mapping
Instead of using if statements, we can use a dictionary to map user inputs to function calls.
def multiply(x, y):
return x * y # Multiply
def divide(x, y):
return x / y # Divide
fun = {
"mul": multiply,
"div": divide
}
a = input() # Input
if a in fun:
result = fun[a](6, 3) # Call
else:
result = "Invalid operation" # Error
print("Result:", result) # Output
Explanation:
- This
code
perform respective operations. - Maps input to functions.
- It calls the function based on input .