Home > database >  How do I assign a variable in a function, and then use that variable later?
How do I assign a variable in a function, and then use that variable later?

Time:07-27

I'm coding a discord bot to send data from a CSV file, and using functions as I'm new to them. I'm trying to store data from the csv into a variable and then sending it off to Discord. However I get this error every time I try to run it:

NameError: name 'row2' is not defined

Code:

def fileDeleteion(fileName):
    if os.path.exists(fileName):
        os.remove(fileName)
    else:
        print("The file does not exist")
        
def userIdThing(id):
    print("ID THING")
    with open('data.csv', 'r') as dataFile:
        print("CSV OPEN")
        dataFileReader = csv.reader(dataFile)
        for row in dataFileReader:
            if row[0] == id:
                row2 = int(row[1])
                row4 = int(row[4])
                print(row2, " ", row4)
                #return [row2, row4]
                dataFile.close
                return row2, row4

#global row2
#global row4
@client.event
async def on_message(message):
    if message.content == "!graph":
        fileDeleteion("test.png")
        fileDeleteion("id.csv")
        #userID2 = (message.author.id)
        userIdThing(int(message.author.id))
        time.sleep(3)
        #print(userID2)
        #print(row2, " row2 ", row4, " row4")
        plt.plot([0, row2, row4])
        plt.ylabel('Follower Increase')
        plt.xlabel("days")
        #plt.show()
        await message.channel.send(file=discord.File("test.png"))
        fileDeleteion("test.png")
        fileDeleteion("id.csv")

This is what the CSV file looks like:

User, followers, account, thedate, followerUpdate
399287308274106370,334,mallardofglory,2022-07-23,4
649023485229662240,1263,HotRedGamer87,2022-07-23,1
798674024250081300,276,Stormy21ish,2022-07-23,300

CodePudding user response:

If you return something in a function you need to assign the return value to a variable to use it. This code should work:

   def fileDeleteion(fileName):
    if os.path.exists(fileName):
        os.remove(fileName)
    else:
        print("The file does not exist")

def userIdThing(id):
    print("ID THING")
    with open('data.csv', 'r') as dataFile:
        print("CSV OPEN")
        dataFileReader = csv.reader(dataFile)
        for row in dataFileReader:
            if row[0] == id:
                row2 = int(row[1])
                row4 = int(row[4])
                print(row2, " ", row4)
                #return [row2, row4]
                dataFile.close
                return row2, row4

#global row2
#global row4
@client.event
async def on_message(message):
    if message.content == "!graph":
        fileDeleteion("test.png")
        fileDeleteion("id.csv")
        #userID2 = (message.author.id)
        row2, row4 = userIdThing(int(message.author.id)) #assigning returned values to variables
        time.sleep(3)
        #print(userID2)
        #print(row2, " row2 ", row4, " row4")
        plt.plot([0, row2, row4])
        plt.ylabel('Follower Increase')
        plt.xlabel("days")
        #plt.show()
        await message.channel.send(file=discord.File("test.png"))
        fileDeleteion("test.png")
        fileDeleteion("id.csv")

CodePudding user response:

To access variables returned in functions, you must set that variable equal to that function outside of the function. For you code it would be:

def fileDeleteion(fileName):
    if os.path.exists(fileName):
        os.remove(fileName)
    else:
        print("The file does not exist")
def userIdThing(id):
    print("ID THING")
    with open('data.csv', 'r') as dataFile:
        print("CSV OPEN")
        dataFileReader = csv.reader(dataFile)
        for row in dataFileReader:
            if row[0] == id:
                row2 = int(row[1])
                row4 = int(row[4])
                print(row2, " ", row4)
                #return [row2, row4]
                dataFile.close
                return row2, row4

#global row2
#global row4
@client.event
async def on_message(message):
    if message.content == "!graph":
        fileDeleteion("test.png")
        fileDeleteion("id.csv")
        #userID2 = (message.author.id)
        row2, row4 = userIdThing(int(message.author.id))
        time.sleep(3)
        #print(userID2)
        #print(row2, " row2 ", row4, " row4")
        plt.plot([0, row2, row4])
        plt.ylabel('Follower Increase')
        plt.xlabel("days")
        #plt.show()
        await message.channel.send(file=discord.File("test.png"))
        fileDeleteion("test.png")
        fileDeleteion("id.csv")

~~EDIT~~

For OP's comments on my answer, I'm adding an edit that shows how to return a list of int values from OP's for loop:

def userIdThing(id):
    print("ID THING")
    with open('data.csv', 'r') as dataFile:
        print("CSV OPEN")
        dataFileReader = csv.reader(dataFile)
        row2List, row4List = [], []
        for row in dataFileReader:
            if row[0] == id:
                row2 = int(row[1])
                row4 = int(row[4])
                print(row2, " ", row4)
                #return [row2, row4]
                dataFile.close
                row2List.append(row2)
                row4List.append(row4)
        return row2List, row4List
        
row2List, row4List = userIdThing(int(message.author.id))
  • Related