I have the following code using a for loop:
total = 0
for num in range(101):
total = total + num
print(total)
Now the
In python there is no need, in most cases, to define/declare variables.
The rule is that if you write (assign) a variable then the variable is a local variable of the function; if you only read it instead then it's a global.
Variables assigned at top-level (outside any function) are global... so for example:
x = 12 # this is an assignment, and because we're outside functions x
# is deduced to be a global
def foo():
print(x) # we only "read" x, thus we're talking of the global
def bar():
x = 3 # this is an assignment inside a function, so x is local
print(x) # will print 3, not touching the global
def baz():
x += 3 # this will generate an error: we're writing so it's a
# local, but no value has been ever assigned to it so it
# has "no value" and we cannot "increment" it
def baz2():
global x # this is a declaration, even if we write in the code
# x refers to the global
x += 3 # Now fine... will increment the global
The for
statement is simply a loop that writes to a variable: if no declaration is present then the variable will be assumed to be a local; if there is a global
or nonlocal
declaration then the variable used will have the corresponding scope (nonlocal
is used to write to local variable of the enclosing function from code in a nested function: it's not used very frequently in Python).