edit local variable out of function

Asked

Viewed 72 times

-1

Hello! How do I change a local variable from a function by external commands to the function? Example:

Create the function

def totalValue(type):
    try:
        valor = float(texto[0])
    except:
         valor = 0
    total = str(float(valor))
    if type == 1:
        return valor
    elif type == 2:
        return total

"text[0]" is a value saved in a txt file used as a local database.

During code execution it is necessary to update the total value. exemple:

total = totalValue(2) + 200

The question is how I can change the value of a local variable of a function, in the "total" case, being in the body of the program or in other functions.

  • 1

    Better to say what accurate do because this is completely wrong (several errors together), seems to have an XY problem there and does not need what you are asking, so the solution is another.

  • In the example you gave, totalValue(2) returns a string, that would generate an error when added to 200.

  • Actually I cut some parts of the program because these values depend on other variables. I wrote this way just to illustrate

  • in the case of syntactic or semantic error, the original program has no errors.

  • Really the problem is not clear enough and what is asked actually looks like an XY poem. Can you elaborate better on what you want to do? It seems to me that instead of using global variables you could create a class and manage the context correctly from it. With global variables, if you don’t know what you’re doing, the problem will escalate, even if it seems to solve initially.

1 answer

1


In the variable valor you can pass a string retrieved from a text file, as long as it is a numeric value or pass this string directly as a parameter in the function calcular_total. This function will increment the global variable called total.

valor = "10.5"

total = 0

def calcular_total(valor):

    global total    

    total += float(valor)

    return total


total = calcular_total(valor)
total = calcular_total("0.5")
total = calcular_total("1.8")

print(total)

Exit:

12.8

  • Thanks! It worked out.

  • Good Jorge, I’m happy to help you. Hug and see you next time!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.