如果未设置变量,如何捕获错误?

2024-10-01 00:18:24 发布

您现在位置:Python中文网/ 问答频道 /正文

调用函数时,如何捕获因未设置模块变量而导致的错误

所以我有这个代码

file = "whatever the file path is"
menu= [] #this is a global variable

def ordermenu():
    with open(file) as f:  # read file
        reader = csv.reader(f, delimiter=",")
        next(reader, None) #skip the header

def showmenu():
    for i in range(len(menu)):
        print(menu)

ordermenu()
showmenu()

在这个函数中,我需要捕捉错误

注意:我不会使用这些全局变量作为参数


Tags: 模块thepath代码isdef错误this
1条回答
网友
1楼 · 发布于 2024-10-01 00:18:24

它被称为NameError,用于表示未定义的内容。只需用try-except像这样包装代码:

try:
    b = a+1
except NameError:
    print("a not defined")

相关问题 更多 >