2

I found the variable scope of the following code to be very unexpected... (coming from other languages where the scope of the scope_var variable would only exist for the span of the IF):

if scope_var := 'exists after IF':
    pass
print(scope_var)

What will be printed?

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
akaButters
  • 375
  • 1
  • 12

1 Answers1

5

Outputs: exists after IF

so the variable scope_var now exists outside / past the IF statement.

This was very strange to me, so I thought I post this Q/A for others coming from other languages to learn from. (I Googled quite a few articles, and nothing like this answer came up, so I hope this helps people like myself.)

...

Apparently it's not just the Walrus := assignment expression. It happens with a regular FOR statement as well:

for i in range(3):     
    pass 
print(i) 

Outputs: 3

akaButters
  • 375
  • 1
  • 12