-4

I am looking for an example to create a global variable in Python , just like in java you can do something like

 String my_global_string = null
 for .... {
     reassign value of my_global_string
}
use the my_global_string value 

What is the equivalent of null in python if the object is of type file

user_mda
  • 18,148
  • 27
  • 82
  • 145
  • In Python, `null` is `None` – Ryan Jun 22 '20 at 20:25
  • 1
    ...are you looking for `None`? Please remember to _search_ before asking a new question. – ChrisGPT was on strike Jun 22 '20 at 20:25
  • 3
    Does this answer your question? [Referring to the null object in Python](https://stackoverflow.com/questions/3289601/referring-to-the-null-object-in-python) – Unatiel Jun 22 '20 at 20:25
  • Before everybody piles on with negative comments or downvotes, cut the OP a little slack here. They are coming to it from the point of view of a strongly typed language, and asking about the equivalent of `null` **for type `file`**. Well the answer is that there is no equivalent for type `file`. There doesn't need to be. A variable that could under certain circumstances point to a `file` object can instead point to `None` when applicable, even though it is a different type. – alani Jun 22 '20 at 20:31
  • 1
    @alaniwi, I get where you're coming from, but this has still been covered already and users _are_ expected to search before asking. This is the kind of question that experienced users should expect to already be here. – ChrisGPT was on strike Jun 22 '20 at 20:36

1 Answers1

1

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)
chepner
  • 497,756
  • 71
  • 530
  • 681