0

I am writing a program and keep on getting trouble with the error:

   File "C:/Users//Documents///", line 47, in                      <module>
print(operations(sorted_list_desc))
NameError: name 'sorted_list_desc' is not defined

Even though you can not see the file I am working with, I have provided my code. I am supposed to loop the years and randomly choose an operator for each of the years. However, I keep on getting the error above. Any ideas why I keep on getting it?

import csv

#List to store different operators
list_operators = ["+","-","*","/"]


#Function to read file of list
def read_file():

#List to store data
    sorted_list_desc = []

 year = csv_file.readline()
    population = csv_file.readline()


    return sorted_list_desc

     print(read_file())

def operations(sorted_list_desc):
    for i in range(len(sorted_list_desc)):
        operator = random.choice(list_operator)
    return operator
print(operations(sorted_list_desc))
##        
Mike Müller
  • 82,630
  • 20
  • 166
  • 161

3 Answers3

1

sorted_list_desc is generated by read_file(). Change your last line to:

print(operations(read_file()))

The line:

print(read_file())

does not magically created a global object withe name sorted_list_desc. You need to hand it over explicitly to operations().

Alternatively, you could write:

sorted_list_desc = read_file()
print(operations(sorted_list_desc))
Mike Müller
  • 82,630
  • 20
  • 166
  • 161
1

You have only assigned sorted_list_desc inside your function read_file(). Thus, your error is telling you that sorted_list_desc is not assigned to anything outside your function's scope. See Python scoping rules, and notice that you don't even need to pass sorted_list_desc as a parameter because it is assigned inside your function anyways.

Community
  • 1
  • 1
miradulo
  • 28,857
  • 6
  • 80
  • 93
0

Looks like sorted_list_desc is defined within the scope of your read_file() function and thus you can't reference it outside of that function. You can call print(operations(sorted_list_desc)) within 'read_file()', or you can define sorted_list_desc = [] at a global scope.

mtage70
  • 21
  • 3