Tutorial Playlist
200 Lessons1. Introduction to Python
2. Features of Python
3. How to install python in windows
4. How to Install Python on macOS
5. Install Python on Linux
6. Hello World Program in Python
7. Python Variables
8. Global Variable in Python
Now Reading
9. Python Keywords and Identifiers
10. Assert Keyword in Python
11. Comments in Python
12. Escape Sequence in Python
13. Print In Python
14. Python-if-else-statement
15. Python for Loop
16. Nested for loop in Python
17. While Loop in Python
18. Python’s do-while Loop
19. Break in Python
20. Break Pass and Continue Statement in Python
21. Python Try Except
22. Data Types in Python
23. Float in Python
24. String Methods Python
25. List in Python
26. List Methods in Python
27. Tuples in Python
28. Dictionary in Python
29. Set in Python
30. Operators in Python
31. Boolean Operators in Python
32. Arithmetic Operators in Python
33. Assignment Operator in Python
34. Bitwise operators in Python
35. Identity Operator in Python
36. Operator Precedence in Python
37. Functions in Python
38. Lambda and Anonymous Function in Python
39. Range Function in Python
40. len() Function in Python
41. How to Use Lambda Functions in Python?
42. Random Function in Python
43. Python __init__() Function
44. String Split function in Python
45. Round function in Python
46. Find Function in Python
47. How to Call a Function in Python?
48. Python Functions Scope
49. Method Overloading in Python
50. Method Overriding in Python
51. Static Method in Python
52. Python List Index Method
53. Python Modules
54. Math Module in Python
55. Module and Package in Python
56. OS module in Python
57. Python Packages
58. OOPs Concepts in Python
59. Class in Python
60. Abstract Class in Python
61. Object in Python
62. Constructor in Python
63. Inheritance in Python
64. Multiple Inheritance in Python
65. Encapsulation in Python
66. Data Abstraction in Python
67. Opening and closing files in Python
68. How to open JSON file in Python
69. Read CSV Files in Python
70. How to Read a File in Python
71. How to Open a File in Python?
72. Python Write to File
73. JSON Python
74. Python JSON – How to Convert a String to JSON
75. Python JSON Encoding and Decoding
76. Exception Handling in Python
77. Recursion in Python
78. Python Decorators
79. Python Threading
80. Multithreading in Python
81. Multiprocеssing in Python
82. Python Regular Expressions
83. Enumerate() in Python
84. Map in Python
85. Filter in Python
86. Eval in Python
87. Difference Between List, Tuple, Set, and Dictionary in Python
88. List to String in Python
89. Linked List in Python
90. Length of list in Python
91. Reverse a List in Python
92. Python List remove() Method
93. How to Add Elements in a List in Python
94. How to Reverse a List in Python?
95. Difference Between List and Tuple in Python
96. List Slicing in Python
97. Sort in Python
98. Merge Sort in Python
99. Selection Sort in Python
100. Sort Array in Python
101. Sort Dictionary by Value in Python
102. Datetime Python
103. Random Number in Python
104. 2D Array in Python
105. Abs in Python
106. Advantages of Python
107. Anagram Program in Python
108. Append in Python
109. Applications of Python
110. Armstrong Number in Python
111. Assert in Python
112. Binary Search in Python
113. Binary to Decimal in Python
114. Bool in Python
115. Calculator Program in Python
116. chr in Python
117. Control Flow Statements in Python
118. Convert String to Datetime Python
119. Count in python
120. Counter in Python
121. Data Visualization in Python
122. Datetime in Python
123. Extend in Python
124. F-string in Python
125. Fibonacci Series in Python
126. Format in Python
127. GCD of Two Numbers in Python
128. How to Become a Python Developer
129. How to Run Python Program
130. In Which Year Was the Python Language Developed?
131. Indentation in Python
132. Index in Python
133. Interface in Python
134. Is Python Case Sensitive?
135. Isalpha in Python
136. Isinstance() in Python
137. Iterator in Python
138. Join in Python
139. Leap Year Program in Python
140. Lexicographical Order in Python
141. Literals in Python
142. Matplotlib
143. Matrix Multiplication in Python
144. Memory Management in Python
145. Modulus in Python
146. Mutable and Immutable in Python
147. Namespace and Scope in Python
148. OpenCV Python
149. Operator Overloading in Python
150. ord in Python
151. Palindrome in Python
152. Pass in Python
153. Pattern Program in Python
154. Perfect Number in Python
155. Permutation and Combination in Python
156. Prime Number Program in Python
157. Python Arrays
158. Python Automation Projects Ideas
159. Python Frameworks
160. Python Graphical User Interface GUI
161. Python IDE
162. Python input and output
163. Python Installation on Windows
164. Python Object-Oriented Programming
165. Python PIP
166. Python Seaborn
167. Python Slicing
168. type() function in Python
169. Queue in Python
170. Replace in Python
171. Reverse a Number in Python
172. Reverse a string in Python
173. Reverse String in Python
174. Stack in Python
175. scikit-learn
176. Selenium with Python
177. Self in Python
178. Sleep in Python
179. Speech Recognition in Python
180. Split in Python
181. Square Root in Python
182. String Comparison in Python
183. String Formatting in Python
184. String Slicing in Python
185. Strip in Python
186. Subprocess in Python
187. Substring in Python
188. Sum of Digits of a Number in Python
189. Sum of n Natural Numbers in Python
190. Sum of Prime Numbers in Python
191. Switch Case in Python
192. Python Program to Transpose a Matrix
193. Type Casting in Python
194. What are Lists in Python?
195. Ways to Define a Block of Code
196. What is Pygame
197. Why Python is Interpreted Language?
198. XOR in Python
199. Yield in Python
200. Zip in Python
Variable scope is a basic idea in Python and programming in general. Writing maintainable and error-free code requires an understanding of how variables operate in various scopes. One of the two scopes of variables is the global variable in Python. This tutorial aims to provide a clear and informative insight into the topic of global variables in Python.
Global variables in Python are a fundamental concept in programming. This tutorial aims to offer an organized insight into the vast topic of global variables and how to use the concept in your programming journey.
Global variables in Python are variables that you define at the script or modules level, outside of any specific function. They have a scope meaning they can be accessed from, within the codebase or module. This allows them to be utilized throughout the program rather than being restricted to a single function or block of code.
An example of creating and utilizing a global variable in Python is shown below:
Code:
# Define a global variable
my_global_variable = 100
def my_function():
# Access the global variable
print(my_global_variable)
# Call the function
my_function() # Output: 100
# You can also modify the global variable within a function
def modify_global_variable():
global my_global_variable
my_global_variable = 205
modify_global_variable()
# Now the global variable has been modified
print(my_global_variable) # Output: 205
The use of the global keyword holds significance when making changes to a global variable within a function. It guarantees that you are manipulating the intended global variable and not a newly created local variable with the same name.
The example above demonstrates how my_global_variable remains modifiable both inside and outside functions since it is defined at the top level of the script.
It's crucial to use global variables sparingly because doing so can make your code less modular and more challenging to comprehend and debug. Instead of extensively depending on global variables, it is frequently advised to encapsulate data within functions or classes and pass values between them as arguments or attributes.
Local variables in Python are those that are declared inside a particular function or block of code and are only usable inside that function or block. Local variables are only used within the function or block in which they are defined and have a constrained scope.
In Python, local variables are created by merely giving a variable name and value within a function or a block of code. Here's an example:
Code:
def our_function():
# Define the local variable
our_local_variable = 50
print(our_local_variable)
# Call the function
our_function() # Output: 50
# Trying to access the our_local_variable outside the function will result in an error
# print(our_local_variable) # This will raise a NameError
In the above case, our_local_variable is a local variable because it is defined inside the our_function function. It can only be accessed and used in the context of that function. You will see a NameError if you attempt to access our_local_variable from outside of our_function because it is not defined there.
To store and alter data within a single function without affecting other areas of the program, local variables are often utilized. They are separate from the global scope and do not conflict with variables defined in other functions or the global variables.
In Python, the term "variable scope" describes the area or context in which a variable is declared and accessible. It specifies the guidelines for how variables should be displayed and usable in various Python code sections.
The two primary types of variable scope in Python are:
Variables defined inside a particular function or block of code are known as local scope. These variables are not visible or useful outside of that function or block; only that function or block has access to them. The local variables are normally erased when the function or block ends, so their values are no longer accessible. Let us look at an example:
Code:
def our_function():
our_local_variable = 50
print(our_local_variable)
our_function() # This works
# print(local_variable) # This will raise a NameError because local_variable is not defined here
Variables defined outside of any functions or blocks at the top level of a script or module are known as global scope. The script or module's global variables can be accessible from anywhere, including inside functions. To be sure you're referring to the global variable and not defining a new local variable with the same name when you want to edit a global variable inside of a function, you must use the global keyword. Let us look at an example:
Code:
our_global_variable = 109
def our_function():
print(our_global_variable)
our_function() # This works because global_variable is accessible inside the function
By defining them at the top level of a script or module in Python, separate from any functions or blocks, you can create global variables. Global variables are available from anywhere in the script or module, including inside functions, because they have a global scope. You may make and use global variables in the following way:
Code:
# Define global variables
my_global_variable_1 = 100
my_global_variable_2 = "Hello, World!"
def my_function():
# Access global variables
print(my_global_variable_1)
print(my_global_variable_2)
# Call the function
my_function() # Output: 100, Hello, World!
# Modify a global variable from within a function
def modify_global_variable():
global my_global_variable_1
my_global_variable_1 = 20
modify_global_variable()
# Now the my_global_variable_1 has been modified
print(my_global_variable_1) # Output: 20
The global_variable_1 and global_variable_2 are defined at the top level of the script in the aforementioned example, making them variables. Both inside and outside of the my_function function, you can access these variables. Use the global keyword before the variable name, as seen in the modify_global_variable function, to change a global variable from within a function.
As long as you define global variables at the top level of your script or module, you can access them both inside and outside of a function in Python. For accessing a global variable both inside and outside of a function, follow these steps:
You don't need to use any additional keywords or declarations to access a global variable inside of a function; just use the variable name.
Code:
global_variable_1 = 100
def my_function_1():
# Access the global variable
print(global_variable_1)
my_function_1() # Output: 100
The global_variable_1 can be accessed in the my_function_1 function because it is defined globally.
You can also use the variable name directly, as you would for any other variable, to access a global variable outside of a function.
Code:
global_variable_2 = 30
def my_function_2():
pass # This function does not use global_variable
# Access the global variable outside of the function
print(global_variable_2) # Output: 300
Since global_variable_2 has a global scope, even though we access it outside of the my_function_2 function, it is still available.
It's crucial to remember that global variables can have their values changed from within a function by using the global keyword. For instance:
Code:
global_variable_3 = 30
def modify_global_variable():
global global_variable_3
global_variable_3 = 50
modify_global_variable()
print(global_variable_3) # Output: 50
The global keyword is used in this instance by the modify_global_variable function to signal that it wishes to change the global variable global_variable_3. 50 is assigned to the global variable after the function has been called.
By declaring variables within a particular function or block of code, you can construct variables with local scope in Python. Local variables cannot be seen outside of the function or block in which they are defined and are only useful within that area. Here are some illustrations of local scope variables:
Code:
def my_function_1():
# Define local variables
local_var_1 = 101
local_var_2 = "Hello, World!"
# Access and use local variables
print(local_var_1)
print(local_var_2)
my_function_1() # Output: 101, Hello, World!
# Trying to access local variables outside the function will result in an error
# print(local_var_1) # This will raise a NameError
# print(local_var_2) # This will raise a NameError
In this case, the local variables local_var_1 and local_var_2 are defined inside the my_function function. They are only accessible and usable within the boundaries of my_function_1.
Code:
def check_age(age_1):
if age_1 >= 18:
# Define a local variable inside the block
can_vote_1 = True
else:
# Define another local variable inside the block
can_vote_1 = False
# Access and use local variables
print("Can vote:", can_vote_1)
check_age(21) # Output: Can vote: True
check_age(16) # Output: Can vote: False
# Trying to access can_vote outside the block will result in an error
# print(can_vote_1) # This will raise a NameError
The can_vote_1 is defined in conditional blocks in this example. It can only be accessed within those blocks because it is a local variable with block-level scope.
To store and modify data within a single function or block without affecting other areas of your code, local variables are useful. They are transitory and ideal for handling temporary data because they are separated from the global scope and normally removed when the function or block ends.
In Python, local and global variables have distinct functions that are utilized to accomplish diverse programmatic objectives. For the following reasons, Python uses local and global variables:
Aspect | Local variables | Global variables |
Scope | Restricted to the particular function or block in which they are defined. | Accessible through functions as well as from elsewhere in the program. |
Lifetime | Exist solely throughout the course of the function or block where they are defined. | Exist for the duration of the program's execution. |
Accessibility | Outside of the function or block where they are defined, they are not visible or accessible. | Available from every section of the program. |
Purpose | Used to keep transitory information and draught outcomes in a particular context. | Used to store data that must be shared and accessed by other program components. |
Data isolation | Avoid naming conflicts between functions, and guarantee data isolation. | If not used appropriately, global variables can result in name disputes. |
In summary, global variables in Python provide a mechanism to share and access data throughout various program components. They can be used from anywhere in the program, including within functions, because they have a global scope.
1. What occurs if you attempt to access a global variable in Python that is not defined?
Because Python cannot identify the variable, accessing an undefined global variable will result in a NameError.
2. Is it feasible to use numerous functions to alter the value of a global variable?
As long as the global keyword is used in each function that alters the global variables in Python, you can change the value of a global variable from numerous functions.
3. Can Python programs encounter potential problems as a result of global variables?
Yes, using too many global variables can reduce modularity and make code more difficult to understand.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...