简体   繁体   中英

Global variable undefined at the module level

I have this program that works it reads in a simple csv file, filters a column in that file for colours. Then writes out a csv file for each of the different colours seprately. Then plots a graph comparing columns for each of the filtered output files. But it still runs with some errors

I posted this question previously but still having problems. If anyone could help with my bad code! My questions are

I dont understand why I am getting 'named col_number variable undefined'(line 58) when I have had to define it twice. I know this is bad code but if somebody could help me with this.

Also, I am trying to pass the user_input(in this case apples, pears or oranges to be a y-axis title when the program runs. I have tried including in after col_number in the return statement and changing the data tag in plt.title('Data v Time') to plt.title(user_input + 'v Time') but the message unresolved reference.

Grateful for any help, my code is below

from matplotlib import style
from matplotlib import pyplot as plt
import numpy as np
import csv
# import random used for changing line colors in chart
import random
from itertools import cycle

# opens a the input file and reads in the data
with open('Test_colours_in.csv', 'r') as csv_file:
    csv_reader = csv.DictReader(csv_file)
# prints list of unique values in column 5 of csv of input file
    my_list = set()
    for line in csv_reader:
        my_list.add(line['Name5'])
    print(my_list)

# takes these unique values and creates files associated with each unique value
    for item in my_list:
        with open(item + '_'+'Test.csv', 'w', newline='') as new_file:
            fieldnames = ['Name1', 'Name2', 'Name3', 'Name4', 'Name5', 'Name6', 'Name7', 'Name8']
            csv_writer = csv.DictWriter(new_file, fieldnames=fieldnames)
            csv_writer.writeheader()

# filters the original file for each item in the list of unique values and writes them to respective file
            csv_file.seek(0)  # Reposition to front of file
            filtered = filter(lambda r: r['Name5'] == item, csv_reader)
            for row in filtered:
                csv_writer.writerow(row)

# Section of code below plots data from each of the filtered files

#
    my_color_list = ['b', 'g', 'r', 'c', 'm', 'y', 'tab:blue', 'tab:orange', 'tab:purple', 'tab:gray', 'b', 'g', 'r',
                     'c', 'm', 'y', 'tab:blue', 'tab:orange', 'tab:purple', 'tab:gray']

# ###################################################################
# ## trying to get this to do the same as the current input commands
    #global col_number
    def get_input(prompt):
        global col_number
        while True:
            user_input = input(prompt).lower()
            if user_input in ('apples', 'pears', 'oranges', 'quit'):
    # the user = int(0),int(1), int(2) values just assign a different column numnber
                if user_input == 'apples':
                    col_number = int(0)
                if user_input == 'pears':
                    col_number = int(1)
                if user_input == 'oranges':
                    col_number = int(2)
                return col_number,
print(get_input('Enter apples, pears, oranges or q to quit'))
# ######end of input#########################################################################col_number = get_input(prompt)

for item in my_list:

    x, y = np.loadtxt(item + '_'+'Test.csv', skiprows=1, usecols=[0, col_number], unpack=True, delimiter=',')
    color = random.choice(my_color_list)
    plt.plot(x, y, color, label=item, linewidth=5)

    style.use('ggplot')

plt.title('Data v Time')
plt.ylabel('Data')
plt.xlabel('Time seconds')

plt.legend()
plt.grid(True, color='k')
plt.show()

data file below

Name1,Name2,Name3,Name4,Name5,Name6,Name7,Name8 1,10,19,4,Blue,6,7,8 2,11,20,4,Blue,6,7,8 3,12,21,4,Blue,6,7,8 4,13,22,4,Green,6,7,8 5,14,23,4,Green,6,7,8 6,15,24,4,Blue,6,7,8 7,16,25,4,Blue,6,7,8 8,17,26,4,Yellow,6,7,8 9,18,27,4,Yellow,6,7,8

To address your specific concern, col_number doesn't need to be a global. Look at what you're doing:

def get_input(prompt):
    global col_number
                col_number = ...
            return col_number,

You don't use the (unset) value of col_number at all, you just set it. And after setting it, you return the same value!

So forget having a global variable. Just assign col_number to the result of your function:

def get_input(...):
    result = ...
    return result

# elsewhere in your code:
col_number = get_input(...)
... use col_number ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM