Sunday, June 19, 2011

Variables

Variables are reserved memory locations to store values. So When we create a variable we reserve space in memory according to the data type of the variable. The interpreter allocates memory .

Assigning values to variables

Python variables do not have to be explicitly declared. The declaration happens automatically when we assign a value to a variable. The equal sign (=) is used to assign values to variables.

The operand to the left of the = operator is the name of the variable, and the operand to the right of the = operator is the value stored in the variable.

For example:

>>> c=100
>>> m=123.34
>>> name="john"

Python doesn't have the same types as C/C++, which appears to be your question.

For example:
>>> i = 123
>>> type(i)
<type 'int'>
>>> type(i) is int
True
>>> i = 123456789L
>>> type(i)
<type 'long'>
>>> type(i) is long
True
>>> i = 123.456
>>> type(i)
<type 'float'>
>>> type(i) is float
True

Multiple Assignment : You can also assign a single value to several variables simultaneously.

For example:

>>> a=d=s=2
>>> a
2
>>> d
2
>>> s
2

Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location. You can also assign multiple objects to multiple variables.

For example:

>>> a,b,c=2,4,"dfg"
>>> a
2
>>> b
4
>>> c
'dfg'
>>>

Python numbers : Number data types store numeric values. They are immutable data types, which means that changing the value of a number data type results in a newly allocated object.

Number objects are created when you assign a value to them.

For example:

>>> a=1
>>> d=3
>>> f=7

You can delete a single object or multiple objects by using the del statement.

For example:

>>> del a
>>> del d,f

No comments:

Post a Comment