Python Literals
In Python, literals are data that are directly assigned to a variable or constant. They are the fixed values that appear directly in the code. Think of literals as the simplest form of constant values, which the Python interpreter understands.
Python supports several types of literals:
1. Numeric Literals
a) Integer Literals
They are integers without a fractional part. They may be positive or negative.
Examples:
x = 10 # Decimal literal
y = 0b1011 # Binary literal (prefix: 0b or 0B)
z = 0o17 # Octal literal (prefix: 0o or 0O)
a = 0x1F # Hexadecimal literal (prefix: 0x or 0X)
- Decimal (base-10):
10, 100, -45
- Binary (base-2):
0b1010
- Octal (base-8):
0o17
- Hexadecimal (base-16):
0x1F
b) Floating-Point Literals
These are real numbers with either a decimal or an exponential part.
Examples:
pi = 3.14 # Decimal form
gravity = 9.8
exp = 1.2e3 # Scientific notation (1.2 * 10^3)
small = 1.2e-4 # Scientific notation (1.2 * 10^-4)
c) Complex Literals
Complex literals are used to represent complex numbers of the form a + bj
, where a
is the real part and b
is the imaginary part.
Examples:
z = 3 + 5j # A complex number
print(z.real) # Outputs: 3.0
print(z.imag) # Outputs: 5.0
2. String Literals
String literals are used to represent text, a sequence of characters. They are enclosed in:
- Single quotes
'.'
- Double quotes
"."
- Triple quotes
' ' '.' ' '
or"""."""
(used for multi-line strings).
Examples:
str1 = 'Hello' # Single-quoted string
str2 = "World" # Double-quoted string
str3 = '''Python is
great for programming.''' # Multi-line string
Special escape sequences in strings:
\n
: Newline\t
: Tab\\
: Backslash\'
and\"
: Single or double quotes
Example:
print("Hello\nWorld") # Outputs: Hello (newline) World
3. Character Literals
Python does not support a specific character type such as in other programming languages like C. It has a single character merely represented as a string with the length of 1.
Example:
char = 'A'
print(type(char)) # Outputs: <class 'str'>
4. Boolean Literals
Boolean literals can be written as True or False.
Examples:
is_python_fun = True
is_tired = False
print(5 > 3) # Outputs: True
5. Special Literal – None
None
is a special literal in Python which signifies absence of any value or it may be written as null.
Example:
x = None
print(x) # Outputs: None
6. Collection Literals
a) List Literals (square brackets [ ]
)
Store ordered, mutable collections of items.
fruits = ['apple', 'banana', 'cherry']
b) Tuple Literals (parentheses ( )
)
Used to store ordered, immutable collections.
coordinates = (10, 20, 30)
c) Dictionary Literals (curly braces { }
)
Used to store key-value pairs.
person = {'name': 'John', 'age': 25}
d) Set Literals (curly braces { }
with unique items)
Used to store unordered, unique items.
unique_numbers = {1, 2, 3, 3} # Outputs: {1, 2, 3}