如何捕获由于未设置模块变量而导致的任何错误?

时间:2020-05-28 04:31:48

标签: python-3.x

所以我有此功能列表和显示列表,但我需要捕捉由未设置的模块变量引起的任何错误。有人可以帮助我做我第一件事吗?

这是我目前的代码

import csv

filep  #filepath
menulist = []

def list():
    """Function to read the csv file, create a nested list 
    and return the list that is sorted based on calories 
    in the ascending order."""

    global menulist
    menulist = [] #store items
    with open(filep) as csv_file: #read file
        reader = csv.reader (csv_file, delimiter=',')
        next(reader, None)

        for row in reader:
            row[2] = int(row[2].strip())
            row[1] = float(row[1].strip())
            if row[2]> 100 and row[2] <200:
                menulist.append(row)

    menulist.sort(key=lambda x: x[-1])


def show_list():#Function to display menu
    global menulist
    for i in range(len(menulist)):
        print ('%-4d%-20s%-15s%-15s' %(i + 1, menulist[i][0], menulist[i][2], menulist[i][1]))

list()
show_list()

例如,如果在调用list()之前未设置变量文件,则该函数需要捕获错误并输出适当的注释

2 个答案:

答案 0 :(得分:1)

您正在使用内置函数名称作为函数名称。在Python中,这不是一个好习惯。它替代了用于创建列表的内置函数list()。并且需要先定义一个变量,然后才能使用它。

在这里,您可以使用定义的变量来捕获错误并打印适当的注释:

import csv

filep = str(input("Enter the file name with path : "))  # filepath
menulist = []


def calorieList():
    """Function to read the csv file, create a nested list
    and return the list that is sorted based on calories
    in the ascending order."""

    global menulist
    menulist = []  # store items
    with open(filep) as csv_file:  # read file
        reader = csv.reader(csv_file, delimiter=",")
        next(reader, None)

        for row in reader:
            row[2] = int(row[2].strip())
            row[1] = float(row[1].strip())
            if row[2] > 100 and row[2] < 200:
                menulist.append(row)

    menulist.sort(key=lambda x: x[-1])


def show_list():  # Function to display menu
    global menulist
    for i in range(len(menulist)):
        print("%-4d%-20s%-15s%-15s" % (i + 1, menulist[i][0], menulist[i][2], menulist[i][1]))


try:
    calorieList()
except FileNotFoundError:
    print("Enter a valid file path.")

show_list()

答案 1 :(得分:0)

我假设您用filep变量来表示file。 如果您尝试在设置之前访问filep,则程序应引发NameError: name 'filep' is not defined

但是,如果要引发自定义错误消息,则可以使用try-except块,如下所示:

import csv

filep  #filepath
menulist = []
def list():
    """Function to read the csv file, create a nested list
    and return the list that is sorted based on calories
    in the ascending order."""

    global menulist
    menulist = [] #store items
    try:
        with open(filep) as csv_file: #read file
            reader = csv.reader (csv_file, delimiter=',')
            next(reader, None)

            for row in reader:
                row[2] = int(row[2].strip())
                row[1] = float(row[1].strip())
                if row[2]> 100 and row[2] <200:
                    menulist.append(row)
    except NameError:
        raise ValueError("Your custom message here")

    menulist.sort(key=lambda x: x[-1])


def show_list():#Function to display menu
    global menulist
    for i in range(len(menulist)):
        print ('%-4d%-20s%-15s%-15s' %(i + 1, menulist[i][0], menulist[i][2], menulist[i][]))

list()
show_list()