Python Introduction

Python Variables, Constants and Literals

The basis of a programming language contains data elements and the block in which they are being stored. Specific names are given for each of these, and special functionalities can be performed on them. In a programming language, they are called as Variables, Constants, and Literals. In this article, we will look at Python Constants, Variables, and Literals along with their types and examples.

Python Variables

  • A Variable is a location that is named in order to store data while the program is being run.
  • In a programming language, Variables are words that are used to store values of any data type.

In simple words, when you create a variable, it takes up some memory space based on the value and the type you set to it. The Python interpreter allocates RAM to the variable based on its data type. The variables’ values can be altered at any time during the program.

An Identifier is a term used in programming language in order to denote unique name given to these variables.

Syntax

                    

variable_name = data values

where, variable_name = combination of letters, numbers and an underscore

Note – In Python, we do not specify the data type for the variable. Python automatically understands which data type is being used and allocates memory space accordingly.

Rules to be followed while declaring a Variable name

  1. A Variable’s name cannot begin with a number. Either an alphabet or the underscore character should be used as the first character.
  2. Variable names are case-sensitive and can include alphanumeric letters as well as the underscore character.
  3. Variable names cannot contain reserved terms.
  4. The equal to sign ‘=’, followed by the variable’s value, is used to assign variables in Python.

Assigning values to Variables in Python

There are few different methods to assign data elements to a Variable. The most common ones are described below –

  1. Simple declaration and assignment of a value to the Variable

In this type, the data values are directly assigned to the Variables in the declaration statement.

Example

                    

num = 10
numlist = [1, 3, 5, 7, 9]
str = 'Hello World'

print(num)
print(numlist)
print(str)

Output

                    

10
[1, 3, 5, 7, 9]
Hello World

Here, we have created 3 variables named as ‘num’, ‘numlist’, and ‘str’. We have assigned all the 3 variables an int value 10, a list of integers, and a string of characters respectively.

  1. Changing the value of a Variable

Data values assigned to the variables can be changed at any time. In Layman language, you can think of a Variable as a bag to store items and these items can be replaced at any time.

Example

                    

val = 50
print("Initial value:", val)

val = 100   # assigning new value
print("Updated value:", val)

Output

                    

Initial value: 50
Updated value: 100

In the above program, initially the value of Variable ‘val’ was 50. Later it was reassigned to a value of 100.

  1. Assign multiple values to multiple Variables

In Python, we can assign multiple values to multiple variables in the same declaration statement by using the following method –

Example

                    

name, age, city = 'David', 27, 'New York'

print(name)
print(age)
print(city)

Output

                    

David
27
New York

We can also assign a single value to multiple variables. Let us look at the below example to understand this,

Example

                    

a = b = 'Hello'

print('Value of a:', a)
print('Value of b:', b)

Output –

                    

Value of a: Hello
Value of b: Hello

Python Constants

  • A Python Constant is a variable whose value cannot be changed throughout the program.

Certain values are fixed and are universally proven to be true. These values cannot be changed over time. Such types of values are called as Constants. We can think of Python Constants as a bag full of fruits, but these fruits cannot be removed or changed with other fruits. 

Note Unlike other programming languages, Python does not contain any constants. Instead, Python provides us a Capitalized naming convention method. Any variable written in the Upper case is considered as a Constant in Python.

