Variables in Python

In python, a variable holds a value but like other languages such as C or C++, python variables are not containers. Instead, a variable in python acts as nametag that refers to a stored value.

This article will also tell you about:

How to create a variable in Python

To create a variable, you just need to assign a value to the variable name using the assignment operator (=).

Syntax:
variable_name = value

  • As soon as the value is assigned to a variable, a link is created that connects the variable name to the value. It is called as Reference.
    Example:
    P = 10​

  • The value of the variable can be changed by assigning another value to it. As soon as a new value is assigned to the variable, it starts pointing to the new value.
    Example:
    P = 5​

  • A variable can also refer to a string. A string is always placed inside double or single quotes.
    Example:
    P = "five"​

  • You can assign the same value to two or more variables, thus this value will have 2 references.
    Example:
    A = 50
    B = A​
    Here, the variable B will refer to the value of A ie 50, not the variable A.
    or
    A = B = 50​


Multiple assignment in Python

Python allows you to create or assign multiple variables in a single line. The variable names and their values are separated by a comma.

Example:

length, breadth = 5, 6

This statement will assign 5 to the variable length and 6 to the variable b.

NOTE: If you will not assign a value to the variable while creating it, an error will occur saying the name is not defined.
Example:

>>> a

Output: Error

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

No datatype declaration: In the above examples, you can see that the same variable P is referring to different types of values including an integer and a string.
This shows that a python variable is generic ie it is not bound to a specific datatype. Thus, while creating a variable, you do not need to declare the datatype. It can freely refer to any type of value.

No declaration of variables: In python, the variables are not declared. To use a variable, you need to initialize the variable.

Rules to create a variable name in Python.

  1. A variable name must start with an alphabet or underscore(_).
  2. It can only contain alphabets, digits and underscore(_). No other characters are allowed.
  3. No space between characters is allowed in a variable name.

Example:

  • Valid Names: age, Weight, DATE, day_1 etc.
  • Invalid Names: #age, (Weight), @DATE, day 1 etc.

Note: Python is a case-sensitive language. Therefore, you need to be careful while creating variable names. Variable name 'AGE' will not be the same as 'age'.

How to print the value of a variable in Python.

You can print the value of a variable as output using the built-in function print(). The variable name is passed as the argument to the print() function.

Syntax:
print(variable_name)

Let us see a simple python program which creates two variables and prints them.

>>> AGE, weight = 58, 62 #Variable creation
>>> print(AGE)
58
>>> print(weight)
62
>>> print(AGE, weight) #Printing both the variables in a single instruction.
58 62
>>> 

How to take input from the user in Python.

  • To take input from the user, a function input() is used.

    Syntax:
    variable_name = input ()

    Example:

    age = input("Enter the age:")
    print("Your age=" ,age)

    Output:

    Enter the age:55
    Your age= 55
  • You can also typecast the variable to make it hold a particular type of value.

    Syntax:
    variable_name = datatype(input ())

    Example:

    age = int(input("Enter the age:"))
    print("Your age=" ,age)

    Output:

    Enter the age:18.5
    
    Traceback (most recent call last):
      File "C:\Users\TS7\AppData\Local\Programs\Python\Python37\if.py", line 1, in <module>
        age = int(input("Enter the age:"))
    ValueError: invalid literal for int() with base 10: '18.5'

    Explanation:

    Since the value to be entered in the variable age is typecasted to integer, the code generates an error on giving a float value as input.

Memory allocation in Python

In Python, a variable is not a reserved memory location, but it refers to a value. This value occupies some space in the memory. When a variable is defined, the variable starts pointing to the value. This is known as a Reference. Now some memory is assigned to the value.

Python maintains a counter for the number of references to a particular value. When this counter becomes zero i.e no variable is pointing to that value, the memory occupied by the value is released and value is removed by the Python garbage collector.

Scope of the Python Variable

The scope of a Variable is the portion of the code where that variable can be accessed. On the basis of scope, the variables are classified in 2 categories.

  • Local Variable: A local variable is created inside a function and it cannot be accessed outside the function. A function is created using 'def' keyword.

    Syntax:
    def function_name():
          local_variable_name = value

  • Global Variable: A global variable is accessible anywhere in the program.

    Syntax:
    variable_name = value

    Usually, global variables are created outside of any function in the program. But, Python allows you to define a global variable within a function using the 'global' statement.

    Syntax:
    def function_name():
          global variable_name
          variable_name = value

 Now let us create a program using local and global variables.

>>> g = 10 #creating a global variable.
>>> print(g)
10

>>> def scope(): #creating a function.
      l = 20 #creating a local variable inside the function.
      global G #declaring a variable as global inside the function using 'global' statement.
      G = 30 #initializing the global variable.

      #printing the local & global variables inside the function.
      print(l)
      print(G)
      print(g) #the function ends here.

>>> scope() #calling the function.

20
30
10

#printing the local variable outside the function.
>>> print(l)

Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
print(l)
NameError: name 'l' is not defined

#printing the global variable declared in the function. 
>>> print(G)

30

Explanation:

  • The global variable g can be accessed anywhere in the program. It is printed inside the scope() function and outside the function as well. 
  • In the above program, you can clearly see that when the local variable l is printed outside, an error shows up saying the name 'l' is not defined. This happened because the scope of the local variable lies only inside of the function. It cannot be accessed outside the function.
  • The global variable created inside the function can be accessed globally in the program. Though it looks like a local variable, but the 'global' statement makes the scope of this variable global.