Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
In this article, we will discuss about literals in Python, their types and their uses. Literals play an essential role in expressing data, such as numbers, strings, and Boolean values.
So let's dive in and discover the power of literals!
What are Literals in Python?
A literal in Python is a notation representing a fixed value in the Python source code. It is a way of declaring a value without using variables or expressions. Literals can be used to describe various data types of values, such as numeric, strings, and boolean values. Literals in python are of many types. Let us have a look on various types of literals.
There are various types of Literals on Python. Let’s Explore the diverse forms of literals that Python offers, from numeric literals and string literals to Boolean literals and more.
Types of literals in Python are -
Numeric Literals in Python
String Literals in Python
Boolean Literals in Python
Literal Collection
Special Literals in Python
Numeric Literals in Python
Numeric literals contain numeric values in Python. They include all the integer, float, long, or decimal values. Let us see some examples to better understand it.
Integer
In Python, an integer (int) is a data type used to represent whole numbers, both positive and negative, without any fractional part. Python's int type is of arbitrary precision, meaning it can grow as large as the memory allows.
number = 100 # This stores the whole number 100
Float
A float in Python is a data type used to store decimal (floating-point) numbers. It can represent numbers with a fractional part or numbers that have a decimal point. Floats are stored using double precision and typically require 8 bytes of memory.
decimal_number = 10.56 # This stores the decimal number 10.56
Long
In Python 2, the long type was used for larger integer values that exceeded the limits of int. However, in Python 3, int can handle arbitrarily large numbers, and the long type has been integrated into the int type. Therefore, there is no separate long type in Python 3.
large_number = 1000000000000 # Python 3 can handle large integers like this without needing a 'long' type
Decimal Values
In Python, the decimal module provides support for fast and precise decimal floating-point arithmetic. This is especially useful when exact precision is needed (e.g., in financial applications) to avoid rounding errors common with float.
To use the decimal data type, you need to import the decimal module. It allows for arbitrary precision when performing arithmetic operations.
from decimal import Decimal
precise_decimal = Decimal('3.14159265359') # This stores a more precise decimal value
As the name suggests, integer literals are used to store integer values like 47, 0, -985, etc. It can store binary, decimal, hexadecimal, or octal values as well.
String literals are used to store textual data in Python. They contain ASCII characters, including letters, special characters, or white spaces.
Single-line String
A single-line string is a sequence of characters enclosed in quotes and treated as a single line of text in programming. It typically does not span multiple lines and is used for straightforward text representation.
Let us see some examples.
Python
Python
str1 ="Coding Ninjas" print(str1)
You can also try this code with Online Python Compiler
The above code is an example of a single line string. As the name suggests, it stores a single line of data.
This will print Coding Ninjas as output
Multi-line String
A multi-line string is a sequence of characters enclosed in triple quotes or specific delimiters that spans multiple lines, allowing for the representation of text blocks with line breaks and indentation in programming.
If you want to store a multiple line string literal, we can code it as:
Python
Python
str1 ='''I am a ninja''' print(str1)
You can also try this code with Online Python Compiler
As you know, boolean values can only have two values, True or False. Therefore, boolean literals are predefined values as True and False. We can use it in conditional statements or loops like:
Implementation
Python
Python
num =1605
if num >1000: print("num is greater than 1000") else: print("num is less than or equal to 1000")
You can also try this code with Online Python Compiler
Here, c contains the True and False value; therefore, it will be False. And d has values of True or False. Hence it will generate output as True.
4. Literal Collection
In Python, literal collections are used to represent collections of values of the same or different data types. Python provides several types of literal collections, including lists, tuples, and dictionaries.
1. List literals
List literals are used to represent ordered sequences of values in Python. They are enclosed in square brackets, with each value separated by a comma. For example:
Tuple literals are similar to list literals, but they are enclosed in parentheses instead of square brackets. They also represent ordered sequences of values, but unlike lists, they are immutable (cannot be changed). For example:
The above code will generate a tuple literal and give output as:
3. Dictionary literals
Dictionary literals are used to represent mappings between keys and values in Python. They are enclosed in curly braces, with each key-value pair separated by a colon. For example:
The above code will generate the output as follows:
4. Set Literals
In addition to these literal collections, Python also provides other types of collections, such as sets and frozensets. Sets are unordered collections of unique values, while frozensets are immutable sets. Here is an example of a set literal:
Implementation
Python
Python
ninja_set ={1,2,3,4,5} print(ninja_set)
You can also try this code with Online Python Compiler
In Python, special literals are values that have a special meaning in the language. They are used to represent values that do not belong to any of the standard data types, such as integers, strings, or lists. In Python the special Literal is ‘None’.
It represents the absence of a value. It is often used to indicate that a variable has not been initialized or a function does not return a value. For example:
Implementation
Python
Python
ninja_var =None if ninja_var is None: print("ninja_var is not initialized") else: print("ninja_var is initialised")
You can also try this code with Online Python Compiler
As the ninja_var has None value, therefore, the output will be:
Uses of Literals in Python
Literals in Python are used to represent specific values of different data types. They are used for various purposes in Python programming, such as:
1. Assigning values to variables
Literal values are often used to assign values to variables in Python.
2. Passing arguments to functions
We can pass literal values as arguments to functions in Python.
3. Initializing data structures
We can initialize data structures such as lists, tuples, and dictionaries using literal values.
4. Comparing values
We can use literal values to compare with other values in Python.
5. Testing code
Literal values are also used for testing code in Python. By assigning literal values to variables, we can test the behavior of our code and ensure that it works correctly.
A sequence of characters enclosed in quotes (single or double).
A fixed value is directly expressed in the code.
Contains
It can be assigned to variables and manipulated using string methods.
Does not require assignment to a variable and represents data directly.
Modifications
It can be concatenated, sliced, and modified using various string operations.
It cannot be modified, as literals are immutable values.
Examples
Examples: "Hello, World!", 'Python is awesome!'
Examples: 42, 3.14, True, False
Usage
Used for representing textual data in Python.
Used for representing fixed values such as numbers, Booleans, and other constant data.
Frequently Asked Questions
What is an example of a literal in Python?
An example of a numeric literal is, say, 42 or for a string, it would be “John”, which represents the integer value 42. Literals are fixed values used to express data directly in the code.
What are the 3 literals in Python?
The three main literals in Python are numeric literals ( e.g., integers, floating point numbers like 42 ), string literals ( e.g., "hello", "john", "jane" ), and Boolean literals ( e.g., True, False ). They directly represent data within the code.
What is the literal 1 in Python?
Python has just two Boolean literals that, are True and False. In Python, True corresponds to the value 1, while False corresponds to the value 0.
What are two examples of literals?
Two examples of literals in Python are the string literal "Hello, world!" and the Boolean literal True. They directly represent a sequence of characters and a Boolean value, respectively, without the need for variables or expressions.
What is the difference between a literal and a datatype in Python?
A literal in Python refers to the data given in a variable or constant. It represents fixed values in the code like 2, "Hello", 3.14, etc whereas datatype in Python refers to the class of data that a variable can hold. Python has several data types like integers (int), floating-point numbers (float), strings (str), and others.