Rules to be followed while declaring a Constant

  1. Python Constants and variable names should contain a combination of lowercase (a-z) or capital (A-Z) characters, numbers (0-9), or an underscore ( ).
  2. When using a Constant name, always use UPPERCASE, For example, CONSTANT = 50.
  3. The Constant names should not begin with digits.
  4. Except for underscore(_), no additional special character (!, #, ^, @, $) is utilized when declaring a constant.
  5. We should come up with a catchy name for the python constants. VALUE, for example, makes more sense than V. It simplifies the coding process.

Assigning Values to Constants

Constants are typically declared and assigned in a module in Python. In this case, the module is a new file containing variables, functions, and so on that is imported into the main file. Constants are written in all capital letters with underscores separating the words within the module.

We create a separate file for declaring constants. We then use this file to import the constant module in the main.py file from the other file.

Example

                    

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

                    

# main.py file
import constant as const

print('Value of PI:', cons.PI)
print('Value of Gravitational force:', cons.GRAVITY)

Output

                    

Value of PI: 3.14
Value of Gravitational force: 9.8

Python Literals

  • The data which is being assigned to the variables are called as Literal.
  • In Python, Literals are defined as raw data which is being assigned to the variables or constants.

Let us understand this by looking at a simple example,

                    

str = ‘How are you, Sam?’

Here, we have declared a variable ‘str’, and the value assigned to it ‘How are you, Sam?’ is a literal of type string.

Python supports various different types of Literals. Let us look at each one of them in detail.

Numeric Literals

Numeric Literals are values assigned to the Variables or Constants which cannot be changed i.e., they are immutable. There are a total of 3 categories in Numeric Literals. They are –  Integer, Float, and Complex.

Example

                    

# Int Numeric Literal
a = 30

# Float Numeric Literal
b = 40.67

# Complex Numeric Literal
c = 10+4j

print(a)
print(b)
print(c)
print(c.real, c.imag)

Output

                    

30
40.67
(10+4j)
10.0 4.0

To generate real and imaginary components of complex numbers, we utilize real literal (c.real) and imaginary literal (c.imag), respectively.

String Literals

A string literal is a series of characters surrounded by quotation marks. For a string, we can use single, double, or triple quotations. We can write multi-line strings or display them in the desired format by using triple quotes. A single character surrounded by single or double quotations is also known as a character literal.

Example

                    

string = 'Hello Guys'
multi_line = '''Hey
    There!!'''
char = 'Z'       

print(string)
print(multi_line)
print(char)

Output –

                    

Hello Guys
Hey
    There!!
Z

Boolean Literals

A Boolean Literal has either of the 2 values – True or False. Where True is considered as 1 and False is considered as 0.

Example

                    

boolean1 = (1 == True)
boolean2 = (1 == False)

num = 20
age = 20

x = True + 10
y = False + 50

print(boolean1)
print(boolean2)

print(num==age)

print('Value of x:', x)
print('Value of y:', y)

Output

                    

True
False
True
Value of x: 11
Value of y: 50

True indicates a value of 1 in Python, while False represents a value of 0. Because 1 equals True, the value of boolean1 is True. And as  1 does not equal False, the value of boolean2 is False. Similarly, we can utilize True and False as values in numeric expressions.

Special Literals

Python provides a special kind of literal known as None. We use this type of Literal in order to specify the field has not been created. It also denotes the end of a list in Python.

Example

                    

soap = "Available"
handwash = None

def items(x):
    if x == soap:
        print('Soap:', soap)
    else:
        print('Soap:', handwash)

items(soap)
items(handwash)

Output

                    

Soap: Available
Soap: None

In the above program, we define a function named ‘item’. Inside the ‘item’ function, when we set the argument as ‘soap’ then, it displays ‘Available’. And, when the argument is ‘handwash’, it displays ‘None’.

Literal Collections

In Python, there are 4 different types of Literal Collections. They represent more complicated and complex data and assist Python scripts to be more extensible. Let us look at each one of them in detail.

  1. List Literals

The elements in a list are of many data types. The values in the List are surrounded by square brackets ([]) and separated by commas (,). List values can be changed i.e., they are mutable.

Example –

                    

cars = ['Tata', 'BMW', 'Audi', 'Ferrari']
student = ['John', 20, 9876432113, 'Mumbai']

print(cars)
print(student)

Output

                    

['Tata', 'BMW', 'Audi', 'Ferrari']
['John', 20, 9876432113, 'Mumbai']

  1. Tuple Literals

Just like a List, a tuple is also a collection of various data types. It is surrounded by parentheses ‘(),’ and each element is separated by a comma (,). It is unchangeable (immutable).

Example –

                    

num = (1, 2, 4, 5, 7, 8)
student = ('John', 20, 9876432113, 'Mumbai')

print(num)
print(student)

Output –

                    

(1, 2, 4, 5, 7, 8)
('John', 20, 9876432113, 'Mumbai')

  1. Dict Literals

The data is stored in the dictionary as a key-value pair. It is surrounded by curly braces ‘{}‘, and each pair is separated by commas (,). A dictionary can hold various types of data. Dictionaries are subject to change.

Example –

                    

student = {'Name':'David', 'Age':22, 'Sex':'Male', 'City':'California', }
print(student)

print(student.keys())
print(student.values()))

Output

                    

{'Name': 'David', 'Age': 22, 'Sex': 'Male', 'City': 'California'}

dict_keys(['Name', 'Age', 'Sex', 'City'])
dict_values(['David', 22, 'Male', 'California'])

  1. Set Literals

Set is an unordered data set collection. It is surrounded by and each element is separated by a comma (,).

Example

                    

vowels = {'a', 'e', 'i', 'o', 'u'}
print(vowels)

chars = {'a', 'b', 'a', 'e', 'z', 'z', 'x'}
print(chars)  # Sets has no duplicate elements

Output

                    

{'o', 'i', 'u', 'e', 'a'}
{'x', 'b', 'z', 'e', 'a'}

Frequently Asked Questions

Q1. Are there Constants in Python?

Unlike other programming languages like C, C++, Java; Python does not contain any constants. Instead, Python provides us a Capitalized naming convention method. Any variable written in the Upper case is considered as a Constant in Python.

ConstantError will be generated if you attempt to update the constant value. You can also set dict and list values to the const module to make them uneditable. Unlike a variable, deleting option is disallowed for constants

Q2. What are constants in Python?

In the Python programming language, Constants are types of variables whose values cannot be altered or changed after initialization. These values are universally proven to be true and they cannot be changed over time. Generally, python constants are declared and initialized on different modules/files.

Q3. How do you create a constant in Python?

The most important point we have to take into consideration while creating a constant in Python is that we need to create a separate python file for declaring constants and then importing this file in the main.py file. Let us understand python constants by looking at the below example.

Example

                    

# constant.py file
PI = 3.14

                    

# main.py file
import constant
print(‘Value of PI:’, constant.PI)

Output

                    

Value of PI: 3.14

Q4. What is the basic difference between a variable, constant, and a literal in Python?

Variables Constants Literals
A variable is a named location in memory where data is stored A constant is a variable whose value cannot be modified. Literals are raw values or data that are stored in a variable or constant.
Variables are mutable, i.e., their values can be changed and updated. Constants are immutable, i.e. their values cannot be changed or updated. Literals are both mutable or immutable depending on the type of literal used.
For example –

num = 50

Here, num is the variable

For example –

GRAVITY = 9.8

Here, GRAVITY is the constant

For example –

str = ‘Hello’

Here, ‘Hello’ is literal.

It is a string literal

Q5. What are the rules and conventions to be followed while naming a variable or constant?

Python programming language incorporates certain rules which should be followed while declaring a Variable or a Constant in the program. They are listed as follows –

  1. Constant and variable names should contain a combination of lowercase (a-z) or capital (A-Z) characters, numbers (0-9), or an underscore ( ).
  2. If you want to use underscore to separate two words in a variable name, do so.
  3. To declare a constant, use all capital letters as feasible.
  4. Never use special characters such as !, @, #, $, %, and so on.
  5. A variable/constant name should never begin with a number.
Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

Your email address will not be published. Required fields are marked *

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.