On a closer look, this question doesn't really appear to be about None
, but about scope. Python doesn't have block scopes, so any definition you assign to my_global_string
inside the loop can serve as the initial definition, so long as the loop itself is at the global scope.
There is no need to "preassign" a null value (None
) to the name before entering the loop.
for x in some_iterable:
my_global_string = "hi there"
print(my_global_string)
Should you need to define a global from some other scope, that's why the global
statement exists.
# This function creates a variable named "my_global_string"
# in the global scope.
def define_a_string():
global my_global_string
my_global_string = "hi there"
for x in some_iterable:
define_a_string()
print(my_global_string)