LIVE Course for free

Rated by 1 million+ students
Get app now
JEE MAIN 2023
JEE MAIN 2023 TEST SERIES
NEET 2023 TEST SERIES
NEET 2023
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
34 views
in Python by (3.0k points)
What is the scope of a variable in Python?

Please log in or register to answer this question.

1 Answer

0 votes
by (3.0k points)
edited by

The scope of a variable in Python refers to the part of the code where it can be accessed. There are two main types of variable scope in Python: global scope and local scope.

A variable with global scope can be accessed from anywhere in the code, including within functions. A variable with local scope can only be accessed within the function or block of code where it is defined.

When a variable is defined within a function or block of code, it has local scope by default. However, you can make a variable have global scope by using the `global` keyword before the variable name. 

For example:

x = 10

def my_function():
    global x
    x = 20

my_function()
print(x)

In this example, the global keyword is used to make the variable x have global scope within the function my_function(). This allows the function to modify the value of the global variable x. The final print() statement outputs the value 20, which was assigned to x by the function.

Related questions

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...