Literals in Python
In Python, literals represent specific constant values that can be assigned to variables or utilized directly within expressions. These constant values come in various types, including numbers, strings, booleans, collections, and other unique identifiers. In contrast to the aforementioned variables, literals are immutable, indicating that once they have been defined, they cannot be altered.
Let us take a look at an example given below:
Example
x = 10 # Integer literal
print(x)
Output:
Here x = 10 is an integer literal.
Types of Literals
Literals are grouped under the following categories:
- Numeric Literals: Integers, floating points, and even complex numbers.
- String Literals: Literally any set of characters written in a string of quotes.
- Boolean Literals: The two most commonly accepted values, True or False.
- Collection Literals: Lists, tuples, dictionaries, and sets.
- Special Literal: The keyword None signifies the lack of value.
Each and every type of literal mentioned earlier holds significant value in Python programming. Therefore, understanding their application and characteristics is essential for any developer.
Numeric Literals
Numeric literals refer to values that can be represented within Python, as implied by their designation. These literals can take on various values and are classified into three distinct categories:
a) Integer (int)
Integer literals are defined as whole numbers without any decimals. They can be negative, positive or zero. Python also allows the use of various formats of integer literals.
- Decimal (Base 10): Uses digits 0-9 (e.g., 100, -5, 0).
- Binary (Base 2): Prefixed with 0b or 0B (e.g., 0b1010 for decimal 10).
- Octal (Base 8): Prefixed with 0o or 0O (e.g., 0o12 for decimal 10).
- Hexadecimal (Base 16): Prefixed with 0x or 0X (e.g., 0xA for decimal 10).
Example
integer_num = 10 # Decimal integer
binary_num = 0b1010 # Binary integer
octal_num = 0o12 # Octal integer
hexadecimal_num = 0xA # Hexadecimal integer
print(integer_num)
print(binary_num)
print(octal_num)
print(hexadecimal_num)
Output:
10
10
10
10
In the preceding example, we have declared several variables employing various representations of integer literals and subsequently displayed their values.
b) Floating-Point (float)
Floating-point literals are numerical values that include a decimal point or are expressed using scientific notation. They are essential for accurate computations involving fractional or real numbers.
- Standard floating-point representation: (for instance, 3.14, -0.99, 2.5)
- Scientific notation (exponential format): Utilizes e or E to signify powers of 10 (for example, 2.5e3 corresponds to 2500.0).
Example
float_num = 20.5 # Standard floating-point number
scientific_num = 2.5e3 # Equivalent to 2500.0
negative_float = -0.99 # Negative floating-point number
print(float_num)
print(scientific_num)
print(negative_float)
Output:
20.5
2500.0
-0.99
In the preceding illustration, we have set up several variables utilizing various floating-point literals and displayed their corresponding values.
c) Complex Numbers (complex)
Python includes support for complex numbers, which are made up of a real component and an imaginary component. The imaginary part is represented by the letter j or J.
2. String Literals
In Python, string literals are defined as sequences of characters that are enclosed within either single quotes (' '), double quotes (" "), or triple quotes (''' ''' or """ """). These literals serve the purpose of storing textual data, which can encompass anything from individual words and complete sentences to multi-line paragraphs.
Types of String Literals:
a) Single-Line Strings
These are contained within either single or double quotation marks and serve the purpose of representing brief textual information.
Example
single_string = 'Hello' # Single-quoted string
double_string = "Python" # Double-quoted string
print(single_string)
print(double_string)
Output:
Hello
Python
In the preceding example, we have set up several variables utilizing various styles of single-line string literals and subsequently displayed their respective values.
b) Multi-Line Strings
Multi-line strings are defined using triple single quotes (''' ''') or triple double quotes (""" """). This feature is particularly useful for representing text that extends over several lines, such as documentation or extensive blocks of text.
Example
# multi-line string
multi_string = """This is a multi-line string.
It can span multiple lines.
Useful for documentation and long texts."""
print(multi_string)
Output:
This is a multi-line string.
It can span multiple lines.
Useful for documentation and long texts.
In the preceding illustration, we have created a multi-line string literal and displayed its content.
c) Escape Characters in Strings
Python allows the use of escape characters to insert special characters within a string.
- \n - Newline
- \t - Tab
- \' - Single quote
- \" - Double quote
- \\ - Backslash
Example
escaped_string = 'Hello\nWorld' # Inserts a new line
print(escaped_string)
Output:
Hello
World
In the preceding illustration, a multi-line string literal has been created and its content has been displayed.
d) String Concatenation and Repetition
In Python, strings can be merged with the + operator, a process known as concatenation, and they can be duplicated using the * operator.
Example
string1 = "Hello "
string2 = "World"
concatenated = string1 + string2 # "Hello World"
repeated = string1 * 3 # "Hello Hello Hello"
print(concatenated)
print(repeated)
Output:
Hello World
Hello Hello Hello
In the preceding example, we initialized a pair of strings and subsequently carried out operations such as concatenation and repetition.
3.Boolean Literals
In Python, boolean literals signify truth values. There exist exclusively two boolean literals:
- True
- False
Example
is_python_fun = True # Boolean literal
is_raining = False
print(is_python_fun)
print(is_raining)
Output:
True
False
In the preceding example, we have declared and displayed two variables that hold Boolean values.
4. Collection Literals
Collection literals represent groupings of values and include the following types:
- List Literals: Ordered and mutable collection (e.g., [1, 2, 3]).
- Tuple Literals: Ordered and immutable collection (e.g., (1, 2, 3)).
- Dictionary Literals: Key-value pairs (e.g., {'name': 'Alice', 'age': 25}).
- Set Literals: Unordered collection of unique items (e.g., {1, 2, 3}).
Example
list_literal = [10, 20, 30] # List literal
tuple_literal = (10, 20, 30) # Tuple literal
dict_literal = {'a': 1, 'b': 2} # Dictionary literal
set_literal = {10, 20, 30} # Set literal
print(list_literal)
print(tuple_literal)
print(dict_literal)
print(set_literal)
Output:
[10, 20, 30]
(10, 20, 30)
{'a': 1, 'b': 2}
{10, 20, 30}
In the preceding illustration, we have created a list, a tuple, a dictionary, and a set, and subsequently displayed them for the users.
5. Special Literal
In Python, there exists a unique literal known as None, which signifies the lack of a value.
Example
value = None # Special literal
print(value)
Output:
In the previous illustration, we assigned a variable with a value of None and subsequently displayed it for the users.
Conclusion:
In Python, literals serve as essential components that denote fixed values within the code. These encompass various types of literals, including numeric literals (such as integers, floats, and complex numbers), string literals (which can be single-line or multi-line), Boolean literals (True and False), collection literals (like lists, tuples, dictionaries, and sets), as well as special literals (None). Grasping the concept of these literals is crucial for programmers aiming to craft code that is both clear and efficient. By utilizing the various forms of literals available, one can effectively manage and manipulate data while ensuring that the readability of the programs is upheld.
Literals in Python - FAQs:
1. What are the literals in Python?
In Python, literals are immutable values that are directly allocated to variables or utilized within expressions. They embody constant data types, including integers, strings, boolean values, collections, and unique values such as None.
2. What types of literals are in Python?
Python provides the following types of literals:
- Numeric Literals (Integer, Floating-Point, Complex)
- String Literals (Single line, multi-line)
- Boolean Literals (True, False)
- Collection Literals (Lists, Tuples, Dictionaries, Sets)
- Special Literal (None)
3. What is the difference between a string literal and a numeric literal?
A string literal signifies a sequence of characters that is surrounded by quotation marks, whereas a numeric literal denotes a numerical figure employed in arithmetic operations.
4. Can we use single and double quotes interchangeably for string literals?
Indeed, Python permits the use of both single (' ') and double (" ") quotation marks for the creation of strings. Nevertheless, it is important to maintain consistency in the choice of quotation marks throughout the same string.
5. What is the purpose of the 'None' literal?
In Python, the 'None' literal signifies the lack of a value or indicates a null value. It is frequently utilized as a stand-in for optional parameters or to denote that a variable has yet to be assigned a value.