Python Data Types and Structures Guide
Python Data Types and Structures Guide
1. Numeric Types
Integers (int)
Integers represent whole numbers without any decimal point. They can be positive or negative.
• Example: age = 25
Floats represent real numbers that include a decimal point. They are used for more precise
calculations.
Complex numbers have a real part and an imaginary part, represented as a + bj where a and b
are floats, and j is the imaginary unit.
• Example: z = 3 + 4j
2. Sequence Types
Strings (str)
Strings are sequences of characters enclosed in single, double, or triple quotes. They are used to
represent text.
Lists (list)
Lists are ordered, mutable collections of items, which can be of mixed data types. They are
defined using square brackets.
Tuples (tuple)
Tuples are ordered, immutable collections of items. Once defined, their values cannot be
changed. They are defined using parentheses.
3. Mapping Type
Dictionaries (dict)
Dictionaries are unordered collections of key-value pairs. Each key must be unique, and they are
defined using curly braces.
4. Set Types
Sets (set)
Sets are unordered collections of unique items. They are defined using curly braces, but they do
not have key-value pairs like dictionaries.
Frozen sets are similar to sets but are immutable. Once created, their items cannot be changed.
5. Boolean Type
Booleans (bool)
Booleans represent one of two values: True or False. They are often used in conditional
statements.
6. None Type
None is a special data type that represents the absence of a value or a null value. It is often used
to signify that a variable has no value.
Data structures
Data structures in Python are ways to store and organize data so that it can be accessed and
modified efficiently. Python provides several built-in data structures, each with unique
characteristics and use cases. Here, we'll explore some of the most commonly used data
structures in Python: lists, tuples, sets, dictionaries, and more advanced structures like linked
lists, stacks, queues, and trees.
1. Lists
Lists are ordered, mutable collections that can hold a variety of data types. They are defined
using square brackets.
• Example:
•
• fruits = ["apple", "banana", "cherry"]
•
Lists allow for various operations like appending, inserting, removing, and slicing.
• Appending:
•
• [Link]("date") # ["apple", "banana", "cherry", "date"]
•
• Slicing:
•
• fruits[1:3] # ["banana", "cherry"]
•
2. Tuples
Tuples are ordered, immutable collections. They are defined using parentheses.
• Example:
•
• point = (10, 20)
•
3. Sets
Sets are unordered collections of unique items. They are defined using curly braces or the set()
function.
• Example:
•
• unique_numbers = {1, 2, 3, 4, 5}
•
• Union:
•
• set_a = {1, 2, 3}
• set_b = {3, 4, 5}
• set_c = set_a.union(set_b) # {1, 2, 3, 4, 5}
•
4. Dictionaries
Dictionaries are unordered collections of key-value pairs. They are defined using curly braces.
• Example:
•
• student = {"name": "John", "age": 21, "major": "Computer Science"}
•
• Accessing:
•
• name = student["name"] # "John"
•
Operators in Python
In Python, operators are special symbols or keywords that perform operations on one or
more operands (values or variables). They are fundamental to writing expressions and
making computations in Python. Here’s a comprehensive overview of the various types
of operators available in Python:
Comparison operators compare two values and return a boolean result (True or False).
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
Assignment operators assign values to variables and can also perform arithmetic
operations.
6. Identity Operators
7. Membership Operators
Membership operators test for membership in a sequence (such as lists, tuples, or strings).
Decision making
Decision-making in Python involves using conditional statements to execute different
blocks of code based on certain conditions. These conditions typically evaluate to
Boolean values (True or False). The primary constructs for decision-making in Python
are if, elif, and else statements.
1. if Statement
The if statement evaluates a condition, and if it is True, the block of code indented under
the if statement is executed.
o Syntax:
o
o if condition:
o # Code to execute if the condition is true
o
o Example:
o
o age = 18
o if age >= 18:
o print("You are eligible to vote.")
o
2. if-else Statement
The if-else statement provides an alternative block of code to execute if the condition
is False.
o Syntax:
o if condition:
o # Code to execute if the condition is true
o else:
o # Code to execute if the condition is false
o
o Example:
o
o age = 16
o if age >= 18:
o print("You are eligible to vote.")
o else:
o print("You are not eligible to vote.")
o
The if-elif-else statement allows you to check multiple conditions sequentially. The
first condition that evaluates to True will have its corresponding block executed. If none
of the conditions are True, the else block is executed.
o Syntax:
o
o if condition1:
o # Code to execute if condition1 is true
o elif condition2:
o # Code to execute if condition2 is true
o elif condition3:
o # Code to execute if condition3 is true
o else:
o # Code to execute if none of the conditions are true
o
o Example:
o
o marks = 85
o if marks >= 90:
o print("Grade: A")
o elif marks >= 80:
o print("Grade: B")
o elif marks >= 70:
o print("Grade: C")
o else:
o print("Grade: D")
o
4. Nested if Statements
You can use nested if statements to check for conditions within conditions. This is
useful when you need to make more complex decisions.
o Syntax:
o
o if condition1:
o if condition2:
o # Code to execute if both condition1 and condition2 are
true
o
o Example:
o
o num = 10
o if num > 0:
o print("The number is positive.")
o if num % 2 == 0:
o print("The number is even.")
o
1. for Loop
The for loop in Python is used to iterate over a sequence (like a list, tuple,
dictionary, set, or string) and execute a block of code for each element in the
sequence.
▪ Syntax:
▪
▪ for item in sequence:
▪ # Code to execute for each item
▪
▪ Example:
▪
▪ fruits = ["apple", "banana", "cherry"]
▪ for fruit in fruits:
▪ print(fruit)
▪
▪ Range Function: Often used with for loops to generate a sequence of
numbers.
▪
▪ for i in range(5):
▪ print(i) # Output: 0, 1, 2, 3, 4
▪
2. while Loop
▪ Syntax:
▪
▪ while condition:
▪ # Code to execute while the condition is true
▪
▪ Example:
▪
▪ count = 0
▪ while count < 5:
▪ print(count)
▪ count += 1
4. Nested Loops
Loops can be nested, meaning you can have a loop inside another loop. Each time
the outer loop executes, the inner loop runs completely.
▪ Example:
▪
▪ for i in range(3):
▪ for j in range(2):
▪ print(f"i = {i}, j = {j}")
▪ # Output:
▪ # i = 0, j = 0
▪ # i = 0, j = 1
▪ # i = 1, j = 0
▪ # i = 1, j = 1
▪ # i = 2, j = 0
▪ # i = 2, j = 1
▪
1. Defining a Function
Functions in Python are defined using the def keyword, followed by the
function name and parentheses containing any parameter
▪ Syntax:
▪
▪ def function_name(parameters):
▪ # Block of code
▪ return value # Optional
▪
▪ Example:
▪
▪ def greet(name):
▪ return f"Hello, {name}!"
▪
2. Calling a Function
▪ Example:
▪
▪ message = greet("Alice")
▪ print(message) # Output: Hello, Alice!
▪
Positional Arguments
Keyword Arguments
▪ Example:
▪
▪ result = add(a=5, b=3)
▪ print(result) # Output: 8
▪
Default Parameters
▪ Example:
▪
▪ def greet(name, message="Hello"):
▪ return f"{message}, {name}!"
▪
▪ print(greet("Alice")) # Output: Hello, Alice!
▪ print(greet("Bob", "Hi")) # Output: Hi, Bob!
▪
Variable-Length Arguments
▪ Example:
▪
▪ def summarize(*args, **kwargs):
▪ for arg in args:
▪ print(arg)
▪ for key, value in [Link]():
▪ print(f"{key}: {value}")
▪
▪ summarize(1, 2, 3, name="Alice", age=30)
▪ # Output:
▪ # 1
▪ # 2
4. Return Statement
The return statement is used to exit a function and return a value to the
caller.
▪ Example:
▪
▪ def square(x):
▪ return x * x
▪
▪ result = square(4)
▪ print(result) # Output: 16
▪
5. Lambda Functions
▪ Syntax:
▪
▪ lambda parameters: expression
▪
▪ Example:
▪
▪ square = lambda x: x * x
▪ print(square(5)) # Output: 25
▪
▪ Example:
▪
▪ def outer_function(text):
▪ def inner_function():
▪ print(text)
▪ return inner_function
▪
▪ closure = outer_function("Hello, World!")
▪ closure() # Output: Hello, World!
7. Docstrings
Docstrings are string literals that occur as the first statement in a function.
They are used to document the purpose and behavior of the function.
▪ Example:
▪
▪ def add(a, b):
▪ """
▪ Add two numbers.
▪
▪ Parameters:
▪ a (int): The first number.
▪ b (int): The second number.
▪
▪ Returns:
▪ int: The sum of a and b.
▪ """
▪ return a + b
▪
▪ print(add.__doc__)
▪
Exceptions handling
Exception handling in Python is a mechanism that allows you to
deal with runtime errors gracefully. Instead of letting the program
crash, you can catch exceptions, handle them, and continue
executing the program. This enhances the robustness and reliability
of your code. Python provides several constructs for exception
handling: try, except, else, finally, and custom exceptions.
The try block contains code that might raise an exception. The
except block contains code that handles the exception if one is
raised.
▪ Syntax:
▪
▪ try:
▪ # Code that might raise an exception
▪ except ExceptionType:
▪ # Code that runs if the exception occurs
▪
▪ Example:
▪ Syntax:
▪
▪ try:
▪ # Code that might raise multiple exceptions
▪ except ExceptionType1:
▪ # Code to handle ExceptionType1
▪ except ExceptionType2:
▪ # Code to handle ExceptionType2
▪
▪ Example:
▪
▪ try:
▪ result = int("hello")
▪ except ValueError:
▪ print("A ValueError occurred!")
▪ except ZeroDivisionError:
▪ print("A ZeroDivisionError occurred!")
▪
▪ Syntax:
▪
▪ try:
▪ # Code that might raise multiple exceptions
▪ except (ExceptionType1, ExceptionType2):
▪ # Code to handle both ExceptionType1 and
ExceptionType2
▪
▪ Example:
▪
▪ try:
▪ result = int("hello")
▪ except (ValueError, TypeError):
▪ print("Either a ValueError or TypeError
occurred!")
▪ Syntax:
▪
▪ try:
▪ # Code that might raise an exception
▪ except ExceptionType:
▪ # Code that runs if the exception occurs
▪ else:
▪ # Code that runs if no exceptions occur
▪
▪ Example:
▪
▪ try:
▪ result = 10 / 2
▪ except ZeroDivisionError:
▪ print("You can't divide by zero!")
▪ else:
▪ print(f"The result is {result}")
▪
▪ Syntax:
▪
▪ try:
▪ # Code that might raise an exception
▪ except ExceptionType:
▪ # Code that runs if the exception occurs
▪ else:
▪ # Code that runs if no exceptions occur
▪ finally:
▪ # Code that always runs
▪
▪ Example:
▪
▪ try:
▪ result = 10 / 2
▪ except ZeroDivisionError:
▪ print("You can't divide by zero!")
▪ else:
▪ print(f"The result is {result}")
▪ finally:
6. Raising Exceptions
You can raise exceptions using the raise keyword. This is useful
for creating custom exceptions or re-raising caught exceptions.
▪ Syntax:
▪
▪ raise ExceptionType("Error message")
▪
▪ Example:
▪
▪ def check_age(age):
▪ if age < 0:
▪ raise ValueError("Age cannot be
negative")
▪ return age
▪
▪ try:
▪ check_age(-1)
▪ except ValueError as e:
▪ print(e) # Output: Age cannot be negative
▪
File handling
File handling in Python allows you to read from and write
to files on your system. This capability is essential for
many applications, from simple data logging to complex
data processing tasks. Python provides a built-in module
called open() to work with files, along with several
methods to perform operations on them. Here’s a
comprehensive guide to file handling in Python.
1. Opening a File
▪ Syntax:
▪
▪ file_object = open(file_name, mode)
▪
▪ Modes:
4. Appending to a File
▪ Example:
▪
▪ file = open("[Link]", "a")
▪ [Link]("\\nNew line appended.")
▪ [Link]()
▪
▪ Example:
▪
▪ with open("[Link]", "r") as file:
▪ content = [Link]()
▪ print(content)
▪
1. Classes
▪ Syntax:
▪
▪ class ClassName:
▪ # Class attributes and methods
▪
▪ Example:
▪
▪ class Dog:
▪ # Class attribute
▪ species = "Canis familiaris"
▪
▪ # Initializer / Instance
attributes
▪ def __init__(self, name, age):
▪ [Link] = name
▪ [Link] = age
▪
▪ # Instance method
▪ def description(self):
▪ return f"{[Link]} is
{[Link]} years old."
▪
▪ # Another instance method
▪ def speak(self, sound):
▪ return f"{[Link]} says
{sound}."
▪
2. Objects
▪ Syntax:
▪
▪ def __init__(self, parameters):
▪ # Initialization code
▪
▪ Example:
▪
▪ class Dog:
▪ def __init__(self, name, age):
▪ [Link] = name
▪ [Link] = age
▪
4. Instance Methods
▪ Example:
▪
▪ class Dog:
▪ def __init__(self, name, age):
▪ [Link] = name
▪ [Link] = age
▪
▪ def description(self):
▪ return f"{[Link]} is
{[Link]} years old."
7. Inheritance
▪ Syntax:
▪
▪ class ParentClass:
▪ # Parent class code
▪
▪ class ChildClass(ParentClass):
▪ # Child class code
▪
▪ Example:
▪
▪ class Animal:
▪ def __init__(self, name):
▪ [Link] = name
▪
▪ def speak(self):
▪ raise
NotImplementedError("Subclass must
implement abstract method")
▪
▪ class Dog(Animal):
▪ def speak(self):
▪ return f"{[Link]} says
Woof!"
▪
▪ class Cat(Animal):
▪ def speak(self):
▪ return f"{[Link]} says
Meow!"
▪
▪ dog = Dog("Buddy")
▪ cat = Cat("Kitty")
▪ print([Link]()) # Output: Buddy
says Woof!
▪ print([Link]()) # Output: Kitty
says Meow!
▪
8. Encapsulation
▪ Example:
▪
▪ class Car:
▪ def __init__(self, make, model,
year):
▪ self._make = make #
Protected attribute
▪ self.__model = model #
Private attribute
▪ [Link] = year
▪
▪ def get_model(self):
▪ return self.__model
▪
▪ my_car = Car("Toyota", "Camry",
2020)
▪ print(my_car._make) #
Output: Toyota
▪ # print(my_car.__model) #
Raises an AttributeError
▪ print(my_car.get_model()) #
Output: Camry
▪
9. Polymorphism
▪ Example:
▪
▪ class Animal:
▪ def speak(self):
▪ pass
▪
▪ class Dog(Animal):
▪ def speak(self):
▪ return "Woof!"
▪
▪ class Cat(Animal):
▪ def speak(self):
▪ return "Meow!"
▪
▪ animals = [Dog(), Cat()]
Libraries and
Modules in Python
In Python, libraries and modules are
collections of code that can be included and
reused in your programs. They help you
organize your code, avoid redundancy, and
make development faster by providing pre-
written functions and classes. Here’s an
overview of libraries, modules, and how to
use them effectively.
1. Modules
▪ Example:
▪
▪from mymodule import greet
▪
▪print(greet("Bob")) # Output:
Hello, Bob!
▪
2. Packages
3. Standard Library
4. Third-Party Libraries