How to define python global variables

Mondo Technology Updated on 2024-01-29

In Python, you can create global variables by defining variables outside of a function. Global variables are visible throughout the program, including inside functions.

Here's a simple example of how to define and use global variables in Python:

Definition of global variables. 

global_variable = 10

Global variables are used inside functions.

def my_function():

print("inside the function, global_variable =", global_variable)

Call the function.

my_function()

Modify global variables outside of the function.

global_variable = 20

Call the function again and observe the change of the global variable.

my_function()

In the example above, the global variable is a global variable that can be accessed anywhere in the program. Inside the function My Function, we print the values of the global variables. Outside of the function, we modify the value of the global variable and call the function again to see the changes.

It's important to note that if you try to modify the value of a global variable within a function without using the global keyword, Python will interpret this by default as creating a new local variable within the function. If you want to modify a global variable inside a function, you should use the global keyword as follows:

global_variable = 10

def modify_global_variable():

global global_variable

global_variable += 5

modify_global_variable()

print(global variable) output 15

By using the global keyword, you can modify the value of a global variable directly within a function.

Python is a high-level programming language that emphasizes readability and concise syntax (especially the use of whitespace indentation to divide blocks), making programming simpler and easier to understand than other languages such as C++ or J**A. In addition, Python supports a variety of programming paradigms, including object-oriented programming, imperative programming, functional programming, etc., which makes it extremely flexible.

Programming in Python: From Getting Started to Doing 3rd Edition is the best guide for you to get started. This book introduces the basics and application scenarios of Python in detail, and takes you to get started easily. Both novice and experienced developers can benefit from this. Buy now and make Python a tool to make your dreams come true!

Related Pages