Search code examples
logic

Python storing value of old assigned variable


lets say i have this code

x = 5

while True:
    x = 10
break

is there a way I can keep the original value of x and the new assigned value


Solution

  • This pattern might be what you're looking for

    x = 5
    y = 0
    while True:
        # y stores old value of x
        y = x
        x = 10
    
    # example where x actually changes
    while True:
        y = x
        x += 1
        print(y, x)