What are Variables in Python?

Spread the love

What are Variables in Python ?

Variable in simple language means its value can vary. You can store any piece of information in a variable. Variables are nothing but just parts of your computer’s memory where information is stored. To be identified easily, each variable is given an appropriate name. Every variable is assigned a name which can be used to refer to the value later in the program.

Variable Naming Conventions –

When you name a variable, you need to follow some basic rules. These Rules are –

1 . The first character of an identifier must be a letter (upper or lowercase) or an underscore (‘_’) .

2 . The rest of the variable name can be underscore(‘_’) or a letter (upper or lowercase) or digits (0-9).

3 . Variable names are case sensitive. For example myvar and myVar are not the same.

4 . Punctuation characters such as @, $ and % are not allowed within a variable.

Assigning or Initializing Values to Variables –

In Python, Programmers need not explicitly declare variables to reserve memory space. The declaration is done automatically when a value is assigned to the variable using the equal sign (=). The operand on the left side of equal sign is the name of the variable and the operand on its right side is the value to be stored in that variable.

In [1]: a = 10

In [2]: b = 5

In [3]: c = a + b

In [4]: c
Out[4]: 15

Here the variable a is assigned with the value 10 and b with 5. Then the variable c is the sum of these two variables.

In python, you can reassign variables as many times as you want to change the value stored in them. You may even store value of one data type in a statement and then a value of another data in a subsequent statement. This is possible because Python variables do not have specific types, so you can assign an integer to a variable and later assign a string to the same variable.

In [5]: a = 'Hello'

In [6]: b = 3.14

In [7]: a
Out[7]: 'Hello'

In [8]: b
Out[8]: 3.14

Multiple Assignment –

Python allows programmers to assign a single value to more than one variables simultaneously.

For example

In [9]: a = b = c = 10

In [10]: a
Out[10]: 10

In [11]: b
Out[11]: 10

In [12]: c
Out[12]: 10

In the above statement all the variables are assigned with the value of 10.

You can also assign different values to multiple variables simultaneously as shown below.

In [13]: a, b, c = 5, 10, 15

In [14]: a
Out[14]: 5

In [15]: b
Out[15]: 10

In [16]: c
Out[16]: 15

Here a is assigned with 5, b with 10 and c with 15.

Rating: 1 out of 5.

Leave a Reply