-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

5
  • In Python, null is None Commented Jun 22, 2020 at 20:25
  • 1
    ...are you looking for None? Please remember to search before asking a new question. Commented Jun 22, 2020 at 20:25
  • 3
    Does this answer your question? Referring to the null object in Python Commented Jun 22, 2020 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. Commented Jun 22, 2020 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. Commented Jun 22, 2020 at 20:36

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.