Python Variables, Constants, and Literals

Python Variables 

A variable is the name of the location where the value is stored in the memory. Think variable is like a container, where the value can be stored and can be updated later on. 

Syntax : 

Variable_name  = value

Variable_name is the name of the variable, and value is the value assigned to the variable.

Example:

 website = “takeuforward” 
 number = 1

Here website and number are the variables numbers, and we assigned the value “takeuforward” to the variable website and 1 to the variable number.

NOTE: In python, Everything is an object, we don’t actually assign the value to the variables, Instead python gives the reference of the object(value) to the variable.  

Python is dynamically typed, which means the python interpreter automatically understands the type of the value and assigns the value type to the variable. We don’t need to specify the type of variable priorly.

Code:

Python Code

website = "takeuforward"
print(type(website))
website = 1
print(type(website))

Output:

<class ‘str’>

<class ‘int’>

We can observe that initially, the variable website is of type string because the value assigned to it is of type string. Later the value of the variable is changed to int, so the type of variable also changed to int.  

Rules for Writing the Variable Names: 

  • Variable names should contain a combination of LowerCase (a-z) and UpperCase (A-Z) characters and digits(0-9) and underscore (_).
  • Variable name should make sense, for example, the variable name ‘website’ makes more sense than the variable name ’w’. 
  • Variable names should not start with digits.
  • Use underscore(_) to separate words in variable names like my_name, and my_salary. 
  • Variable names should not be equal to any reserved words, like for, while, etc. 

Assigning Values to the Variables: 

Assignment operator ‘ = ’  is used to assigning the value to the variables. 

Code:

Python Code

x = 9
y = [1, 3, 4, 6, 3, 2]
z = 'tuf'
print(x)
print(y)
print(z)

Output:

9
[1, 3, 4, 6, 3, 2]
tuf

In the above code, we had declared 3 variables x,y, and z and assigned the integer value 10 to x, a list of integer values to y, and a string to z 

Updating the Value of Variables : 

Python allows changing the value assigned to the variable at any time in the code. 

Code:

Python Code

name = 'takeuforward'
print(name)
name = 'raj Vikramaditya'
print(name) 

Output:

takeuforward
raj Vikramaditya

Initially, the value stored in the name is ‘ takeuforward ‘, upon changing, the value stored in the name got changed to ‘ raj Vikramaditya ‘. 

Assigning Multiple Values to the Multiple Variables 

Python allows assigning the multiple values to multiple variables in the same declaration. Below is an example.

Code:

Python Code

name, job_title, company = 'raj', 'SDE', 'Google'
print(name)
print(job_title)
print(company)

Output:

raj
SDE
Google

Assigning Same value to Multiple Variables

We can assign the same value to the multiple variables in a single declaration. Let’s look at an example 

Code:

Python Code

a = b = c = 1
print(a, b, c) 

Output: 1 1 1

Python Constants : 

A python constant is a variable whose value cannot be changed throughout the program. 

Unlike other programming, languages python does not have any keyword for declaring the constant variable. Instead, Python provides a special naming convention for constant variables. Any variable written with all Upper case letters is identified as constant in python.

Rules for Writing the Constant Names: 

  • Always use Upper case letters for writing the name. For Example NAME, AGE 
  • Use underscore (_) to separate the words in the name. Example CONST_PI, CONST_G
  • Use a name that makes sense.
  • The constant name should not start with digits.

Assigning values to Constants:

In python, constants are declared and assigned in a module. A module is a new file containing variables, functions, etc which can be imported into the main file.  Inside the module, constants are written in capital letters. 

Creating a Module and declaring Constants 

Code : 

Python Code

#create a constant.py file
PI  = 3.14 
SPEED_OF_SOUND = 343 
GRAVITY = 9.8 

Importing the constant values into the main file.

Code:

Python Code

import constant as const
print("value of PI is:", const.PI)
print("Acceleration due to gravity is:", const.GRAVITY, "m/s")
print("Speed of sound is:", const.SPEED_OF_SOUND, "m/s")

Output:

value of PI is: 3.14
Acceleration due to gravity is: 9.8 m/s
Speed of sound is: 343 m/s

Python Literals : 

The data which is being assigned to the variables are called Literal. Literal is the raw data given to the variable or constant. In python there are various types of literal let’s look at them one by one.

