首页 > 解决方案 > 尝试使用 try / except 函数更改多个变量

问题描述

def tryexcept(variable,range1,range2):
    while variable not in range(range1,range2):
        try:
            if variable not in range(range1,range2):
                variable = int(input("Enter your decision \033[95m(1)\033[0m or \033[95m(2)\033[0m"))
                # Making the options stand out with \033[95m for error prevention, plus it looks nice
        except:
            print("Not valid please enter an intiger \033[95m(1 or 2)\033[0m")

menu_option = 0

tryexcept(menu_option,1,3)

我尝试了全局变量并更改了变量的定义顺序

标签: pythonexceptionwhile-loopglobal-variablestry-catch

解决方案


这是你想要的吗?

def tryexcept(variable,range1,range2):
    while variable not in range(range1,range2):
        try:
            if variable not in range(range1,range2):
                variable = int(input("Enter your decision \033[95m(1)\033[0m or \033[95m(2)\033[0m"))
            # Making the options stand out with \033[95m for error prevention, plus it looks nice
        except:
            print("Not valid please enter an intiger \033[95m(1 or 2)\033[0m")
# Returns the variable once the loop is finished
    return variable


menu_option = 0

# Sets menu_option to the return value
menu_option = tryexcept(menu_option,1,3)

推荐阅读