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

martineau
  • 119,623
  • 25
  • 170
  • 301
  • Is there a `main` starting point ? – azro May 09 '20 at 15:49
  • 2
    `other_function(data_set)`…‽ – deceze May 09 '20 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. – Robin Zigmond May 09 '20 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. – Swetank Poddar May 09 '20 at 15:51
  • List is an **object**. Though it's reference is passed by value, the content can be shared between functions. – PM 77-1 May 09 '20 at 15:52
  • Sorry guys, new to using stack overflow also, the code snippet above is from a full python script that works, however my issue was of course that I couldn't figure out how to declare data_set local and call it to another function. However the answer below looks like it might solve my problem, going to attempt that and then let the results be known. – Alexander Kerr May 09 '20 at 15:54
  • about global variables in python: https://stackoverflow.com/questions/423379/using-global-variables-in-a-function – Andrea Baldini May 09 '20 at 15:57
  • Does this answer your question? [Calling a variable from one function to another function in Python](https://stackoverflow.com/questions/20768856/calling-a-variable-from-one-function-to-another-function-in-python) – wwii May 09 '20 at 15:57
  • [How can I store a result of a function in a variable in Python?](https://stackoverflow.com/questions/35423564/how-can-i-store-a-result-of-a-function-in-a-variable-in-python) is probably a better *duplicate*. – wwii May 09 '20 at 16:02

4 Answers4

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()
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
  • 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. – Alexander Kerr May 09 '20 at 16:29
  • 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)``` – Alexander Kerr May 15 '20 at 19:12
  • @AlexanderKerr Sorry, you will have to ask a new question on the site, it is too hard to debug in comments. – Joe Iddon May 15 '20 at 20:31
  • Will do, I had prev thought to, then deleted since I had this here. – Alexander Kerr May 15 '20 at 21:30
  • Posted new question and put full code up, question is @ https://stackoverflow.com/questions/61828948/undefined-error-when-passing-list-as-parameter-in-python , would appreciate your input on where I went wrong with it please? – Alexander Kerr May 15 '20 at 21:55
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")
Mace
  • 1,355
  • 8
  • 13
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"
Gerrit Geeraerts
  • 924
  • 1
  • 7
  • 14
  • 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. – Alexander Kerr May 15 '20 at 17:44
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

LevB
  • 925
  • 6
  • 10