Numeric Literals: 

There are 3 different categories of numeric literals, They are — Integer, Float, and Complex.

Code:

Python Code

a = 0b101010 # Binary Literals
b = 106  # Decimal Literal
c = 0o2340  # Octal Literal
d = 0x12dec  # Hexadecimal Literal


#Float Literal
float_1 = 10.5987
float_2 = 1.23e2

#Complex Literal
x = 4 + 3.14j

print(a, b, c, d)
print(float_1, float_2)
print(x, x.imag, x.real)

Output:

42 106 1248 77292
10.5987 123.0
(4+3.14j) 3.14 4.0

In the above code 

  • We assigned integer literals to different variables. Here ‘a’ is a binary literal, ‘b’ is a decimal literal, ‘c’ is an octal literal, and ‘d’ is a hexadecimal literal. All the literals are converted into decimal literals when we print them.
  • 10.587 and 1.23e2 are float literals. 1.23e2 expands to 1.23 * 102 .
  • ‘x’ is assigned with a complex literal. Imaginary and real literal of the complex literals can be obtained using x.imag and x.real. 

String Literals : 

String literal is a sequence of characters surrounded by quotes. The quotes can be single, double, or triple quotes. A character literal is a single character surrounded by either a single or double quote. 

Code:

Python Code

s = "This is a string Literal"
char = 'c'
multi_line = """This is multi-line 
                string Literal"""
print(s)
print(char)
print(multi_line)

Output:

This is a string Literal
c
This is multi-line
string Literal

Here “This is string Literal” is the string Literal. “C” is the character Literal and “”” This is multi-line string Literal ””” is the multi-line string Literal.

Boolean Literals : 

Boolean Literal has any of the two values True or False.

True is treated as 1 and False is treated as 0. 

Code:

Python Code

b1 = (1 == True)
b2 = (0 == False)
x = True + 1
y = False + 3
print("b1 is: ", b1)
print("b2 is: ", b2)
print("x is: ", x)
print("y is: ", y)

Output:

b1 is: True
b2 is: True
x is: 2
y is: 3

Since True represents 1 and False represents 0, b1 and b2 are True. Similarly for x and y.

Special Literal : 

Python provides a special Literal called None. It is used for specifying that the field has not been created. 

Code:

Python Code

skills = ['coding', 'blogging', 'freelancing']

def checkskill(skill):
    if skill in skills:
        print('yes')
    else:
        print(None)

checkskill('coding')
checkskill('painting')

Output:

yes
None

The function chekskill() checks whether the provided skill is present in skills or not. If yes prints yes, else prints None. 

Literal Collections : 

In python, there are 4 types of literal Collections. They are 

  1. List Literals
  2. Tuple Literals
  3. Set Literals 
  4. Dictionary Literals 

Code:

Python Code

languages = ['java', 'python', 'c++']
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9)
maang = {'m': 'Meta',
         'a': 'Apple',
         'a':  'Amazon',
         'n': 'Netflix',
         'g': 'Google'}
vowels = {'a', 'e', 'i', 'o', 'u'}

print(languages)
print(numbers)
print(maang)
print(vowels)

Output:

[‘java’, ‘python’, ‘c++’]
(1, 2, 3, 4, 5, 6, 7, 8, 9)
{‘m’: ‘Meta’, ‘a’: ‘Amazon’, ‘n’: ‘Netflix’, ‘g’: ‘Google’}
{‘i’, ‘a’, ‘o’, ‘e’, ‘u’}

Here the languages are the List Literal, numbers are tuple Literal, maang is Dictionary Literal, and vowels are Set Literal. 
To know more about the Literal Collections refer to Python Data Types

Difference between a Variable, Constant and Literal 

VariablesConstantsLiterals
Variable is the name of the memory location where the data is stored.A constant is a variable whose value cannot be changedLiterals are raw values or data that are stored in a variable or constant 
Variables are mutable i.e their values can be changed or updatedConstants are immutable  i.e their values cannot be changedLiterals are mutable or immutable depending upon the Literal type. 
Example :number = 1Here number is a variableExample SPEED_OF_LIGHT = 343Here SPEED_OF_LIGHT is constantExample: s = ‘takeuforward’s is the string Literal

Special thanks to SaiSri Angajala for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this articleIf you want to suggest any improvement/correction in this article please mail us at [email protected]