Variables In Python
- – Variables are used in every programming language and their importance in programming cannot be over-emphasized.
- – Variables in python programming can be considered as a storehouse for data or values.
- – In other words, variables are containers where values are stored.
- – Variables can be used with strings, numbers and integers.
- – In Python, you do not need to specify the type of value in your variable
- – Python is able to detect whether the value you are trying to assign to a variable is a number, integer or a string.
How Many Type Of Variable Are There In Python
Variable
1) Procedural/Functional oriented 2) Object Oriented
a) Local a) Local
b) Global b) Global
c) Class level[Static]
d) Object level[Instance]
Procedural/Functional Oriented- Local And Global Variable-
Ex-
x = 70 # Global variable
class Demo:
x = 30 # Class variable
def display1():
x = 10 # Local variable
print(x) # 10
print(Demo.x) # 30
def display2():
print(x) # 70
print(Demo.x) # 30
def main():
Demo.display1()
Demo.display2()
Demo.main()
Output-
10
30
70
30
Object Oriented- Local, Global And Class Level Variable-
x=70 #Global variable
class Demo:
x=30 #Class level Variable
def display1():
x=40 #Local variable
print(x) #40
print(Demo.x) #30
def display2():
print(x) #70
print(Demo.x) #30
def main():
Demo.display1()
Demo.display2()
Demo.main()
Output-
40
30
70
30
Object Level Variable-
class Demo:
def display1(): #Class level method
print("Inside display1")
def display2(self): #Object level method
print("Inside display2")
def main():
Demo.display1()
obj = Demo() #Demo() --> Will Return the address of the object.. Ex- Returning the address as 2048
# ar --> Referenced variable which will hold the address of the Demo() object.
obj.display2()
Demo.main()
Output-
Inside display1
Inside display2
Global Keyword-
- – This keyword is used to set the global variable from inside the function.
- – global keyword should always be placed at 1st statements inside the function.
x = 20
def display1():
global x
print(x) # 20
x = x + 10
print(x) # 30
def display2():
print(x) # 30
# x = x + 20 # 40 #UnboundLocalError: local variable 'x' referenced before assignment
display1()
display2()
Output-
20
30
30
Ex-
def display():
global x
x = 70
display()
print(x) # 70
Output-
70
Ex-
x=40
def display():
x=10
print(x) #40
global x # SyntaxError: name 'x' is used to global declaration
print(x) #
display()