Python入门问题:如何根据用户输入执行对应多个函数?
Hey there! Let's break down how to build this functionality step by step—perfect for Python beginners. Here's a straightforward approach that's easy to extend later on:
1. First, define your target functions
Start by writing the functions you want to trigger. For example:
def func1(): print("Executing Function 1!") def func2(): print("Executing Function 2!") def func3(): print("Executing Function 3!")
2. Create a function mapping dictionary
This is the key part—it links input characters to their corresponding functions. It makes your code clean and easy to update if you add more functions later:
function_map = { 'A': func1, 'B': func2, 'C': func3 }
3. Handle user input and execute functions
Now, get the user's input, process it, and run the matching functions. We'll also add basic error handling for invalid inputs:
# Get user input user_input = input("Enter function codes (e.g., 'A,B' or 'B,C'): ") # Split the input into individual codes, strip any extra spaces function_codes = [code.strip() for code in user_input.split(',')] # Loop through each code and execute the corresponding function for code in function_codes: if code in function_map: function_map[code]() # Call the function else: print(f"Warning: '{code}' is not a valid function code. Skipping.")
4. Test it out!
If you run this code and enter A,B, you'll see:
Executing Function 1! Executing Function 2!
If you enter B,X, you'll get:
Executing Function 2! Warning: 'X' is not a valid function code. Skipping.
Bonus: Extra enhancements for robustness
- Make input case-insensitive: convert the user's input to uppercase (or lowercase) before processing:
function_codes = [code.strip().upper() for code in user_input.split(',')] - Support different separators (like semicolons) by splitting on multiple delimiters—you can use
re.split()for that:import re function_codes = [code.strip().upper() for code in re.split(r'[;,]', user_input)] - Add a help message if the user enters something like
help:if user_input.strip().lower() == 'help': print("Valid function codes: A (func1), B (func2), C (func3)") else: # Process the codes as before ...
This approach keeps your code modular and easy to maintain—perfect as you grow your Python skills!
内容的提问来源于stack exchange,提问作者Michael

