Python SS One Content
Python SS One Content
Certainly! Python is a popular high-level programming language known for its simplicity,
readability, and versatility. It's widely used for web development, data analysis, scientific
computing, automation, artificial intelligence, and more. Here's a brief introduction to some
key aspects of Python:
1. Syntax and Readability: Python emphasizes clean and readable code by using
indentation (whitespace) to define blocks of code, rather than relying on curly braces
or other symbols. This forces programmers to write code that is consistent and easy to
understand.
2. Variables and Data Types: In Python, you can create variables without explicitly
declaring their types. Common data types include integers, floating-point numbers,
strings (text), lists, tuples, dictionaries, and more.
3. Control Structures: Python supports common control structures like if statements,
for and while loops. These structures allow you to control the flow of your program
based on conditions and iterate through data.
4. Functions: Functions in Python allow you to group code into reusable blocks. You
define functions using the def keyword and can pass arguments to them. Functions
can also return values using the return keyword.
5. Lists, Tuples, and Dictionaries:
• Lists are ordered collections of elements, and they can contain elements of
different data types.
• Tuples are similar to lists but are immutable, meaning their contents cannot be
changed after creation.
• Dictionaries are collections of key-value pairs. They allow you to access
values using their associated keys.
6. Object-Oriented Programming (OOP): Python supports OOP principles like
classes and objects. You can define your own classes with attributes (variables) and
methods (functions) that operate on those attributes.
7. Modules and Libraries: Python has an extensive standard library that provides built-
in modules for various purposes. Additionally, there is a vast ecosystem of third-party
libraries and frameworks that extend Python's capabilities. For example, numpy for
numerical computations, pandas for data manipulation, and matplotlib for data
visualization.
8. File Handling: Python can read and write files easily using built-in functions. You
can read text files, manipulate their content, and write new data to them.
9. Exception Handling: Python provides a way to handle exceptions (errors) using try
and except blocks. This helps to gracefully handle unexpected situations in your code.
10. Interactivity: Python can be run interactively using an interpreter or a Jupyter
Notebook. This allows you to experiment with code snippets, test ideas, and see
immediate results.
To get started with Python, you need to install it on your system. You can download the
Python interpreter from the official website (https://www.python.org/downloads/) and follow
the installation instructions for your operating system.
Once installed, you can write Python code in a text editor or integrated development
environment (IDE) and run it using the Python interpreter. Start with simple programs,
gradually exploring the language's features and syntax. There are also numerous online
resources, tutorials, and courses available to help you learn Python effectively.
Why Python:
1. Readability and Simplicity: Python's syntax is clear and easy to understand, making
it a great language for beginners and experienced programmers alike. Its use of
indentation enforces clean and consistent code.
2. Versatility: Python can be used for a wide range of applications, from web
development and data analysis to scientific research and artificial intelligence. Its
extensive library ecosystem provides tools for various tasks.
3. Community and Support: Python has a large and active community of developers,
which means you can find a wealth of resources, tutorials, and help online. This
community also contributes to the development of new libraries and tools.
4. Cross-Platform: Python is available on multiple operating systems, including
Windows, macOS, and Linux, ensuring your code can run on different platforms
without major modifications.
5. Integration: Python can be easily integrated with other programming languages,
allowing you to leverage existing code written in different languages.
6. Rapid Development: Python's high-level abstractions and dynamic typing make it
suitable for rapid prototyping and development, helping you bring your ideas to life
quickly.
Installation:
To start working with Python, you need to install it on your computer. Here's a basic guide to
installing Python:
Python comes with a built-in Integrated Development and Learning Environment (IDLE) that
provides a simple way to write and execute Python code. Here's how you can use Python
IDLE:
1. Opening IDLE: After installing Python, you can open IDLE by searching for "IDLE"
in your operating system's search bar and selecting the appropriate option.
2. Writing Code: In the IDLE window, you can start writing Python code directly.
Simply type your code and press Enter to execute it.
3. Running Code: To run a block of code, you can highlight it with your cursor and
press F5 or select "Run Module" from the "Run" menu.
4. Interactive Mode: IDLE also supports an interactive mode where you can enter
Python commands one by one and see their immediate results. This is useful for
experimenting with code.
5. Saving Files: You can save your code as Python files with the .py extension. Use the
"File" menu to create new files, open existing ones, and save your work.
Remember that while IDLE is a simple environment for learning and experimenting, as you
become more comfortable with Python, you might want to explore more feature-rich code
editors and integrated development environments (IDEs) like Visual Studio Code, PyCharm,
or Jupyter Notebook for more complex projects.
Week Two
PYTHON SYNTAX AND VARIABLES
Certainly! Let's dive into the basics of Python syntax and how to work with
variables:
print("Hello, world!")
3. Comments: Comments are used to annotate your code and provide explanations.
Single-line comments start with # , and multi-line comments are enclosed within triple
quotes (''' or """).
# This is a single-line comment
'''
This is a multi-line comment.
It can span multiple lines.
'''
4. Indentation Blocks: Control structures, functions, and classes are
defined using indentation blocks. A colon is used to indicate the start
of an indented block.
if x > 10:
print("x is greater than 10")
Variables in Python:
Variables are used to store and manage data in a program. In Python, you
don't need to declare the type of a variable explicitly; Python determines
the type based on the value assigned. Variable names should follow certain
rules:
• They can contain letters (both uppercase and lowercase), digits, and
underscores.
• They must start with a letter or an underscore.
• They are case-sensitive (e.g., ‘myVariable’ and ‘myvariable’ are different).
age = 25
age = age + 1 # Now age is 26
WEEK THREE
1. Numeric Types:
• int: Represents integers (whole numbers) like -3, 0, 42.
• float: Represents floating-point numbers (numbers with decimal
points) like 3.14, -0.5.
2. Text Type:
• str: Represents strings of characters. Strings are enclosed in single ( ' )
or double (") quotes.
3. Sequence Types:
• list: Represents ordered collections of items, which can be of different
data types. Lists are mutable (modifiable).
5. Set Types:
• set: Represents an unordered collection of unique elements. Sets are
enclosed in curly braces {}.
my_set = {1, 2, 3, 4}
6. Boolean Type:
• bool: Represents Boolean values True or False . Used in logical
operations and conditions.
is_student = True
has_car = False
7. None Type:
• None: Represents the absence of a value. It's often used to indicate the
absence of a meaningful result.
result = None
These are the fundamental built-in data types in Python. Understanding these types
and their characteristics is crucial for writing effective and correct programs.
Additionally, Python allows you to create your own custom data types using classes,
which is a fundamental concept in object-oriented programming.
To determine the data type of a variable, you can use the type() function:
age = 25
print(type(age)) # Output: <class 'int'>
name = "Alice"
print(type(name)) # Output: <class 'str'>
Remember that Python is dynamically typed, so variables can change their data type
during execution if you reassign them to different values.
WEEK FOUR
PYTHON CASTING
Casting, also known as type conversion or type casting, is the process of changing the data
type of a value from one type to another. Python provides built-in functions to perform type
casting between different data types. Here's how you can perform casting in Python:
1. Implicit Type Conversion: Python performs some automatic type conversions based
on the context. For example, when performing operations involving different numeric
types, Python may automatically convert them to a common type:
int_num = 5
float_num = 3.14
2. Explicit Type Conversion: Sometimes you need to explicitly convert values from
one type to another. Python provides built-in functions for explicit type conversion:
• int(): Converts a value to an integer.
float_num = 3.14
int_num = int(float_num) # Converts float to int
int_num = 5
float_num = float(int_num) # Converts int to float
num = 42
num_str = str(num) # Converts int to string
• list(), tuple(), set(): Converts a sequence type (like a list or tuple) to another
sequence type.
my_list = [1, 2, 3]
my_tuple = tuple(my_list) # Converts list to tuple
non_empty_list = [1, 2, 3]
bool_list = bool(non_empty_list) # Converts non-empty list to True
It's important to note that not all type conversions are valid. For example, converting a non-
numeric string to an integer will raise a ‘ValueError’ unless the string contains a valid
representation of an integer. Similarly, some conversions might lead to loss of information
(e.g., converting a floating-point number to an integer truncates the decimal part).
Always be cautious when performing type conversions to ensure that the resulting value
retains its intended meaning and behaviour.
WEEK FIVE
PYTHON STRINGS
In Python, strings are used to represent sequences of characters. They can contain letters,
digits, symbols, and whitespace. Strings are widely used for text processing, manipulation,
and representation. Here's an overview of working with strings in Python:
Creating Strings: Strings in Python can be created using single quotes (‘'’), double quotes
(‘"’), or triple quotes (‘'''’ or ‘"""’ ). Triple quotes are used for multi-line strings.
String Concatenation: Strings can be concatenated (joined together) using the + operator.
greeting = "Hello"
name = "Alice"
message = greeting + " " + name
print(message) # Output: Hello Alice
String Methods: Python provides a variety of built-in methods to manipulate and work with
strings. Some commonly used string methods include:
• join(): Joins elements of a list into a single string using a specified delimiter.
name = "Alice"
age = 30
greeting = "Hello, my name is {} and I am {} years old.".format(name, age)
These are just a few examples of the many string methods available in Python. Strings are a
fundamental part of Python programming, and understanding how to manipulate and work
with them is crucial for various applications, including text processing, formatting, and more.
WEEK SIX
PYTHON LISTS, PYTHON TUPLES
Sure, let's explore Python lists and tuples, two common sequence data types used to store
collections of items.
Python Lists: A list is a mutable, ordered collection of items, which can be of different data
types. Lists are created using square brackets ‘[]’.
• Access elements by index: Elements in a list are ordered, starting from index 0.
• Modify elements: Lists are mutable, so you can change the value of elements.
fruits[1] = "grape"
fruits.append("pear")
fruits.insert(1, "watermelon")
new_fruits = ["cherry", "kiwi"]
fruits.extend(new_fruits)
Python Tuples: A tuple is an immutable, ordered collection of items, similar to a list but its
elements cannot be changed after creation. Tuples are created using parentheses () .
point = (3, 4)
coordinates = (-1.5, 2.7)
mixed_tuple = (1, "hello", 3.14, False)
Tuples are often used when you have a collection of items that should not be modified after
creation. They provide structural integrity to the data.
# Accessing elements
print(point[0]) # Output: 3
# Unpacking tuples
x, y = point
print(x) # Output: 3
print(y) # Output: 4
Tuples are commonly used in situations where the position of each item has significance,
such as representing coordinates, dates, or other structured data.
Key Differences:
Both lists and tuples are important data types in Python, and your choice between them will
depend on whether you need the ability to modify the data or if you want to ensure the data
remains unchanged.
WEEK SEVEN
PYTHON SETS
A set in Python is an unordered collection of unique elements. Sets are used to store multiple
items, but unlike lists or tuples, sets don't allow duplicate values. Sets are created using curly
braces ‘{}’ or the built-in ‘set()’ constructor.
Creating Sets:
numbers = {1, 2, 3, 4, 5}
Set Operations: Sets support various operations, such as union, intersection, and difference.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2 # Returns {1, 2, 3, 4, 5}
• Intersection (‘&’): Returns elements that are common in both sets.
• Difference (‘-‘): Returns elements in the first set but not in the second set.
• Symmetric Difference (‘^’): Returns elements that are in either of the sets, but not in
both.
Sets are particularly useful when you want to maintain a collection of unique elements and
perform operations like intersection, union, and difference. They are often used for tasks
involving membership testing and handling distinct items in a dataset.
WEEK EIGHT
PYTHON DICTIONARIES
Creating Dictionaries:
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
grades = {
"math": 95,
"science": 85,
"history": 70
}
name = person["name”] # Access the value associated with the key "name"
Dictionary Methods:
• ‘get()’: Retrieves the value associated with a key. If the key doesn't
exist, it returns a default value (or ‘None’ if not provided).
age = person.pop("age”) # Removes the key "age" and returns the value 31
• ‘update()’:
Updates the dictionary with new key-value pairs from
another dictionary.
Dictionaries are commonly used to store structured data where each piece
of information is associated with a specific key. They are particularly useful
when you want to quickly access values using a descriptive label (the key)
rather than an index.
WEEK NINE
PYTHON CONDITIONS
Conditions in Python are used to control the flow of a program based on whether certain
conditions are met or not. Python provides various conditional statements and control
structures to implement conditions. Here's an overview of how conditions work in Python:
If Statement: The basic building block of conditions is the if statement. It allows you to
execute a block of code if a specified condition is true.
x = 10
if x > 5:
print("x is greater than 5")
If-Else Statement: You can extend the if statement with an else block to execute different
code when the condition is false.
x=3
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
Elif Statement: The ‘elif’ (short for "else if") statement allows you to check multiple
conditions in a single block.
x=5
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is equal to 5")
else:
print("x is less than 5")
Nested Conditions: You can nest conditional statements within each other to create more
complex branching logic.
x = 10
y=5
if x > 5:
if y > 2:
print("Both x and y are greater than their respective thresholds.")
else:
print("x is greater than 5, but y is not greater than 2.")
else:
print("x is not greater than 5.")
Logical Operators: Python also provides logical operators (and , or , not) to combine
conditions.
x = 10
y=5
if x > 5 or y > 2:
print("At least one condition is true.")
Ternary Operator: Python supports a concise way to write conditional expressions using
the ternary operator x if condition else y.
age = 15
Conditional statements are essential for controlling program execution based on different
conditions, making your code more dynamic and responsive. They are used extensively for
decision-making, error handling, and creating different branches of logic within your code.
WEEK ELEVEN
PYTHON LOOPS
In Python, loops are used to repeat a certain block of code multiple times.
Python provides two main types of loops: for loops and while loops. Here's
an overview of how loops work in Python:
For Loops: A for loop is used to iterate over a sequence (like a list, tuple, or
string) or other iterable objects. It runs a block of code a fixed number of
times, iterating through each element in the sequence.
You can also use the range() function to generate a sequence of numbers
and iterate over it:
for i in range(5):
print(i) # Output: 0, 1, 2, 3, 4
count = 0
for i in range(10):
if i == 5:
break
print(i) # Output: 0, 1, 2, 3, 4
• continue: Skips the rest of the current iteration and moves to the next
iteration.
for i in range(5):
if i == 2:
continue
print(i) # Output: 0, 1, 3, 4
• else with Loops: The else block can be used with loops to execute
code after the loop finishes normally (without encountering a break
statement).
for i in range(5):
print(i)
else:
print("Loop finished")
Nested Loops: You can nest one loop inside another to create complex
iterations.
for i in range(3):
for j in range(2):
print(i, j)
while True:
user_input = input("Enter 'quit' to exit: ")
if user_input == 'quit':
break
Loops are essential for automating repetitive tasks and processing
sequences of data. They allow you to efficiently execute the same block of
code multiple times, enhancing the functionality and interactivity of your
programs.
SECOND TERM
WEEK ONE
Python Functions
Functions are a powerful tool that can help you to write more organized and reusable
code. They can also help to improve the readability and maintainability of your code.
Function Syntax
In Python, you define a function using the def keyword, followed by the
function name, a pair of parentheses (), and a colon :. The function body is
indented, and it contains the code to be executed when the function is
called.
def my_function():
# Function body
print("Hello, world!")
Function Calling
To execute a function, you call it by its name followed by parentheses ().
Function Parameters
Functions can accept parameters (also known as arguments), which are
values that the function can use when it's called. Parameters are defined
inside the parentheses when declaring the function.
def greet(name):
print(f"Hello, {name}!")
Return Statement
Functions can return values using the return statement. This allows you to
compute a result inside the function and pass it back to the caller.
sum_result = add(5, 3)
print(sum_result) # Output: 8
Default Parameters
You can provide default values for function parameters. If a value is not
provided when calling the function, it will use the default.
def greet(name="Guest"):
print(f"Hello, {name}!")
Variable Scope
Variables defined inside a function have local scope, meaning they are only
accessible within that function. Variables defined outside of any function
have global scope and can be accessed from anywhere in the program.
def my_function():
local_variable = "I'm local"
print(global_variable) # Accessing a global variable
print(local_variable) # Accessing a local variable
my_function()
print(global_variable) # Still accessible
# print(local_variable) # This would result in an error; local_variable is not defined
here
Docstrings
It's good practice to include docstrings (documentation strings) in your
functions to explain their purpose and usage. Docstrings are enclosed in
triple quotes """.
square = lambda x: x ** 2
print(square(4)) # Output: 16
Function Decorators
Python allows you to use function decorators to modify or enhance the
behavior of functions. Decorators are typically used for tasks like logging,
authentication, or modifying the return value of a function.
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
Recursion
A function can call itself, a behavior known as recursion. Recursive functions
are useful for solving problems that can be broken down into smaller
instances of the same problem.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
Conclusion
Python functions are a fundamental part of Python programming, enabling
you to write reusable and organized code. By understanding function
syntax, parameters, scope, and advanced concepts like decorators and
recursion, you can leverage the power of functions to build complex and
efficient programs.
WEEK TWO
Python Lambda
Lambda functions are often used for short and simple operations, especially
when you need to pass a small function as an argument to another function
(e.g., sorting or filtering data).
result = add(5, 3)
print(result) # Output: 8
numbers = [1, 2, 3, 4, 5]
squared = map(lambda x: x ** 2, numbers)
students = [
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 22},
{"name": "Charlie", "age": 28},
]
print(students)
# Output:
# [{'name': 'Bob', 'age': 22},
# {'name': 'Alice', 'age': 25},
# {'name': 'Charlie', 'age': 28}]
Lambda functions are concise and convenient for short operations, but for
more complex functions, it's generally better to use regular named
functions defined with def. Lambda functions are best suited for situations
where you need a quick, throwaway function to perform a specific task.
WEEK THREE
Python Arrays
In Python, the most commonly used data structure for storing a collection
of items is the list, rather than an array. Lists in Python are versatile and
flexible, allowing you to store elements of different data types and change
their size dynamically. However, Python also provides an array module in its
standard library for working with arrays. Here's an overview of both lists
and arrays:
Lists in Python:
1. Creation: Lists are created using square brackets [], and you can
initialize them with elements.
my_list = [1, 2, 3, 4, 5]
2. Dynamic Size: Lists can grow or shrink dynamically. You can add
elements to a list using append() or extend() methods, and you can
remove elements using remove() or pop().
my_list.append(6) # Adds 6 to the end
my_list.extend([7, 8]) # Extends the list with [7, 8]
my_list.remove(4) # Removes the first occurrence of 4
my_list.pop() # Removes and returns the last element
4. Slicing: You can access elements in a list using slicing. Lists are zero-
indexed.
import array
int_array = array.array('i', [1, 2, 3, 4, 5])
2. Fixed Size: Arrays have a fixed size when created. You cannot change
their size dynamically by adding or removing elements.
3. Single Data Type: Unlike lists, arrays store elements of a single data
type specified when creating the array.
4. Performance: Arrays are more memory-efficient and faster for
certain operations (e.g., numerical computations) compared to lists.
However, this advantage is often negligible for most general-purpose
tasks.
5. Access: Elements in an array are accessed in the same way as lists,
using indexing and slicing.
6. Array Types: The array module supports various data types such as
integers ('i'), floating-point numbers ('f'), and characters ('u'),
among others.
WEEK FOUR
Python Classes/Objects
Classes:
A class is a blueprint or template for creating objects. It defines the
structure and behavior that objects of the class will have. Classes
encapsulate data (attributes) and functions (methods) that operate on that
data. To define a class in Python, you use the class keyword followed by
the class name:
class MyClass:
# Class attributes and methods go here
Objects (Instances):
An object is an instance of a class, created based on the class's blueprint.
You can create multiple objects from a single class. Each object has its own
data and can call the methods defined in the class. To create an object, you
call the class as if it were a function:
Attributes:
Attributes are data members or variables that belong to a class or its
instances. They represent the characteristics or properties of objects.
Attributes can be either class attributes (shared by all instances) or instance
attributes (specific to each instance). You define attributes inside the class.
class MyClass:
Methods:
Methods are functions defined inside a class that operate on its data
(attributes). Methods can be class methods (operate on class-level data) or
instance methods (operate on instance-specific data). The self parameter in
instance methods refers to the instance calling the method.
class MyClass:
def instance_method(self):
return "I am an instance method"
@classmethod
def class_method(cls):
return "I am a class method"
@staticmethod
def static_method():
return "I am a static method"
Constructor (__init__):
The __init__ method is a special method called a constructor. It is used to
initialize instance attributes when an object is created. The self parameter
refers to the instance being created, and you can assign values to instance
attributes inside this method.
class MyClass:
def __init__(self, name, age):
self.name = name
self.age = age
# Creating an object
my_object = MyClass("Alice", 30)
# Accessing attributes
print(my_object.name) # Output: Alice
print(my_object.age) # Output: 30
# Calling methods
result = my_object.instance_method()
print(result) # Output: I am an instance method
Inheritance:
Inheritance allows you to create a new class (subclass or derived class)
based on an existing class (base class or parent class). The subclass inherits
attributes and methods from the base class and can extend or override
them.
class ParentClass:
def method(self):
class ChildClass(ParentClass):
def method(self):
child = ChildClass()
Python's support for OOP makes it a versatile and powerful language for
building complex software systems. Classes and objects are central to this
capability, enabling you to create organized, reusable, and maintainable
code.
WEEK FIVE
Python Dates
In Python, you can work with dates and times using the datetime module
from the standard library. The datetime module provides classes and
functions for manipulating dates, times, and time intervals. Here's an
overview of how to work with dates in Python:
import datetime
current_datetime = datetime.datetime.now()
print(current_datetime)
# Output: 2023-08-24 12:34:56.789012 (This is the date and time you run the code)
Date Formatting
To format a datetime object as a string, you can use the strftime() method and
provide a format string:
formatted_date = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_date)
# Output: 2023-08-24 12:34:56
date_string = "2023-08-24"
parsed_date = datetime.datetime.strptime(date_string, "%Y-%m-%d")
print(parsed_date)
# Output: 2023-08-24 00:00:00
Date Arithmetic
You can perform various date arithmetic operations, such as adding or
subtracting days, hours, minutes, etc., to a datetime object:
Date Comparison
You can compare datetime objects to determine which date or time is earlier
or later:
Time Zones
Python's datetime module does not handle time zones by default. To work
with time zones, you can use external libraries like pytz.
import pytz
WEEK SIX
Python JSON
import json
data = {
"name": "Alice",
"age": 30,
"city": "New York"
}
You can also use the indent parameter to format the JSON string for better
readability:
print(loaded_data)
# Output: {'name': 'Alice', 'age': 30, 'city': 'New York'}
try:
python_object = json.loads(json_string)
except json.JSONDecodeError as e:
print(f"JSON decoding error: {e}")
WEEK SEVEN
Python PIP
pip is a package manager for Python that allows you to easily install,
manage, and remove Python packages (libraries and modules) from the
Python Package Index (PyPI) and other package repositories. It's a powerful
tool for managing Python dependencies and is typically included with
Python installations from version 3.4 and higher.
1. Installing Packages
To install a Python package using pip, open your command-line interface
(terminal or command prompt) and run the following command:
Replace package_name with the name of the package you want to install. For
example, to install the popular package requests, you would run:
This command will download and install the package and its dependencies.
pip list
This command will list all the packages installed in your Python
environment, along with their versions.
3. Uninstalling Packages
To uninstall a package, you can use the pip uninstall command followed by
the package name:
4. Updating Packages
To update a package to the latest version available on PyPI, you can use the
pip install --upgrade command:
5. Requirements Files
You can create a requirements file to list all the packages your project
depends on, along with their versions. This makes it easy to recreate the
same environment on another system or share your project's dependencies.
To generate a requirements file, you can use the pip freeze command:
To install all the packages listed in a requirements file, you can use the -r
option:
Once activated, you can use pip to install packages in the virtual
environment without affecting the global Python installation.
Always exercise caution when using pip, especially if you have administrative
privileges, to avoid accidentally modifying or deleting system packages.
Virtual environments can help isolate your project dependencies and
minimize conflicts.
WEEK EIGHT
File Handling Open, Read, Write, Create and Delete Files
After you're done with a file, it's essential to close it using the close()
method.
A safer way to open and close files is to use the with statement (context
manager), which automatically closes the file when you're done:
3. Writing to Files
To write data to a file, open it in write ('w' ) or append ('a' ) mode, then use
the write() method to write content to the file. Be cautious when using write
mode ('w') as it overwrites the file's existing content.
To delete a file, you can use the os.remove() function from the os module:
import os
file_to_delete = 'file_to_delete.txt'
if os.path.exists(file_to_delete):
os.remove(file_to_delete)
else:
print("The file does not exist.")
THIRD TERM
WEEK ONE
Python Modules
In Python, a module is a file that contains Python code, including functions, variables, and
classes, that can be reused in other Python scripts. Modules are a fundamental concept in
Python, allowing you to organize and encapsulate code for better maintainability and
reusability.
def greet(name):
return f"Hello, {name}!"
result = my_module.greet("Alice")
print(result) # Output: Hello, Alice!
result = greet("Bob")
print(result) # Output: Hello, Bob!
import my_module as mm
result = mm.greet("Charlie")
my_package/
__init__.py
module1.py
module2.py
result = module1.some_function()
Python modules and packages are essential for structuring and managing code in larger
projects, as they promote code reuse and maintainability. By encapsulating related code into
modules and packages, you can create more organized and modular Python applications.
WEEK TWO
Numpy
NumPy (Numerical Python) is a powerful Python library for numerical and mathematical
operations. It provides support for large, multi-dimensional arrays and matrices, along with a
vast collection of high-level mathematical functions to operate on these arrays. NumPy is a
fundamental library for data manipulation and scientific computing in Python.
Here are some key aspects of NumPy and how to use it:
1. Installing NumPy
NumPy is not included in the Python standard library, so you need to install it separately
using a package manager like pip. In your command-line interface, run the following
command:
import numpy as np
It's a common convention to import NumPy with the alias np for brevity.
3. NumPy Arrays
At the core of NumPy is the numpy.ndarray (array) object. NumPy arrays are similar to
Python lists, but they have some distinct features:
• Homogeneous Data: NumPy arrays store elements of the same data type, unlike
Python lists, which can store mixed data types.
• Fixed Size: The size of a NumPy array is fixed upon creation, and you cannot change
it dynamically.
• Efficient: NumPy arrays are more memory-efficient and faster than Python lists for
numerical computations.
my_list = [1, 2, 3, 4, 5]
my_array = np.array(my_list)
4. Array Operations
NumPy provides a wide range of mathematical and logical operations for arrays:
# Arithmetic operations
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
result = a + b
# Element-wise operations
squared = np.square(a)
sum_of_elements = np.sum(a)
mean_value = np.mean(a)
# Matrix operations
matrix_a = np.array([[1, 2], [3, 4]])
matrix_b = np.array([[5, 6], [7, 8]])
matrix_product = np.dot(matrix_a, matrix_b)
5. NumPy Functions
NumPy includes a plethora of mathematical and statistical functions:
# Trigonometric functions
sin_values = np.sin(np.pi / 2)
cos_values = np.cos(np.pi / 4)
# Statistics functions
mean = np.mean([1, 2, 3, 4, 5])
std_deviation = np.std([1, 2, 3, 4, 5])
6. Broadcasting
NumPy allows you to perform operations on arrays of different shapes through broadcasting,
which automatically expands smaller arrays to match the shape of larger ones. This makes it
easier to work with arrays of different dimensions.
NumPy is a fundamental library for scientific computing and data analysis in Python. It's an
essential tool for tasks involving numerical data, linear algebra, statistics, and more. By
mastering NumPy, you can efficiently handle large datasets and perform complex
mathematical operations in Python.
WEEK THREE
Pandas
Pandas is a powerful Python library for data manipulation and analysis. It provides easy-to-
use data structures (primarily DataFrame and Series objects) and functions to work with
structured data, making it an essential tool for data scientists, analysts, and engineers working
with tabular data. Pandas is built on top of the NumPy library and integrates well with other
data analysis libraries like Matplotlib and Scikit-Learn.
1. Installing Pandas
You can install Pandas using pip:
2. Importing Pandas
After installation, you can import Pandas into your Python script or Jupyter Notebook:
import pandas as pd
The common convention is to import Pandas with the alias pd for brevity.
import pandas as pd
# From a dictionary
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35]}
df = pd.DataFrame(data)
import pandas as pd
# From a list
my_list = [1, 2, 3, 4, 5]
series = pd.Series(my_list)
# From a dictionary
data = {'Alice': 25, 'Bob': 30, 'Charlie': 35}
series = pd.Series(data)
5. Viewing Data
Pandas provides methods for quickly inspecting and understanding your data:
• df.head(): Shows the first few rows of the DataFrame (default is 5 rows).
• df.tail(): Shows the last few rows of the DataFrame.
• df.shape: Returns the dimensions (rows, columns) of the DataFrame.
• df.info(): Provides information about the DataFrame, including data types and missing
values.
• df.describe(): Generates summary statistics for numerical columns.
9. Data I/O
Pandas supports a wide range of data input and output formats, including CSV, Excel, SQL
databases, JSON, and more. You can use functions like read_csv(), to_csv() , read_excel(),
to_excel(), and read_sql() to work with these formats.
Pandas is an invaluable tool for data manipulation, cleaning, and analysis in Python. It
simplifies many complex data tasks and is a foundational library for any data-related project
in Python.
WEEK FOUR
scipy
SciPy is an open-source library in Python used for high-level computations and data analysis.
It builds on the functionality provided by NumPy and provides additional tools for scientific
and technical computing. SciPy is organized into sub-packages that focus on specific
scientific domains, including optimization, integration, interpolation, signal processing, linear
algebra, statistics, and more.
1. Installing SciPy
You can install SciPy using pip, typically alongside NumPy:
2. Importing SciPy
Once installed, you can import SciPy and its sub-packages into your Python scripts or
notebooks:
import scipy
Example 2: Optimization
# Initial guess
initial_guess = [1, 1]
# Perform optimization
result = minimize(objective, initial_guess, method='BFGS')
print(f"Optimal solution: {result.x}")
Example 3: Interpolation
import numpy as np
from scipy.interpolate import interp1d
# Interpolate values
x_new = 2.5
y_new = f(x_new)
print(f"Interpolated value at {x_new}: {y_new}")
These are just a few examples of the many capabilities offered by SciPy. Depending on your
specific scientific or engineering task, you can explore the appropriate sub-packages and
functions within SciPy to perform advanced computations and analyses.
SciPy is widely used in fields like physics, engineering, biology, and data science, making it
an essential library for a wide range of scientific and technical applications in Python.
WEEK FIVE
scikit-learn
1. Installing scikit-learn
You can install scikit-learn using pip:
2. Importing scikit-learn
After installing, you can import scikit-learn into your Python scripts or
notebooks:
import sklearn
Transformers
Transformers are a subset of estimators that perform data
transformations. They can be used for tasks like feature scaling,
dimensionality reduction, and more. Transformers are often used in
combination with estimators to preprocess data before modeling.
Datasets
scikit-learn provides several datasets for practice and experimentation. You
can load datasets directly from scikit-learn or use external data sources.
Clustering
Clustering is the task of grouping similar data points together. scikit-learn
offers clustering algorithms such as K-means clustering and hierarchical
clustering.
Dimensionality Reduction
Dimensionality reduction techniques like Principal Component Analysis
(PCA) and t-Distributed Stochastic Neighbor Embedding (t-SNE) are
available in scikit-learn to help with visualization and feature selection.
6. Pipelines
Pipelines in scikit-learn allow you to combine transformers and estimators
into a single workflow. This is useful for creating a sequence of data
preprocessing steps followed by model training.
# Create a pipeline with data scaling and support vector machine classifier
pipe = Pipeline([
('scaler', StandardScaler()),
('svm', SVC())
])
# Make predictions
y_pred = pipe.predict(X_test)
WEEK SIX
Matplotlib
2. Importing Matplotlib
After installation, you can import Matplotlib into your Python scripts or
notebooks:
The common convention is to import Matplotlib with the alias plt for
brevity.
3. Basic Plotting
Matplotlib allows you to create a wide variety of plots, including line plots,
scatter plots, bar plots, histograms, pie charts, and more. Here's a simple
example of creating a line plot:
# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
4. Customizing Plots
Matplotlib provides extensive customization options for plots, including
setting colors, markers, line styles, legends, and more. You can customize
various aspects of the plot using functions like plot(), xlabel(), ylabel(),
title(), and many others.
6. Saving Plots
You can save your Matplotlib plots as image files (e.g., PNG, JPEG, PDF)
using the savefig() function:
plt.savefig('my_plot.png')
7. Advanced Features
Matplotlib offers advanced features for creating 3D plots, animations,
interactive plots, and more. For more complex visualizations, you can
explore libraries like Seaborn and Plotly, which are built on top of
Matplotlib and provide higher-level APIs for specific use cases.
8. Learning Resources
To become proficient in Matplotlib, you can explore the official Matplotlib
documentation and various online tutorials and books dedicated to data
visualization in Python.
WEEK SEVEN
Keras
1. Installing Keras
If you're using TensorFlow 2.x, you don't need to install Keras separately
because it's included as part of TensorFlow. You can install TensorFlow
using pip:
2. Importing Keras
After installing TensorFlow, you can import Keras from within TensorFlow:
import tensorflow as tf
from tensorflow import keras
model = keras.Sequential([
keras.layers.Dense(128, activation='relu', input_shape=(784,)),
keras.layers.Dropout(0.2),
keras.layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.save('my_model.h5')
loaded_model = keras.models.load_model('my_model.h5')
8. Pretrained Models
Keras provides access to various pretrained deep learning models, such as
VGG, ResNet, and Inception, that you can fine-tune for specific tasks.
9. Learning Resources
To learn more about Keras and deep learning, you can explore the official
TensorFlow documentation, online tutorials, and books dedicated to deep
learning with Keras and TensorFlow.
WEEK EIGHT
Tensorflow
1. Installing TensorFlow
You can install TensorFlow using pip. There are two major versions of
TensorFlow:
2. Importing TensorFlow
After installation, you can import TensorFlow into your Python scripts or
notebooks:
import tensorflow as tf
Tensors
Tensors are the fundamental data structures in TensorFlow. They are multi-
dimensional arrays that can hold both numerical data and other types of
data. Tensors flow through the computational graph, making it possible to
perform operations on them efficiently.
Eager Execution
TensorFlow 2.x introduced eager execution, which allows you to evaluate
operations immediately as they are called, similar to NumPy. This makes
TensorFlow code more intuitive and easier to debug.
Keras Integration
As of TensorFlow 2.0, Keras has been integrated as the official high-level
API for defining and training deep learning models. This simplifies the
process of building and training neural networks.
import tensorflow as tf
from tensorflow import keras
# Define a simple feedforward neural network
model = keras.Sequential([
keras.layers.Dense(64, activation='relu', input_shape=(784,)),
keras.layers.Dropout(0.2),
keras.layers.Dense(10, activation='softmax')
])
5. Model Deployment
TensorFlow provides tools and libraries for deploying trained models to
various platforms, including mobile devices and the web. TensorFlow
Serving is a dedicated system for serving machine learning models in
production.
7. Learning Resources
To learn more about TensorFlow, you can explore the official TensorFlow
documentation, tutorials, and online courses. TensorFlow has a large and
active community, so there are many resources available for both beginners
and experienced users.
TensorFlow is widely used in machine learning research and industry
applications, making it a valuable tool for building, training, and deploying
machine learning models. It supports a wide range of applications and has
extensive support for deep learning.