Create Python global variables in a function & Use in Other Functions

A variable declared outside of the function or in the global scope (class level) is known as Global Variables in Python. These are defined and declared outside a function and we need to use them inside a function.

Declare the Global variable when you want to use the same variable for the rest of the program.

How to create or use global variables in a function?

Answer: Simpl uses a global variable in other functions by declaring it as global in each function that assigns to it. See the below example.

Output: 1

Why using a global keyword? because defining a Global variable is not a good ide and python wants to make sure that you really want to use global variables.

Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6
Python 3.7
All Python program are in Python 3, so it may change its different from python 2 or upgraded versions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.