0

How can catch the error caused by a module variable not being set when the function is called

so example i have this code

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()

In this function i need to catch the error.

NOTE: i won't be using those global variable as parameters.

9
  • Could you use try: except:? Commented May 29, 2020 at 3:42
  • What error are you looking for? It seems like ordermenu didn't add anything to menu so showmenu has nothing to do. You could just check if len(menu) == 0 in that function. Commented May 29, 2020 at 3:45
  • im just looking for errors where i could say 'Variables not set' if the variables aren't set Commented May 29, 2020 at 3:48
  • 1
    "variable not set" is vague. You don't have any undefined variables in your example. Commented May 29, 2020 at 3:48
  • 1
    Hi, could you explain what "variable not set" means? Commented May 29, 2020 at 3:49

1 Answer 1

2

It is called NameError for something not defined. Just wrap your code with try-except like this:

try:
    b = a+1
except NameError:
    print("a not defined")
Sign up to request clarification or add additional context in comments.

3 Comments

That program didn't have a name error. OP said "variables not set" which I think is too vague to answer at this point.
I think the NameError hits at the module csv is not loaded.
I took that to just being that OP didn't post a complete example. Maybe that's what the problem is though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.