After executing the above code, what is the value of y?

Technology CommunityCategory: PythonAfter executing the above code, what is the value of y?
VietMX Staff asked 3 years ago
Problem
>>> x = 100
>>> y = x
>>> x = 200

After executing the above code, what is the value of y?

>>> print(y)
100

Assignment in Python means one thing, and one thing only: The variable named on the left should now refer to the value on the right.

In other words, when I said:

y = x

Python doesn’t read this as, “y should now refer to the variable x.” Rather, it read it as, “y should now refer to whatever value x refers to.”

Because x refers to the integer 100, y now refers to the integer 100. After these two assignments (“x = 100” and “y = x”), there are now two references to the integer 100 that didn’t previously exist.

When we say that “x = 200”, we’re removing one of those references, such that x no longer refers to 100. Instead, x will now refer to the integer 200.