2

I'm coming from JavaScript where "const" and "let" are block-scoped. I just noticed when there's a variable in Python inside a for block, that variable can be accesed outside in the main code after the loop finishes running.

for a_value in values:
   myName = "Zoltan"

print(myName) # prints "Zoltan"

In JavaScript I need to do something like this:

let myName; // The variable needs to declared outside to be accesed later outside

for (let i = 0; i < 4; i++) {
  myName = "Zoltan";

console.log(myName)

So, Python doesn't do block scoping. Did I notice correctly?

cxw
  • 16,685
  • 2
  • 45
  • 81
Zoltan King
  • 1,964
  • 4
  • 18
  • 38

0 Answers0