0

Is it possible to use the new value of x when declaring the variable z?

x = 1
y = 1 + x
x = 2
z = y

That is, z must be 3, not 2.

DapperDuck
  • 2,728
  • 1
  • 9
  • 21
  • You have assigned a new value for x, but the value for y has already been generated. So everything is correct. – iqmaker Jan 02 '21 at 17:13

3 Answers3

1

If you want the value of y to depend on the current value of x, then you can make it a function:

x = 1
y = lambda: 1 + x
x = 2
z = y()

print(z) # outputs 3
kaya3
  • 47,440
  • 4
  • 68
  • 97
1

Python uses a top down structure, meaning that y = 1 + x was executed before x was updated. In this case, you can't use a mutable object, such as a list, because addition was performed on the value, and that action won't update based on new values in the list. However, you can use the lambda function like this:

x = 1
y = lambda: 1 + x
x = 2
z = y()

The lambda function makes the value of y dependent on x, so the program outputs 3.

DapperDuck
  • 2,728
  • 1
  • 9
  • 21
0

first of all, and maybe this is already the solution, Python has a logic system with a few main rules. One of those rules is that it always reads from top to bottom.

If I now look at your code, I can show you what happens:

x = 1     #1) set x to 1
y = 1 + x #2) set y to 1+1
x = 2     #3) set x to 2 
z = y     #4) set z to y, wich is 2

As you can see, rule 3 sets x to 2, but y is already defined and not changed anymore. So the solution to your problem is very easy:

just switch rules 2 and 3

or

get rid of rule 3 en set the value of rule 1 to 2.