03python 03 Variables in PYTHON
03python 03 Variables in PYTHON
How you will get the output as following using the above two variables:
My first name is John and My last name is Smith
Print(“My first name is”,fname,” and my last name is”,lname)
Python is a Case-Sensitive Language
• Age=10
• AGE=20
• age=30
If we declare the above three variables with same name, then what will
be the output of following statement
Print(Age)
Re-declare the Variable:
• We can re-declare the python variable once we have declared the
variable already.
Number = 100
print(“Initial Value: ", Number)
30 or 30.5
Performing different operations on Variables
a=10
c=“NIT Srinagar”
d=“CSE”
print(c+d) // This will do the concatenation of String
Print(a+c) // this will give us error. (TypeError: unsupported
operand type(s) for +: 'int' and 'str’)
How Variables are stored in memory
• Whenever you write the statement
‘a=100’
Value 100 is getting stored in some memory location and variable with
name “a” is pointing to that memory location. So, variable with name
“a” will point to a memory location where 100 is stored.
You can check the memory location by id(variable_name)
id(a)
How Variables are stored in memory
Suppose, a=100
id(a) gives some memory location
If, we write a=200, then value 200 will be stored in some new memory
location and variable with name a will start pointing to that memory
location of 200.
id(a) will give new value.
How Variables are stored in memory
Suppose, a=100
b=100
So, here b will point to the same memory location where a was
pointing. Because, value 100 was already stored as an object in some
memory location and for proper memory utilization, python does not
store the same value.
So, variable will point to the same memory location.
id(a)
Id(b)
How Variables are stored in memory
There are two types of memory which is used by python
• Stack Memory: used for storing the state of the program
• Heap Memory: used for storing the variables/objects
Python manager uses the concept called Reference counting, whenever a new object is
created it will update the reference count of the object.
A=100
b=100
Here, python memory manager creates only one object i.e "100" and reference count is
"2".
Whenever a new object is created python manager will checks the memory for the
object.
If object already exists python manager will not create new object instead it references
the name to the object and increases the reference counter of the object.
What will be the output?
>>> f name = 5
>>> print(1,00,000)
>>>month = 09