【问题标题】:Why adding try except block in if statement and the program says variable not defined为什么在 if 语句中添加 try except 块并且程序说变量未定义
【发布时间】:2021-04-20 12:11:58
【问题描述】:

我想写一个关于工具的程序,它有三个选择——计算器、随机数选择器和日历。但是,当我尝试对无效的用户输入使用 try-except 时,if 语句中的变量被称为未定义。代码如下:

        if user_input == 0:
        try:
            small_option = int(
            input("Which operation do you want to do? \n 1. Adding \n 2. Subtracting \n 3. Multiplying "
                  "\n 4. Dividing"))
            small_list = [0, 1, 2, 3]
            user_option = small_list[small_option]
        except IndexError:
            print("Invalid option")

那么if语句中的下一个变量是未定义的,如下几行:

                if user_option == 0:
                num1 = float(input("Enter first number: "))
                num2 = float(input("Enter second number: "))

当我运行它时,程序显示Traceback (most recent call last): File "C:/Users/31459/PycharmProjects/Useful programs/Tools.py", line 41, in <module> if user_option == 0: NameError: name 'user_option' is not defined

import calendar
import random




def adding(para1, para2):
    return para1 + para2



def substract(para1, para2):
    return para1 - para2



def multiplying(para1, para2):
    return para1 * para2



def dividing(para1, para2):
    return para1 / para2


while True:
    try:
        big_option = input("Which tool will you use? \n 0. Calculator \n 1. Calender \n 2. Random number generator")
        big_list = [0, 1, 2]
        big_option_int = int(big_option)
        user_input = big_list[big_option_int]
        if user_input == 0:
            try:
                small_option = int(
                input("Which operation do you want to do? \n 1. Adding \n 2. Subtracting \n 3. Multiplying "
                      "\n 4. Dividing"))
                small_list = [0, 1, 2, 3]
                user_option = small_list[small_option]
            except IndexError:
                print("Invalid option")
                if user_option == 0:
                    num1 = float(input("Enter first number: "))
                    num2 = float(input("Enter second number: "))
                if user_option == 1:
                    print("The sum is", num1, "+", num2, adding(num1, num2))
                elif user_option == 2:
                    print("The subtraction is", num1, "-", num2, substract(num1, num2))
                elif user_option == 3:
                    print("The multiplying is", num1, "*", num2, multiplying(num1, num2))
                else:
                    print("The divide is", num1, "/", num2, dividing(num1, num2))
                    break
            if user_option == 1:
                user_year_str = input("Please input the year you want to get.")
                user_month_str = input("Please input the month you want to get.")
                user_year = int(user_year_str)
                user_month = int(user_month_str)
                calendar.month(user_year, user_month)
            else:
                random_input_1 = input("Please input the 1st number:")
                random_input_2 = input("Please input the 2nd number:")
                random_input_1_int = int(random_input_1)
                random_input_2_int = int(random_input_2)
                random.randint(random_input_1_int, random_input_2_int)
    except IndexError:
        print("Invalid option")

【问题讨论】:

  • 请提供minimal reproducible example 并按照您的编辑器中显示的格式设置代码。缩进在 Python 中非常重要,当前的代码会给出一个 IndentationError,很难猜出你的代码实际上是什么样子。因此,请帮助我们通过发布能够重现您的问题的最少、完整的代码来帮助您。

标签: python error-handling


【解决方案1】:

需要定义用户选项

您确定在使用条件语句之前定义了变量吗?

在使用条件语句之前需要有一个值

【讨论】:

    【解决方案2】:

    这可能是因为 try 块引发错误并且它无法初始化变量user_option。因此,它会引发错误。

    尝试添加这个作为替代

    user_option = small_option -1
    

    【讨论】:

      【解决方案3】:

      python 中的每个对象(这里:变量)都有一个范围,并且在该范围内是可识别的。在它的范围之外它是无法识别的。

      user_option 变量的作用域是其中定义了 user_option 的 try 块。 如果你想在 try 块之外使用 user_option,你应该在更大的范围内定义它(意味着在它定义的 try 块之外)。

      【讨论】:

        【解决方案4】:

        您通过直接索引访问列表使选项 4 无效。

        索引从 0 开始,因此选项 4 不存在,即索引错误。 1-3 不会引发错误,因为 user_option 是毫无例外地定义的。但是您在small_list 中的“0”选项将永远不会被使用。

        只需在 try/catch 之前初始化变量 user_option 即可修复 UnboundLocalError。但不是你的逻辑缺陷。您可以将给定的选项值减一以将其转换为 0 起始索引,因为您已经定义了 small_list 变量

        small_list[small_option-1] 会在你写 1 时检索 0,在你写 4 时检索 3,所有这些都是 small_list 的定义索引。

        user_option = None        # by defining the variable first, we avoid the UnboundLocalError
        try:
            small_option = int(
            input("Which operation do you want to do? \n 1. Adding \n 2. Subtracting \n 3. Multiplying "
                    "\n 4. Dividing"))
            small_list = [0, 1, 2, 3]
            user_option = small_list[small_option-1]        # 1. Adding = small_list[0], 2. Subtracting = small_list[1], etc..
        except IndexError:
            print("Invalid option")
        if user_option == 0:
            num1 = float(input("Enter first number: "))
            num2 = float(input("Enter second number: "))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-09-17
          • 1970-01-01
          • 2013-10-25
          • 2023-02-10
          • 1970-01-01
          • 2020-08-31
          • 2017-03-21
          • 1970-01-01
          相关资源
          最近更新 更多