0

Please explain the output for the code below. According to me Output should be 1,1 but it is not.Also the assignment of x after the print statement.

x=0
y=0

def f():
    x=1
    y=1
    class C:
        print(x,y)
        x = 2

f()

Output -> 0 1

  • 2
    No, don’t do that: if you write inexplicable code you’ll get inexplicable results. Of course, there is an explanation, but why bother making things so difficult - just write simple code. – DisappointedByUnaccountableMod Jan 27 '21 at 23:35
  • Please repeat [on topic](https://stackoverflow.com/help/on-topic) and [how to ask](https://stackoverflow.com/help/how-to-ask) from the [intro tour](https://stackoverflow.com/tour). “Explain this code to me” is not a Stack Overflow issue. We expect you to trace the code. If you have a *specific* question, then provide your *traced* example to support that question. Tracing includes printing critical values to follow both the data flow and the control flow. – Prune Jan 27 '21 at 23:37
  • 1
    @Prune This is a question about scoping rules. How would you trace that? – Barmar Jan 27 '21 at 23:39
  • Does this help? https://medium.com/@makmanalp/python-statements-in-the-body-of-a-class-63664392e062 – Random Davis Jan 27 '21 at 23:40
  • It seems like this should be answered somewhere in https://stackoverflow.com/questions/291978/short-description-of-the-scoping-rules but I can't find it. – Barmar Jan 27 '21 at 23:41
  • @Barmar: just as I did: start with tracing `id(x), id(y)` in each block. – Prune Jan 27 '21 at 23:41
  • 1
    @Prune How would that explain *why* this is happening? He already knows they're different because of the print output. – Barmar Jan 27 '21 at 23:43
  • 1
    @Prune sounds like you know more about Python than the OP and are expecting them to be able to do the same thing you did to be able to solve the problem themselves, but are not sharing your methodology because they "ought" to know that before coming here. Maybe you could answer the question with how you traced the issue? – Random Davis Jan 27 '21 at 23:44
  • Is this a [class assignment](https://stackoverflow.com/q/65921085/1324033)? It'd help you and your classmates more to research into solving it yourself first – Sayse Jan 27 '21 at 23:48

0 Answers0