Python Literals
Literals in Python refer to the data that is given in a variable or constant. Literals can be numbers, characters, or any other data type that has a fixed value. In Python, there are several types of literals that you can use in your programs. Understanding these literals is essential as they form the basic building blocks of any Python program.
Types of Python Literals
Python supports various types of literals, which can be broadly categorized into the following:
1. String Literals
String literals are sequences of characters enclosed within single quotes (' '
), double quotes (" "
), or triple quotes (''' '''
or """ """
). Triple quotes are generally used for multiline strings.
Code Example
# Single and Double Quote Strings
string1 = 'Hello, World!'
string2 = "Python Programming"
# Multiline String
multi_line_string = '''This is a
multiline string.'''
print(string1)
print(string2)
print(multi_line_string)
Output
2. Numeric Literals
Python supports three types of numeric literals: Integer, Float, and Complex.
- Integer literals are whole numbers without a decimal point.
- Float literals are numbers with a decimal point.
- Complex literals include a real and an imaginary part (e.g.,
3 + 4j
).
Code Example
# Integer Literal
integer = 100
# Float Literal
float_number = 10.75
# Complex Literal
complex_number = 3 + 4j
print(integer)
print(float_number)
print(complex_number)
Output
3. Boolean Literals
Boolean literals can have one of two values: True or False. These are used to represent truth values in logical operations and conditional statements.
Code Example
is_python_fun = True
is_sun_cold = False
print(is_python_fun)
print(is_sun_cold)
Output
4. Special Literal: None
Python includes a special literal called None
, which represents the absence of a value or a null value. It is often used to indicate that a variable is empty.
Code Example
value = None
print(value)
Output
5. Collection Literals
Python supports several collection literals like:
- List Literals: Created using square brackets
[]
and can hold different data types. - Tuple Literals: Created using parentheses
()
and are immutable. - Dictionary Literals: Created using curly braces
{}
with key-value pairs. - Set Literals: Created using curly braces
{}
and contain unique elements.
Code Example
# List Literal
list_example = [1, 2, 3, "Python"]
# Tuple Literal
tuple_example = (1, 2, 3, "Python")
# Dictionary Literal
dict_example = {'a': 1, 'b': 2}
# Set Literal
set_example = {1, 2, 3}
print(list_example)
print(tuple_example)
print(dict_example)
print(set_example)
Output
Literals in Python are a fundamental part of writing code. They represent constant values and are used to assign data to variables. Understanding the different types of literals, such as strings, numbers, booleans, and collections, is crucial for coding effectively in Python.