Python: Variables

                        Python: Variables 

Declaring a Variable

A variable holds a value that may change. The process of writing the variable name is called Declaring the variable. In Python, variables do not need to be declared explicitly in order to reserve memory spaces as in other programming languages like C, Java, etc. When we initialize the variable in Python, Python Interpreter automatically does the declaration process.

{tocify} $title= {Table of Contents}

Initializing a Variables

The general format of assignment statement is as follows:

Variable = expression

The equal sign (=) is known as Assignment operator. An expression is any value, text or arithmetic expression, whereas variable is the name of the variable. The value of the expression will be stored in the variable.

Let us now look at an example of initializing a variable:

>>>year=2016

>>> name=’Albert’

The two given statements reserve two memory spaces with variable names year and name.2016 and

Albert, are stored respectively, in these memory spaces as shown in Figure below:


Note: Whenever you want to display the value of the variables, simply type these variable names on console.

Let us now look at an example of a variable displaying its value:

>>> year

2016   # Output

>>> name

‘Albert’   # Output

>>> 

Note: You can also assign one variable value into another variable. Assign the value of name1 variable into name2 variable.

Let us now look at an example of assigning one variable value into another:

>>> name1=’Albert’

>>> name2=name1

>>> name2

‘Albert’      # Output

>>> 

Whenever two values are successively assigned to a variable, the interpreter will forget the previous value assigned to it and store the latest value in the variable memory space.

>>> year=2016

>>> year=2017

>>> year

2017              # Output

>>> 

In the given example, we first assigned 2016 to the variable year and then assigned 2017 to the same variable. The interpreter will forget the value 2016 and will display 2017 as the value of year. We can also assign different types of values to the same variable. For example, we can assign a text value where there previously was a numeric value. Even in such a case however, only the last assigned value remains.

Let us now look at an example of assigning different types of values to the same variable:

>>> amount=50

>>> amount

50              # Output

>>> amount=’Fifty’

>>> amount

‘Fifty’                # Output

>>> 

 



Post a Comment (0)
Previous Post Next Post