Ovi
Ovi

Reputation: 573

Can I make python use a previous definition of a variable?

This is a simplified version of my problem

def findX():
    x = 2
    return x

def main():
    y = findX()
    y = y + 10
    #(unknown code here)
    print (y)


main()

I want the output to be:

2

Can I do this without subtracting 10 or without running findX() again? I think defining y = findX() as a global variable might work, but I would like to avoid global variables if possible.

Upvotes: 0

Views: 103

Answers (1)

BrenBarn
BrenBarn

Reputation: 251408

No, you can't. When you assign a new value to y, it replaces the old value.

If you want to keep both values, assign the new one to a different variable:

y = findX()
z = y + 10

Upvotes: 5

Related Questions