How to create a global variable in python ?

Published: April 29, 2020

Updated: November 29, 2022

Tags: Python; Variables; Global;

DMCA.com Protection Status

Example of how to create a global variable in python:

Using global

To declare for example a as a global variable:

global a

Illustration with a function

Using global variables in a function:

 >>> global a,b
 >>> a = 0.5
 >>> b = 2
 >>> def function( x ):
...     return a * x + b
... 
 >>> function(1)
 2.5
 >>> b = 4
 >>> function(1)
 4.5