0
def fuc():
   for i in range(2)
      myval=1
   print(myval)

Why is "myval" still accessible even after the for loop? I recall in C, if a variable is set up in a loop, it is only accessible in the loop. So in order to print it like this, I'd have to decleare it outside the loop first. Does anyone know why? In what scope does the variable live in Python?

Jerry Yu
  • 11
  • 3
  • 1
    A loop does not create a new namespace. – Klaus D. Jul 25 '21 at 02:44
  • 1
    Python variables have three possible scopes: function scope, module scope, and class scope. There is no block scoping in Python; a variable defined inside a function will be scoped to the nearest enclosing `def` function. – Silvio Mayolo Jul 25 '21 at 02:45
  • 1
    This is very important to understand: Python is **not** C. Python *doesn't even have variable declarations* – juanpa.arrivillaga Jul 25 '21 at 02:45

0 Answers0