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

Python3中如何根据用户多选输入按顺序调用多个函数

Hey there! Let's fix up your code to handle multiple function selections easily, no matter what delimiter the user uses. Here's a revised version that meets your needs, plus a breakdown of the key changes:

Modified Code

def askUser():
    while True:
        user_input = input("Do you want to run functions? Enter numbers separated by any delimiter (e.g., 1,3 or 2 4): \n")
        # Extract all numeric characters from the input
        choices = []
        for char in user_input:
            if char.isdigit():
                choices.append(int(char))
        
        # Filter out invalid numbers (only keep 1-4)
        valid_choices = [c for c in choices if 0 < c < 5]
        
        if not valid_choices:
            print("Please enter at least one valid number between 1 and 4! Try again.")
            continue
        
        # Notify user about any invalid entries we're ignoring
        invalid_choices = [c for c in choices if c not in range(1, 5)]
        if invalid_choices:
            print(f"Note: Numbers {invalid_choices} are invalid and will be ignored.")
        
        print(f"You entered valid choices: {valid_choices}")
        return valid_choices

def f1():
    print("f1 was called")
def f2():
    print("f2 was called")
def f3():
    print("f3 was called")
def f4():
    print("f4 was called")

# Map numbers to their corresponding functions
mydict = {1: f1, 2: f2, 3: f3, 4: f4}

# Get valid user choices and execute functions in order
selected_choices = askUser()
for choice in selected_choices:
    mydict[choice]()

Key Changes Explained

  • Flexible Input Handling: Instead of forcing a specific delimiter, we extract all numeric characters from the user's input. This works with commas, spaces, semicolons, or even mixed delimiters (like 1 3,2).
  • Validation & Feedback: We filter out any numbers outside the 1-4 range and let the user know which entries were invalid. If no valid numbers are entered, we prompt them to try again.
  • Sequential Execution: We return a list of valid choices from askUser(), then loop through that list to call each function in the order the user entered them.
  • Fixed Original Bug: Your original code tried to call mydict[choice]() before askUser() ran, which would throw an error because choice wasn't defined. We've reordered this to get the choices first, then execute the functions.

内容的提问来源于stack exchange,提问作者Rahul

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:57:47