Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does assigning to the variable after the `print` statement in a local class definition change the printed value? [duplicate]

Why does this function output 0 1?

Why is a class in a function behaving like a function? Why didn't I have to call A like a function?

How does the assignment statement after print() affect the values of x and y? When I assign value to x, x becomes 0 and if I assign a value to y, y becomes 0.

x = 0
y = 0

def f():
  x = 1
  y = 1
  class A:
    print(x,y)
    x = 99

f()
like image 593
Hussam Cheema Avatar asked Feb 13 '21 10:02

Hussam Cheema


People also ask

What happens when you assign a value to a variable?

The act of assignment to a variable allocates the name and space for the variable to contain a value. We saw that we can assign a variable a numeric value as well as a string (text) value. We also saw that we can re-assign a variable, providing it a new value which replaces any previous value it contained.

Can you assign a print statement to a variable?

No worries you can assign print() statement to the variable like this. According to the documentation, All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end.

What is variable What is the use of print statement?

As mentioned above, the print statement is used to output all kinds of information. This includes textual and numerical data,variables, and other data types. You can also print text (or strings) combined with variables, all in one statement. You'll see some of the different ways to do this in the sections that follow.

Which operator is used to assign a value to a variable?

The simple assignment operator ( = ) is used to assign a value to a variable. The assignment operation evaluates to the assigned value.


Video Answer


1 Answers

From the Python 3.9 documentation :

If a name binding operation occurs anywhere within a code block, all uses of the name within the block are treated as references to the current block.

The line x = 99 in the class definition, makes x local to the class block.

In a class block,

References follow the normal rules for name resolution with an exception that unbound local variables are looked up in the global namespace.

At the point the print(x,y) is executed, x is an unbound local variable. It's value is looked up in the global namespace, where x = 0.

When a name is used in a code block, it is resolved using the nearest enclosing scope.

When print(x, y) is executed, the value of y is looked up in the nearest enclosing scope, which is the body of def f(), where y = 1.

So print(x, y) outputs 0 1.

like image 120
RootTwo Avatar answered Oct 28 '22 08:10

RootTwo