0

I am quite new to python and currently trying to work on a project that asks the user to read data from a csv file, and to store that data so that other functions can be performed on it. The only issue I seem to be having at the moment is that I can't use global variables.

Just now I have the following code structure:

import csv
import sys
data_set = []

def loadFile(x):
    with open(x, "r") as readfile:
        csv_reader = csv.reader(readfile, delimiter= ';')
        for row in csv_reader:
            data_set.append(row)
    print("Loaded weather data from", (x[0:-4]).capitalize())
    print()

def avgDay(x):
    for line in data_set:
        if(len(x) == 5 and (x[3:5] + "-" + x[0:2]) in line[0]):
           print("The weather on", x, "was on average", line[2], "centigrade")

Is there some way I can call data_set to other functions? (I have a few more functions that need to work with the data).

9
  • Is there a main starting point ? Commented May 9, 2020 at 15:49
  • 2
    other_function(data_set)…‽ Commented May 9, 2020 at 15:49
  • Just use function arguments and return values. loadFile can return the data in a list, and avgDay could take that data as an argument. Commented May 9, 2020 at 15:50
  • What do you mean by can't use global variables? Does it throw an error when you try to use it? Also, you could always encapsulate the functions and data into a class... that way you can use self to get the data. Commented May 9, 2020 at 15:51
  • List is an object. Though it's reference is passed by value, the content can be shared between functions. Commented May 9, 2020 at 15:52

4 Answers 4

4

Yes, simply pass it in as a parameter, and return it when it is originally generated.

import csv
import sys

def loadFile(x):
    date_set = []
    with open(x, "r") as readfile:
        csv_reader = csv.reader(readfile, delimiter= ';')
        for row in csv_reader:
            data_set.append(row)
    print("Loaded weather data from", (x[0:-4]).capitalize())
    print()
    return data_set

def avgDay(x, data_set):
    for line in data_set:
        if(len(x) == 5 and (x[3:5] + "-" + x[0:2]) in line[0]):
           print("The weather on", x, "was on average", line[2], "centigrade")

def main():
    data_set = loadFile(...)
    avgDay(..., data_set)

if __name__ == 'main':
    main()
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you, lecturer was just saying no using global variables and pointed me to a very basic tutorial on parameters but couldn't figure out how that would work in my code without the above example.
Ok looks like I spoke too soon, I am getting a data_set not defined error when using this method, but that's because I am not using a main, I am using the following format for returning my functions. def menu_number(): number = int(input("Choose what to do: ")) if (number) == 1: x = input("Give name of the file: " ) loadFile(x) print_menu() menu_number() elif (number) == 2: x = input("Give a date (dd.mm): ") avgDay(x, data_set) lowHigh(x, data_set) rain(x, data_set)
@AlexanderKerr Sorry, you will have to ask a new question on the site, it is too hard to debug in comments.
Will do, I had prev thought to, then deleted since I had this here.
Posted new question and put full code up, question is @ stackoverflow.com/questions/61828948/… , would appreciate your input on where I went wrong with it please?
1

Your loadFile function can return a dataset that can be used inside avgDay

import csv
import sys


def loadFile(x):

    data_set = []

    with open(x, "r") as readfile:
        csv_reader = csv.reader(readfile, delimiter= ';')
        for row in csv_reader:
            data_set.append(row)
    print("Loaded weather data from", (x[0:-4]).capitalize())
    print()

    return data_set

def avgDay(x):

    data_set = loadFile(x)

    for line in data_set:
        if(len(x) == 5 and (x[3:5] + "-" + x[0:2]) in line[0]):
           print("The weather on", x, "was on average", line[2], "centigrade")

Comments

0

global vars can only be set if u use the word global

you can access global vars without anything special

data_set = "global_var" #global

def print_global_data_set():
    print(data_set)

def set_global_data_set():
    global data_set # you need this line to tell python that you are going to set a global variable
    data_set = 'global_var_set_from_function'

def set_local_data_set():
    data_set = "local" # this will not set the global var but a local var so the global data_set stays unchanged

print(data_set) # outputs "global_var"
set_local_data_set()
print_global_data_set() # outputs "global_var" (set_local_data_set did not set the global var but a local var)
set_global_data_set()
print_global_data_set() # outputs "global_var_set_from_function"

1 Comment

That statement isn't quite true though is it? If I define a variable outside the scope of a function, that variable is automatically assigned a global status.
0

Functions can have attributes. You can make data_set an attribute of loadFile and then reference it in avgDay.

with open(x, "r") as readfile:

    csv_reader = csv.reader(readfile, delimiter= ';')

    for row in csv_reader:

        data_set.append(row)

    loadFile.data_set_attr = data_set

Then, in avgDay, reference loadFile.data_set_attr

1 Comment

But why 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.