No Widget Added

Please add some widget in Offcanvs Sidebar

Shopping cart

shape
shape

Python Literals

Python Literals

Python literals are fixed values that are assigned to variables or used directly in the code. They represent constant values and can be of various types such as numeric, string, boolean, special literals (None), and collection literals. Here’s a detailed explanation of each type with examples:

1. Numeric Literals

Numeric literals include integers, floating-point numbers, and complex numbers.

Integer Literals

decimal = 10          # Decimal (base 10)
binary = 0b1010       # Binary (base 2)
octal = 0o12          # Octal (base 8)
hexadecimal = 0xA     # Hexadecimal (base 16)

Floating-Point Literals

float_num = 10.5
float_exp = 1.5e2    # Exponential notation (equivalent to 1.5 * 10^2)

Complex Literals

complex_num = 3 + 5j

2. String Literals

String literals are sequences of characters enclosed in quotes. Python supports single, double, triple single, and triple double quotes.

Single-line Strings

single_quoted = 'Hello'
double_quoted = "World"

Multi-line Strings

triple_single = '''This is
a multi-line
string'''

triple_double = """This is also
a multi-line
string"""

Raw Strings

raw_string = r'C:\Users\name'

3. Boolean Literals

Boolean literals represent True and False.

is_true = True
is_false = False

4. Special Literal

Python has a special literal, None, representing the absence of a value.

no_value = None

5. Collection Literals

Python supports several types of collection literals including lists, tuples, dictionaries, and sets.

List Literals

empty_list = []
number_list = [1, 2, 3, 4, 5]
string_list = ["apple", "banana", "cherry"]
mixed_list = [1, "Hello", 3.14, None]

Tuple Literals

empty_tuple = ()
number_tuple = (1, 2, 3, 4, 5)
string_tuple = ("apple", "banana", "cherry")
mixed_tuple = (1, "Hello", 3.14, None)

Dictionary Literals

empty_dict = {}
person = {"name": "John", "age": 30, "city": "New York"}

Set Literals

empty_set = set()
number_set = {1, 2, 3, 4, 5}
string_set = {"apple", "banana", "cherry"}

Examples of Using Literals in Code

# Numeric Literals
a = 10            # Integer literal
b = 3.14          # Floating-point literal
c = 2 + 3j        # Complex literal

# String Literals
single = 'Single-quoted string'
double = "Double-quoted string"
triple = """Triple-quoted string for multiple lines"""

# Boolean Literals
is_active = True
is_logged_in = False

# Special Literal
unknown = None

# Collection Literals
numbers = [1, 2, 3, 4, 5]        # List literal
coordinates = (10.0, 20.0)       # Tuple literal
person = {"name": "Alice", "age": 30}  # Dictionary literal
unique_ids = {101, 102, 103}     # Set literal

# Printing literals
print(a, b, c)
print(single)
print(double)
print(triple)
print(is_active)
print(unknown)
print(numbers)
print(coordinates)
print(person)
print(unique_ids)

Leave A Comment

Your email address will not be published. Required fields are marked *