How to make a variable in the functions of the global python

"Learn how to make a variable global in a Python function w/ an example of a 'total' variable that counts the sum of all inputs."

Creating a Global Variable in Python

A global variable in Python is a variable that can be accessed from anywhere in the program, regardless of the scope. This can be useful when you need to share information between different functions or classes. To create a global variable, you use the keyword “global” before the variable name.

For example, let’s say you want to create a global variable called “message”. You would do this by typing the following code:


global message
message = "Hello World!"

Now this variable can be accessed from anywhere in the program. If you want to access it from a function, you just need to use the keyword “global” again before the variable name.


def say_hello():
  global message
  print(message)

say_hello() # prints "Hello World!"

Global variables can be very useful when you need to share information between different functions or classes. However, it’s important to be careful when using global variables, as they can lead to unexpected behavior if not used correctly.

Answers (0)