Table of Contents
ToggleIn Python, literals are the notation for representing fixed values in source code. Unlike variables, literals are static and do not change during the execution of a program. Python supports various types of literals, including integer, float, complex, string, list, tuple, and dictionary literals. In this guide, we’ll explore each type of literal with examples.
Integer literals represent whole numbers and can be written in decimal, octal, or hexadecimal formats. Python treats all integer literals as objects of the int type.
# Decimal Literal
x = 10
print(x, type(x)) # Output: 10
# Octal Literal (prefixed with 0o or 0O)
y = 0o34
print(y, type(y)) # Output: 28
# Hexadecimal Literal (prefixed with 0x or 0X)
z = 0x1C
print(z, type(z)) # Output: 28
Float literals represent real numbers with a fractional part. They can be written in standard or scientific notation.
# Standard Float Literal
x = 25.55
print(x, type(x)) # Output: 25.55
# Scientific Notation
y = 1.23E5
print(y, type(y)) # Output: 123000.0
Complex literals represent complex numbers with a real and imaginary part. The imaginary part is suffixed with j or J.
# Complex Literal
x = 2 + 3j
print(x, type(x)) # Output: (2+3j)
String literals are sequences of characters enclosed in single, double, or triple quotes. They are immutable and belong to the str class.
# Single Quotes
x = 'Hello'
print(x, type(x)) # Output: Hello
# Double Quotes
y = "Hello"
print(y, type(y)) # Output: Hello
# Triple Quotes
z = '''Hello'''
print(z, type(z)) # Output: Hello
Lists, tuples, and dictionaries are collections of items. Lists and tuples are ordered, while dictionaries are unordered key-value pairs.
# List Literal
list1 = [1, "Ravi", 75.50, True]
print(list1, type(list1)) # Output: [1, 'Ravi', 75.5, True]
# Tuple Literal
tuple1 = (1, "Ravi", 75.50, True)
print(tuple1, type(tuple1)) # Output: (1, 'Ravi', 75.5, True)
# Dictionary Literal
dict1 = {"USA": "New York", "France": "Paris"}
print(dict1, type(dict1)) # Output: {'USA': 'New York', 'France': 'Paris'}
Using literals in your code makes it more readable and easier to understand. Always prefer literals over indirect methods like int() or str() when representing fixed values.
Python literals are a fundamental concept that allows you to represent fixed values in your code. By understanding the different types of literals and how to use them, you can write more efficient and readable Python programs.
Happy coding! 🚀
