Variables and Memory in Python.
Variables
and Memory
Application
memory
Heap
|
Stack
|
Global
|
Code
|
Contains Remaining Memory
Contains
local variables
Contains
global variable
Contains general instructions
The
variables defined inside functions are stored in stack and the global variables
lies within Global .After the function returns the memory occupied by stack
variable is free. Memory consumed by global variables can only be collected
after the program terminates.
Scope
of variable: Global and Local
E.g.
pi = 3.14
def cube(num):
‘’’
number->number
Given a
number, this program returns the third power of the given number.
>>>cube(2)
8
‘’’
cubed
= num * num * num
print(pi)
return
cubed
def circlearea(radius):
‘’’
number->number
Given
a number(radius) this program gives area of the circle.
Formula:
Area=
pi * radius * radius
>>>circlearea(10)
314
‘’’
area
= pi * radius * radius
print(pi)
return
area
print(pi)
Inside Stack
Frame 1
|
Frame 2
|
….
|
Frame n
|
Variable
Definition: It is a construct or identifier
that refers to a value in memory location.
[Variable is
analogical to shopping mall luggage counter token.]
X Y
x1001
|
x1002
|
….
|
….
|
….
|
x1001
|
2
|
x1002
|
3
|
…
|
|
|
|
A variable
does not contain a value , it refers to it.
Variable as Storage unit.
Since variables hold reference
to data for manipulation. Popular
database operations like Insert, Update, Delete should also be possible on
variable.
To something like insert or
assign or define:
Syntax
is : variable = value
E.g.
>>>x=5
To update a variable value:
Syntax
is : variable
= new _value
E.g.
>>>x=10
After new value assignment, the
variables are pointer is pointed to new value. Since one variable can point to
only one location at a time. The value old value is garbage collected.
To delete a variable:
Syntax
is : del variablename
E.g. >>>del x
id() function:
This is used to determine the id
of a variable. It is value based and not variable name based.
>>>x=5
>>>id(x)
140566819039352
>>>y=6
>>>id(y)
140566819039328
>>>z=5
>>>id(z)
140566819039352
Here two different variables x and z have
same id because they refer to same value.
Unique property of the = (assignment) operator
It right to left hence , in
variable = value , value is considered first and the identification is value
based.
Variable Nomenclature
1. Variable name must start with
[_a-z, A-Z] then followed by [_a-z, A-Z, 0-9]
2. Variable names are case
sensitive
3. Keywords cannot be used as
Python Variable names
>>>import keyword
>>>keyword.kwlist
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del',
'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if',
'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise',
'return', 'try', 'while', 'with', 'yield']
Examples of valid and invalid
variable name.
_a=3 #valid
Apple = “apple” #valid
0time = 0 #in-invalid
Variable and Data Types
number = 100 #
An integer assignment
miles = 1000.0 #
A floating point
name = "John" # A string
x = [1,2,”users”] # A List
y = (“username”, “password”) # A
Tuple
dict ={'name':'john','code':6734,'dept':'sales'} # A dictionary
Data type conversion
Function
|
Description
|
int(x
[,base])
|
Converts
x to an integer. base specifies the base if x is a string.
|
long(x
[,base] )
|
Converts
x to a long integer. base specifies the base if x is a string.
|
float(x)
|
Converts
x to a floating-point number.
|
complex(real
[,imag])
|
Creates
a complex number.
|
str(x)
|
Converts
object x to a string representation.
|
repr(x)
|
Converts
object x to an expression string.
|
eval(str)
|
Evaluates
a string and returns an object.
|
tuple(s)
|
Converts
s to a tuple.
|
list(s)
|
Converts
s to a list.
|
set(s)
|
Converts
s to a set.
|
dict(d)
|
Creates
a dictionary. d must be a sequence of (key,value) tuples.
|
frozenset(s)
|
Converts
s to a frozen set.
|
chr(x)
|
Converts
an integer to a character.
|
unichr(x)
|
Converts
an integer to a Unicode character.
|
ord(x)
|
Converts
a single character to its integer value.
|
hex(x)
|
Converts
an integer to a hexadecimal string.
|
oct(x)
|
Converts
an integer to an octal string.
|
Values that a variable can point to
variable = data-type
variable = expression
variable = variable
variable = function()
Python Variable properties
1.
Implicitly defined
Python
variables do not need explicit declaration to reserve memory space. The
declaration happens automatically when you assign a value to a variable. The
equal sign (=) is used to assign values to variables.
2.
Strongly typed
Python
is strongly typed as the interpreter keeps track of all variables types.
Compiler here cannot can tell which type a variable refers
to.
Type()
function
type(object) -> the object's type
>>>x=”name”
>>>type(x)
<type 'str'>
Multiple
assignment
Ex: >>>a=b=c=1
>>>a,b,c= 1,2,”name
Python
default variable ‘_’
‘_’ is a variable auto defined by
Python and it stores last calculation. It is like ANS button on calculator.
>>> 20 + 30
50
>>> 50 + _
100
Operators in Python
Variables serve as storage unit
for input data of any type or functions return value. Variables exist because
data cannot be stored in continuous memory blocks due to multitasking. Continuous
data memory mapping will also cause fragmentation and other losses. Thus all
applications think as the entire computer memory belongs to them so the data is
stored randomly and variables keep reference to them, else the data will be
lost. One variable has only one referring arm so it can only point to one
expression value at a time. It’s good to have data stored randomly at best
available space and keep a variable reference to them. But if we don’t
manipulate data what is the use. Computer is a data processor and not data
storage unit. It just stores for processing and keeps processed data.
Processing ability comes from the
use of operators on data or variables pointing to data.
Syntax: Variable/Data operator
Variable/Data
Most commonly used operators are
1)
Arithmetic operators:
+,
-, *,/,//,%,**,-
+,-,*,/ works as expected from
their algebra class notations.
// is called floor division and
it truncates the floating point value while preserving the data type.
% is called modulus and gives reminder
of division. It works right to left.(?)
** is exponential.
2)
Conditional operators
<,>,==,<=,>=,!=
These operators result in Boolean
True or False value. They are good for using in conditions
3)
Membership operators
in,
not in simply
checks if the value is in a particular sequence or range and return True and
False accordingly.
>>>5 in [1,2,3,45]
True
0 comments:
Post a Comment