0% found this document useful (0 votes)
8 views32 pages

Python Data Types and Structures Guide

The document provides an overview of Python data types, including numeric types, sequence types, mapping types, set types, boolean types, and the None type. It also discusses data structures such as lists, tuples, sets, and dictionaries, along with Python operators and decision-making constructs like if, elif, and else statements. This serves as a foundational guide for understanding Python programming concepts and syntax.

Uploaded by

prachi gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views32 pages

Python Data Types and Structures Guide

The document provides an overview of Python data types, including numeric types, sequence types, mapping types, set types, boolean types, and the None type. It also discusses data structures such as lists, tuples, sets, and dictionaries, along with Python operators and decision-making constructs like if, elif, and else statements. This serves as a foundational guide for understanding Python programming concepts and syntax.

Uploaded by

prachi gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Notes

[Link] / © Copyright 1stepGrow / All rights reserved


Data Types in python
In Python, data types are a fundamental concept that determine the kind of values that can be
stored and manipulated within the program. Python is a dynamically typed language, meaning
you don't need to declare the type of a variable explicitly. The interpreter infers the type based on
the value assigned. Here's an overview of the primary data types in Python:

1. Numeric Types

Integers (int)

Integers represent whole numbers without any decimal point. They can be positive or negative.

• Example: age = 25

Floating-Point Numbers (float)

Floats represent real numbers that include a decimal point. They are used for more precise
calculations.

• Example: temperature = 36.6

Complex Numbers (complex)

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.

• Example: name = "Alice"

Lists (list)

Lists are ordered, mutable collections of items, which can be of mixed data types. They are
defined using square brackets.

[Link] / © Copyright 1stepGrow / All rights reserved


• Example: fruits = ["apple", "banana", "cherry"]

Tuples (tuple)

Tuples are ordered, immutable collections of items. Once defined, their values cannot be
changed. They are defined using parentheses.

• Example: point = (10, 20)

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.

• Example: student = {"name": "John", "age": 21, "major": "Computer


Science"}

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.

• Example: unique_numbers = {1, 2, 3, 4, 5}

Frozen Sets (frozenset)

Frozen sets are similar to sets but are immutable. Once created, their items cannot be changed.

• Example: frozen_numbers = frozenset([1, 2, 3, 4, 5])

5. Boolean Type

Booleans (bool)

Booleans represent one of two values: True or False. They are often used in conditional
statements.

• Example: is_valid = True

6. None Type

[Link] / © Copyright 1stepGrow / All rights reserved


None (NoneType)

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.

• Example: result = None

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)

Tuples are useful for storing fixed collections of items.

[Link] / © Copyright 1stepGrow / All rights reserved


• Accessing:

• x = point[0] # 10

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}

Sets support operations like union, intersection, and difference.

• 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"}

Dictionaries allow fast access, addition, and deletion of key-value pairs.

• 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:

[Link] / © Copyright 1stepGrow / All rights reserved


1. Arithmetic Operators

Arithmetic operators perform mathematical operations like addition, subtraction,


multiplication, etc.

o Addition (+): Adds two operands.


