ASSIGNMENT
ASSIGNMENT
Q.3 Define Types of Variable in Python.
Answer :-Â
Types of Variables in Python
In Python, variables are used to store data, and the type of variable depends on the type of data it holds.
Python is a dynamically typed language, meaning you do not need to declare the type of a variable explicitly; it is determined automatically at runtime.
Here are the main types of variables in Python.Â
1. Global Variables :-Â
Definition: – These are variables declared outside of any function or class. They are accessible throughout the program, including within functions, unless explicitly shadowed by a local variable.
Scope: Available globally, across all functions and classes.
Example :-Â
x = 10 # Global variable
def display():
print(“Value of x:”, x)
display() # Output: Value of x: 10.Â
2. Local Variables
Definition: Variables declared inside a function or block of code. They are accessible only within that function or block and cease to exist outside of it.
Scope: Limited to the function or block in which they are defined.
Example:
def example():
y = 5 # Local variable
print(“Value of y:”, y)
example() # Output: Value of y: 5
# print(y) # This will cause an error as y is not accessible outside the function
3. Instance Variables:-
Definition: These are variables specific to an object, defined within a class using
self. Each object can have its own copy of instance variables.Scope: Specific to the object of a class.
Example:
class Example:
def __init__(self, value):
self.data = value # Instance variable
obj1 = Example(10)
obj2 = Example(20)
print(obj1.data) # Output: 10
print(obj2.data) # Output: 20
4. Class Variables :-
Definition: Variables shared across all instances of a class. They are defined within the class but outside any instance methods.
Scope: Shared by all objects of the class.
Example:
shared_data = “shared” # Class variable
obj1 = Example()
obj2 = Example()
print(obj1.shared_data) # Output: shared
print(obj2.shared_data) # Output: shared
Example.shared_data = “updated” # Modifies the class variable
print(obj1.shared_data) # Output: updated
print(obj2.shared_data) # Output: updated
5.Constants
Definition: Although Python does not support true constants, variables defined in uppercase by convention are treated as constants and not modified during the program’s execution.
Scope: Global or local depending on where they are defined.
Example:
PI = 3.14159 # Constant
GRAVITY = 9.8 # Constant
print(“PI:”, PI)
print(“Gravity:”, GRAVITY)
6. Nonlocal Variables
Definition: These are variables declared inside a nested function and are not global or local to the current function. They allow access to variables in the nearest enclosing scope that is not global.
Scope: Limited to the enclosing scope.
Example :