You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 09:07:56