o
o result = 10 + 5 # 15
o
o Subtraction (``): Subtracts the second operand from the first.
o
o result = 10 - 5 # 5
o
o Multiplication (``): Multiplies two operands.
o
o result = 10 * 5 # 50
o
o Division (/): Divides the first operand by the second (result is float).
o
o result = 10 / 5 # 2.0
o
o Floor Division (//): Divides and returns the integer part of the quotient.
o
o result = 10 // 3 # 3
o
o Modulus (%): Returns the remainder of the division.
o
o result = 10 % 3 # 1
o
o Exponentiation (*): Raises the first operand to the power of the second.
o
o result = 2 ** 3 # 8
o

2. Comparison (Relational) Operators

Comparison operators compare two values and return a boolean result (True or False).

o Equal (==): Checks if two operands are equal.


o
o result = (10 == 5) # False
o
o Not Equal (!=): Checks if two operands are not equal.
o
o result = (10 != 5) # True
o
o Greater Than (>): Checks if the first operand is greater than the second.
o
o result = (10 > 5) # True
o
o Less Than (<): Checks if the first operand is less than the second.

[Link] / © Copyright 1stepGrow / All rights reserved


o
o result = (10 < 5) # False
o
o Greater Than or Equal To (>=): Checks if the first operand is greater than or
equal to the second.
o
o result = (10 >= 5) # True
o
o Less Than or Equal To (<=): Checks if the first operand is less than or equal to
the second.
o
o result = (10 <= 5) # False
o

3. Logical Operators

Logical operators perform logical operations and return boolean results.

o AND (and): Returns True if both operands are true.


o
o result = (10 > 5 and 5 < 3) # False
o
o OR (or): Returns True if at least one operand is true.
o
o result = (10 > 5 or 5 < 3) # True
o
o NOT (not): Reverses the boolean value of the operand.
o
o result = not (10 > 5) # False
o

4. Bitwise Operators

Bitwise operators perform bit-level operations on binary numbers.

o AND (&): Performs bitwise AND.


o
o result = 10 & 5 # 0 (binary: 1010 & 0101)
o
o OR (|): Performs bitwise OR.
o
o result = 10 | 5 # 15 (binary: 1010 | 0101)
o
o XOR (^): Performs bitwise XOR.
o
o result = 10 ^ 5 # 15 (binary: 1010 ^ 0101)
o
o NOT (~): Performs bitwise NOT.
o
o result = ~10 # -11 (binary: ~1010)
o

[Link] / © Copyright 1stepGrow / All rights reserved


o Left Shift (<<): Shifts the bits of the first operand left by the specified number of
positions.
o
o result = 10 << 2 # 40 (binary: 1010 << 2 -> 101000)
o
o Right Shift (>>): Shifts the bits of the first operand right by the specified number
of positions.
o
o result = 10 >> 2 # 2 (binary: 1010 >> 2 -> 10)
o

5. Assignment Operators

Assignment operators assign values to variables and can also perform arithmetic
operations.

o Assignment (=): Assigns the right operand to the left operand.


o
o x = 5 # x is now 5
o
o Add and Assign (+=): Adds the right operand to the left operand and assigns the
result to the left operand.
o
o x += 3 # x is now 8 (5 + 3)
o
o Subtract and Assign (=): Subtracts the right operand from the left operand and
assigns the result to the left operand.
o
o x -= 2 # x is now 6 (8 - 2)
o
o Multiply and Assign (=): Multiplies the left operand by the right operand and
assigns the result to the left operand.
o
o x *= 4 # x is now 24 (6 * 4)
o
o Divide and Assign (/=): Divides the left operand by the right operand and assigns
the result to the left operand.
o
o x /= 3 # x is now 8.0 (24 / 3)
o
o Floor Divide and Assign (//=): Floor divides the left operand by the right
operand and assigns the result to the left operand.
o
o x //= 2 # x is now 4.0 (8.0 // 2)
o
o Modulus and Assign (%=): Takes the modulus using the left operand and the right
operand and assigns the result to the left operand.
o
o x %= 3 # x is now 1.0 (4.0 % 3)
o

[Link] / © Copyright 1stepGrow / All rights reserved


o Exponent and Assign (*=): Raises the left operand to the power of the right
operand and assigns the result to the left operand.
o
o x **= 2 # x is now 1.0 (1.0 ** 2)
o
o Bitwise AND and Assign (&=): Performs bitwise AND on the operands and
assigns the result to the left operand.
o
o x &= 2 # x is now 0 (1.0 & 2)
o
o Bitwise OR and Assign (|=): Performs bitwise OR on the operands and assigns
the result to the left operand.
o
o x |= 2 # x is now 2 (0 | 2)
o
o Bitwise XOR and Assign (^=): Performs bitwise XOR on the operands and
assigns the result to the left operand.
o
o x ^= 1 # x is now 3 (2 ^ 1)
o
o Left Shift and Assign (<<=): Performs left shift on the operands and assigns the
result to the left operand.
o
o x <<= 1 # x is now 6 (3 << 1)
o
o Right Shift and Assign (>>=): Performs right shift on the operands and assigns
the result to the left operand.
o
o x >>= 1 # x is now 3 (6 >> 1)
o

6. Identity Operators

Identity operators compare the memory locations of two objects.

o is: Returns True if the operands refer to the same object.


o
o result = (x is y) # True if x and y are the same object
o
o is not: Returns True if the operands do not refer to the same object.
o
o result = (x is not y) # True if x and y are not the same object
o

7. Membership Operators

Membership operators test for membership in a sequence (such as lists, tuples, or strings).

o in: Returns True if the value is found in the sequence.


o
o result = ("apple" in ["apple", "banana", "cherry"]) # True

[Link] / © Copyright 1stepGrow / All rights reserved


o
o not in: Returns True if the value is not found in the sequence.
o
o result = ("pineapple" not in ["apple", "banana", "cherry"]) #
True
o

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

[Link] / © Copyright 1stepGrow / All rights reserved


3. if-elif-else Statement

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

[Link] / © Copyright 1stepGrow / All rights reserved


Loops in python
Loops in Python are used to execute a block of code repeatedly, either for a
specific number of times or until a certain condition is met. The two primary
types of loops in Python are for loops and while loops. Understanding these
loops allows you to automate repetitive tasks and handle collections of data
efficiently.

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

The while loop in Python repeatedly executes a block of code as long as a


specified condition is True.

▪ Syntax:

▪ while condition:
▪ # Code to execute while the condition is true

▪ Example:

▪ count = 0
▪ while count < 5:
▪ print(count)
▪ count += 1

[Link] / © Copyright 1stepGrow / All rights reserved


3. Loop Control Statements

Python provides several control statements to alter the behavior of loops:

▪ break: Terminates the loop prematurely.



▪ for i in range(10):
▪ if i == 5:
▪ break
▪ print(i) # Output: 0, 1, 2, 3, 4

▪ continue: Skips the rest of the code inside the loop for the current iteration
and moves to the next iteration.

▪ for i in range(10):
▪ if i % 2 == 0:
▪ continue
▪ print(i) # Output: 1, 3, 5, 7, 9

▪ else: Can be used with for and while loops. The else block executes
when the loop terminates naturally (i.e., not by break).

▪ for i in range(5):
▪ print(i)
▪ else:
▪ print("Loop completed.") # Output: 0, 1, 2, 3, 4,
"Loop completed."

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

[Link] / © Copyright 1stepGrow / All rights reserved


Functions in Python
Functions in Python are blocks of reusable code that perform a specific
task. They allow for modular, organized, and more readable code.
Functions can accept inputs, perform operations, and return outputs.
Here's an overview of defining, using, and understanding functions in
Python.

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

You call a function by using its name followed by parentheses containing


any arguments.

▪ Example:

▪ message = greet("Alice")
▪ print(message) # Output: Hello, Alice!

3. Function Parameters and Arguments

Functions can accept various types and numbers of arguments. Parameters


are specified in the function definition, while arguments are the actual
values passed to the function.

Positional Arguments

Arguments passed to the function in the correct positional order.

[Link] / © Copyright 1stepGrow / All rights reserved


▪ Example:

▪ def add(a, b):
▪ return a + b

▪ result = add(5, 3)
▪ print(result) # Output: 8

Keyword Arguments

Arguments passed to the function by explicitly stating the parameter


name.

▪ Example:

▪ result = add(a=5, b=3)
▪ print(result) # Output: 8

Default Parameters

Parameters that assume a default value if no argument is provided.

▪ 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

Functions can accept an arbitrary number of arguments using *args for


positional arguments and **kwargs for keyword 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

[Link] / © Copyright 1stepGrow / All rights reserved


▪ # 3
▪ # name: Alice
▪ # age: 30

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

Lambda functions are small anonymous functions defined using the


lambda keyword. They can have any number of arguments but only one
expression.

▪ Syntax:

▪ lambda parameters: expression

▪ Example:

▪ square = lambda x: x * x
▪ print(square(5)) # Output: 25

6. Nested Functions and Closures

Functions can be nested within other functions. A closure occurs when a


nested function captures the local variables from its containing function.

▪ Example:

▪ def outer_function(text):
▪ def inner_function():
▪ print(text)
▪ return inner_function

▪ closure = outer_function("Hello, World!")
▪ closure() # Output: Hello, World!

[Link] / © Copyright 1stepGrow / All rights reserved


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.

1. The try and except Blocks

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:

[Link] / © Copyright 1stepGrow / All rights reserved



▪ try:
▪ result = 10 / 0
▪ except ZeroDivisionError:
▪ print("You can't divide by zero!")

2. Handling Multiple Exceptions

You can handle multiple exceptions by specifying different except


blocks for different exception types.

▪ 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!")

3. Catching Multiple Exceptions in a Single Block

You can catch multiple exceptions in a single except block by


enclosing them in parentheses.

▪ 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!")

[Link] / © Copyright 1stepGrow / All rights reserved


4. Using else with try-except

The else block is executed if no exceptions are raised in the try


block.

▪ 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}")

5. The finally Block

The finally block is always executed, whether an exception is


raised or not. It is typically used for cleanup actions.

▪ 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:

[Link] / © Copyright 1stepGrow / All rights reserved


▪ print("This will always be executed.")

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

The open() function is used to open a file. It requires at


least one argument: the file name. You can also specify the
mode in which the file is opened.

▪ Syntax:

▪ file_object = open(file_name, mode)

▪ Modes:

[Link] / © Copyright 1stepGrow / All rights reserved


▪ 'r':Read (default mode). Opens the file for
reading, raises an error if the file does not
exist.
▪ 'w': Write. Opens the file for writing,
creates a new file if it does not exist or
truncates the file if it exists.
▪ 'a': Append. Opens the file for appending,
creates a new file if it does not exist.
▪ 'b': Binary mode. Used with other modes to
read/write binary files.
▪ 't': Text mode (default mode). Used with
other modes to read/write text files.
▪ '+': Update mode. Opens the file for both
reading and writing.
▪ Example:

▪ file = open("[Link]", "r")

2. Reading from a File

There are several methods to read from a file in Python.

▪ read(size): Reads the specified number of bytes


from the file. If no size is specified, it reads the
entire file.

▪ file = open("[Link]", "r")
▪ content = [Link]()
▪ print(content)
▪ [Link]()

▪ readline(): Reads a single line from the file.

▪ file = open("[Link]", "r")
▪ line = [Link]()
▪ print(line)
▪ [Link]()

▪ readlines(): Reads all lines from the file and
returns them as a list.

▪ file = open("[Link]", "r")
▪ lines = [Link]()
▪ for line in lines:
▪ print([Link]())
▪ [Link]()

[Link] / © Copyright 1stepGrow / All rights reserved


3. Writing to a File

To write to a file, you need to open it in write ('w'),


append ('a'), or update ('+') mode.

▪ write(string): Writes the specified string to the


file.

▪ file = open("[Link]", "w")
▪ [Link]("Hello, World!")
▪ [Link]()

▪ writelines(lines): Writes a list of lines to the
file.

▪ lines = ["First line\\n", "Second
line\\n", "Third line\\n"]
▪ file = open("[Link]", "w")
▪ [Link](lines)
▪ [Link]()

4. Appending to a File

Appending data to an existing file can be done using the


append ('a') mode.

▪ Example:

▪ file = open("[Link]", "a")
▪ [Link]("\\nNew line appended.")
▪ [Link]()

5. Using with Statement

The with statement is used for resource management and


ensures that files are properly closed after their suite
finishes. This is the recommended way to handle files as it
ensures that the file is closed even if an exception occurs.

▪ Example:

▪ with open("[Link]", "r") as file:
▪ content = [Link]()
▪ print(content)

[Link] / © Copyright 1stepGrow / All rights reserved


Classess and Objects
In Python, classes and objects are fundamental
concepts of object-oriented programming (OOP).
They allow you to create custom data types and
organize code into reusable and modular structures.
Here's an in-depth look at classes and objects in
Python.

1. Classes

A class is a blueprint for creating objects. It defines


a set of attributes and methods that the objects
created from the class will have.

▪ 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

An object is an instance of a class. It is created from


a class and can access the attributes and methods
defined in the class.

[Link] / © Copyright 1stepGrow / All rights reserved


▪ Creating an Object:
▪ my_dog = Dog("Buddy", 3)

▪ Accessing Attributes and Methods:

▪ print(my_dog.name) # Output: Buddy
▪ print(my_dog.age) # Output: 3
▪ print(my_dog.description()) #
Output: Buddy is 3 years old.
▪ print(my_dog.speak("Woof")) #
Output: Buddy says Woof.

3. The __init__ Method

The __init__ method is a special method called a


constructor. It is automatically invoked when a new
object is created. It is used to initialize the object's
attributes.

▪ Syntax:

▪ def __init__(self, parameters):
▪ # Initialization code

▪ Example:

▪ class Dog:
▪ def __init__(self, name, age):
▪ [Link] = name
▪ [Link] = age

4. Instance Methods

Instance methods are functions defined inside a


class that operate on instances of the class (objects).
They take self as the first parameter, which refers
to the instance calling the method.

▪ Example:

▪ class Dog:
▪ def __init__(self, name, age):
▪ [Link] = name
▪ [Link] = age

▪ def description(self):
▪ return f"{[Link]} is
{[Link]} years old."

[Link] / © Copyright 1stepGrow / All rights reserved


5. Class Attributes vs. Instance Attributes

▪ Class Attributes: Shared among all


instances of a class. Defined outside the
__init__ method.
▪ Instance Attributes: Unique to each
instance. Defined inside the __init__
method.
▪ Example:

▪ class Dog:
▪ species = "Canis familiaris" #
Class attribute

▪ def __init__(self, name, age):
▪ [Link] = name #
Instance attribute
▪ [Link] = age #
Instance attribute

6. Class Methods and Static Methods

▪ Class Methods: Operate on the class itself,


rather than instances. Use the @classmethod
decorator and take cls as the first
parameter.
▪ Static Methods: Do not operate on either
class or instances. Use the @staticmethod
decorator and do not take self or cls as the
first parameter.
▪ Example:

▪ class Dog:
▪ species = "Canis familiaris"

▪ def __init__(self, name, age):
▪ [Link] = name
▪ [Link] = age

▪ @classmethod
▪ def common_species(cls):
▪ return [Link]

▪ @staticmethod
▪ def is_domesticated():
▪ return True

[Link] / © Copyright 1stepGrow / All rights reserved


▪ print(Dog.common_species()) #
Output: Canis familiaris
▪ print(Dog.is_domesticated()) #
Output: True

7. Inheritance

Inheritance allows a class to inherit attributes and


methods from another class. This promotes code
reuse and creates a hierarchical relationship
between classes.

▪ 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

[Link] / © Copyright 1stepGrow / All rights reserved


Encapsulation is the practice of keeping data
(attributes) and methods private, restricting access
to certain components of an object. This can be
achieved by prefixing attributes with an underscore
(_) or double underscore (__).

▪ 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

Polymorphism allows methods to do different


things based on the object it is acting upon, even
though they share the same name.

▪ 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()]

[Link] / © Copyright 1stepGrow / All rights reserved



▪ for animal in animals:
▪ print([Link]())
▪ # Output:
▪ # Woof!
▪ # Meow!

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

A module is a single file containing Python


code. It can include functions, classes,
variables, and runnable code. Modules allow
you to break down large programs into
manageable and organized files.

Creating and Using Modules

▪ Creating a Module: Create a file


named [Link]:

▪# [Link]

▪def greet(name):
▪ return f"Hello, {name}!"

▪ Using a Module: You can import
and use the module in another script.

▪# [Link]
▪import mymodule

▪print([Link]("Alice"))
# Output: Hello, Alice!

[Link] / © Copyright 1stepGrow / All rights reserved


Importing Specific Elements

You can import specific functions, classes,


or variables from a module using the from
keyword.

▪ Example:

▪from mymodule import greet

▪print(greet("Bob")) # Output:
Hello, Bob!

2. Packages

A package is a collection of related modules


organized in a directory hierarchy. It usually
contains an __init__.py file, which can be
empty or used to initialize the package.

Creating and Using Packages

▪ Creating a Package: Directory


structure:
▪markdownCopy code
▪mypackage/
▪ __init__.py
▪ [Link]
▪ [Link]

▪ Using a Package: You can import
modules from a package using dot
notation.

▪# [Link]
▪def foo():
▪ return "foo"

▪# [Link]
▪def bar():
▪ return "bar"

▪# [Link]
▪from mypackage import module1,
module2

▪print([Link]()) # Output:
foo

[Link] / © Copyright 1stepGrow / All rights reserved


▪print([Link]()) # Output:
bar

3. Standard Library

Python comes with a rich standard library


that provides many modules and packages
for various tasks, such as file I/O, system
calls, data serialization, mathematics, and
more.

Commonly Used Standard Library


Modules

▪ os: Provides functions for interacting


with the operating system.

▪import os

▪print([Link]) # Output:
'posix', 'nt', etc.

▪ sys: Provides access to some
variables used or maintained by the
interpreter.

▪import sys

▪print([Link]) # Output:
Python version info

▪ math: Provides mathematical
functions.

▪import math

▪print([Link](16)) # Output:
4.0

▪ datetime: Provides classes for
manipulating dates and times.

▪from datetime import datetime

▪now = [Link]()
▪print(now) # Output: Current
date and time

[Link] / © Copyright 1stepGrow / All rights reserved


▪ random: Provides functions for
generating random numbers.

▪import random

▪print([Link](1, 10)) #
Output: Random integer
between 1 and 10

4. Third-Party Libraries

Third-party libraries are not included in the


Python standard library but can be installed
using package managers like pip. They
extend Python’s functionality by providing
additional tools and frameworks.

Installing and Using Third-Party


Libraries

▪ Installing with pip:


▪bashCopy code
▪pip install requests

▪ Using a Third-Party Library:

▪import requests

▪response =
[Link]('<[Link]
[Link]>')
▪print(response.status_code) #
Output: 200

Popular Third-Party Libraries

▪ requests: Simplifies HTTP


requests.

▪import requests

▪response =
[Link]('<[Link]
[Link]>')
▪print([Link]())

▪ pandas: Provides data structures and
data analysis tools.

[Link] / © Copyright 1stepGrow / All rights reserved



▪import pandas as pd

▪data = {'name': ['Alice',
'Bob'], 'age': [25, 30]}
▪df = [Link](data)
▪print(df)

▪ numpy: Supports large, multi-
dimensional arrays and matrices,
along with a collection of
mathematical functions.

▪import numpy as np

▪array = [Link]([1, 2, 3])
▪print(array) # Output: [1 2 3]

▪ matplotlib: Plotting library for
creating static, animated, and
interactive visualizations.

▪import [Link] as plt

▪[Link]([1, 2, 3], [4, 5, 6])
▪[Link]()

▪ flask: Micro web framework for
building web applications.

▪from flask import Flask

▪app = Flask(__name__)

▪@[Link]('/')
▪def hello_world():
▪ return 'Hello, World!'

▪if __name__ == '__main__':
▪ [Link]()

[Link] / © Copyright 1stepGrow / All rights reserved

You might also like