4, 5 Unit Notes
4, 5 Unit Notes
a. define file and list different types of file operations with example program.
A file is a named collection of related information that is stored on a computer's secondary storage, such
as a hard disk, CD-ROM, or USB drive. Files are organized in a hierarchical directory structure for easy
access and management. Different types of file operations allow users and programs to interact with
files in various ways. Here are some common file operations:
1. Opening a File: This operation establishes a connection between the file and the program. It allows
the program to read from or write to the file.
2. Reading from a File: This operation retrieves data from an opened file. Reading can be done
sequentially or randomly, depending on the file access mode.
3. Writing to a File: This operation stores data into an opened file. It can overwrite existing data or
append new data to the end of the file.
4. Closing a File: This operation terminates the connection between the file and the program. It ensures
that all data operations are completed and resources are freed up.
5. Seeking within a File: This operation moves the file pointer to a specific position within the file. It
allows for random access and editing of file contents.
Example:
file = open("myfile.txt", 'r')
file.seek(0)
file.close()
This will move our cursor to index position 0 & file reading will start from the start point again.
6. Renaming a File: This operation changes the name of a file in the file system. To rename our file, we
will use the .rename() method from the os module. The .rename() method takes two arguments:
The current file name, passed as a string type.
The renamed file name, to be passed as a string type.
Example:
import os
os.rename('myfile.txt', 'ourfile.txt')
7. **Deleting a File**: This operation removes a file from the file system.The os module has a
method .remove() which performs the task. The .remove() method takes a single argument as string
type which is our file name.
Ex: import os
os.remove('myfile.txt')
file = open('myfile.txt', 'r')
# Writing to a file
file.write("Hello, this is a sample text.\n")
file.write("Writing to files in Python is easy!\n")
This program demonstrates the basic file operations of opening, writing, reading, and closing a file using
Python's built-in file handling capabilities. Each programming language provides similar functionalities
through its file handling libraries or modules.
QUESTION -b) list and explain about different types of file modes with example program.
In programming, file modes specify how files should be opened and manipulated. Different modes allow
different operations on files, such as reading, writing, appending, etc. Here are the commonly used file
modes and their explanations:
- Opens a file for reading. The file must exist; otherwise, an error occurs.
- The file pointer is placed at the beginning of the file.
- Example:
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
```
- Opens a file for appending. If the file exists, new data is written at the end of the file. If the file does
not exist, it creates a new file.
- The file pointer is placed at the end of the file.
- Example:
file = open("example.txt", "a")
file.write("This is appended text.")
file.close()
- Opens a file for reading and writing. If the file exists, it truncates the file. If the file does not exist, it
creates a new file.
- The file pointer is placed at the beginning of the file.
- Example:
file = open("example.txt", "w+")
file.write("This is a sample text.")
file.seek(0) # Move the file pointer to the beginning
content = file.read()
print(content)
file.close()
6. Append and Read Mode (`"a+"`):
- Opens a file for reading and appending. The file is created if it does not exist.
- The file pointer is placed at the end of the file.
- Example:
```python
file = open("example.txt", "a+")
file.write("This is appended text.")
file.seek(0) # Move the file pointer to the beginning
content = file.read()
print(content)
file.close()
```
- This mode can be added to any of the above modes (e.g., `"rb"`, `"wb+"`, `"ab"`).
- It opens the file in binary mode, which is used for non-text files (e.g., images, executable files).
- Example:
file = open("image.jpg", "rb")
img_data = file.read()
# Process binary data
file.close()
```
These are the common file modes used in programming to control how files are opened and
manipulated. It's important to manage file operations properly, especially closing files after use to
release system resources and ensure data integrity.
NUMPY (NUMERICAL PYTHON) :
Describe the primary functionalities of the NumPy package in Python and its importance
in numerical computing.?
NumPy stands for numeric python which is a python package for the computation and
processing of the multidimensional and single dimensional array elements.
It is a powerful library in Python that provides support for large, multi-dimensional arrays and
matrices, along with a collection of mathematical functions to operate on these arrays
efficiently.
Travis Oliphant created NumPy package in 2005 by injecting the features of the ancestor
module Numeric into another module Numarray.
With the revolution of data science, data analysis libraries like NumPy, SciPy, Pandas, etc. have
seen a lot of growth. With a much easier syntax than other programming languages, python is
the first choice language for the data scientist.
NumPy provides a convenient and efficient way to handle the vast amount of data. NumPy is
also very convenient with Matrix multiplication and data reshaping. NumPy is fast which makes
it reasonable to work with a large set of data.
Let's delve into its primary functionalities and importance in numerical computing with examples:
1. Multi-dimensional Arrays
NumPy's primary data structure is the `ndarray`, a homogeneous array of fixed-size items.
These arrays can be of any dimension (1D, 2D, 3D, etc.) and can hold elements of the same data
type, which ensures efficient computation.
**Example:**
import numpy as np
a = np.array([1, 2, 3, 4, 5]) # Creating a 1-dimensional array
print(a)
Output: [1 2 3 4 5]
b = np.array([[1, 2, 3], [4, 5, 6]]) # Creating a 2-dimensional array (matrix)
print(b)
# Output:
# [[1 2 3]
# [4 5 6]]
2. Mathematical Functions:
NumPy provides a rich set of mathematical functions that operate element-wise on arrays,
which are optimized for performance.
These include basic arithmetic operations, such as addition, subtraction, multiplication, division,
and more complex operations like trigonometric, exponential, and statistical functions.
*Example:
import numpy as np
mean = np.mean(data)
print(mean)
# Output: 3.5
```
3. Broadcasting is a powerful mechanism that allows NumPy to work with arrays of different
shapes when performing arithmetic operations.
This means that operations between arrays of different sizes can be executed without explicitly
reshaping them, which saves time and memory.
**Example:
import numpy as np
print(c)
# Output:
# [[11 22 33]
# [14 25 36]]
```
4. Indexing and Slicing:
import numpy as np
# Output: 2
# Output: [2 5]
# Output: [4 5]
NumPy integrates seamlessly with other scientific computing libraries in Python, such as SciPy,
Matplotlib, pandas, and scikit-learn.
This interoperability enables comprehensive data analysis, visualization, and machine learning
workflows.
**Example:
import numpy as np
y = np.sin(x)
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('sin(x)')
plt.title('Sine Function')
plt.show()
NumPy's importance in numerical computing stems from its efficient implementation, extensive
functionality, and widespread adoption in the scientific community. It provides:
- **Performance**: NumPy operations are optimized and often executed in compiled C code, making
them much faster than equivalent Python operations on lists.
**Versatility**: It supports a wide range of numerical operations, from basic arithmetic to linear
algebra, Fourier transforms, and random number generation.
**Memory Efficiency**: NumPy arrays are more memory efficient than Python lists, which is crucial
when working with large datasets.
In essence, NumPy is essential for tasks involving numerical computation, data manipulation, and
scientific research due to its speed, versatility, and ease of integration with other libraries.
PANDAS :
Discuss the role of Pandas in data manipulation and analysis in Python, providing examples of its
usage.
Pandas, a powerful library in Python for data manipulation and analysis, primarily revolves
around two main data structures: `Series` and `DataFrame`.
These structures form the backbone of Pandas, allowing users to work with labeled and
relational data seamlessly.
Pandas data structures are foundational for performing data analysis tasks efficiently in Python,
making it a go-to choice for professionals and researchers working with structured data.
1. Series
A Pandas `Series` is a one-dimensional labeled array capable of holding data of any type (integer, float,
string, Python objects, etc.). It is similar to a NumPy array but with an additional labeled index, which
makes it more powerful for data manipulation.
**Creating a Series:**
import pandas as pd
s = pd.Series([1, 3, 5, 7, 9])
print(s)
Output:
0 1
1 3
2 5
3 7
4 9
dtype: int64
- The left column represents the index (automatically generated as integers by default).
2.DataFrame :
A Pandas `DataFrame` is a two-dimensional labeled data structure with columns of potentially different
data types. It can be thought of as a table in a relational database or a spreadsheet in Excel.
**Creating a DataFrame:**
data = {
df = pd.DataFrame(data)
print(df)
Output:
2 Charlie 35 Chicago
1. DataFrame Object: Pandas introduces the DataFrame, a two-dimensional labeled data structure
with columns of potentially different types. This structure resembles a spreadsheet or SQL table,
making it easy to manipulate and analyze tabular data.
2. Data Manipulation: Pandas provides a rich set of functions and methods for manipulating data.
This includes indexing, slicing, merging and joining datasets, reshaping, pivoting, and handling
missing data.
3. Data Cleaning: Pandas simplifies tasks such as removing or filling missing data, handling
duplicates, transforming data types, and filtering rows or columns based on conditions.
4. Grouping and Aggregation: Pandas supports powerful operations like group-by, which allows
for splitting data into groups based on criteria, applying functions to each group independently,
and combining the results.
5. Time Series Analysis: Pandas has robust support for working with time series data, including
date range generation, shifting and lagging time series, and frequency conversion.
6. Input/Output: Pandas can read data from and write to a wide range of file formats including
CSV, Excel, SQL databases, JSON, and HDF5.
- **Data Manipulation**: Pandas provides powerful tools for data cleaning, reshaping, and merging
datasets.
- **Data Exploration**: Allows for easy data indexing, slicing, and selection based on labels or
conditions.
- **Integration**: Integrates seamlessly with other libraries like NumPy, Matplotlib, and scikit-learn,
enabling comprehensive data analysis workflows.
− Django is a registered trademark of the Django Software Foundation, and is licensed under BSD
License History of Django
2003 − Started by Adrian Holovaty and Simon Willison as an internal project at the Lawrence Journal-
World newspaper.
2005 − Released July 2005 and named it Django, after the jazz guitarist Django Reinhardt.
Currently − Django is now an open source project with contributors across the world.
Django – Design Philosophies Django comes with the following design philosophies –
Loosely Coupled − Django aims to make each element of its stack independent of the others.
Don't Repeat Yourself (DRY) − Everything should be developed only in exactly one place instead of
repeating it again and again.
Clean Design − Django strictly maintains a clean design throughout its own code and makes it easy to
follow best web-development practices.
Advantages of Django Here are few advantages of using Django which can be listed out here –
Object-Relational Mapping (ORM) Support − Django provides a bridge between the data model and
the database engine, and supports a large set of database systems including MySQL, Oracle, Postgres,
etc. Django also supports NoSQL database through Djangononrel fork. For now, the only NoSQL
databases supported are MongoDB and google app engine.
Multilingual Support − Django supports multilingual websites through its built-in internationalization
system. So you can develop your website, which would support multiple languages.
Framework Support − Django has built-in support for Ajax, RSS, Caching and various other
frameworks.
Administration GUI − Django provides a nice ready-to-use user interface for administrative activities.
Development Environment − Django comes with a lightweight web server to facilitate end-to-end
application development and testing.
Django is a high-level Python web framework that enables rapid development of secure and
maintainable websites and web applications. It follows the principle of "Don't Repeat Yourself" (DRY)
and encourages rapid development and clean, pragmatic design.
1. MVC Architecture: Django follows the Model-View-Controller (MVC) architectural pattern, although it
is often referred to as MTV (Model-Template-View) in Django terminology. This separation of concerns
allows developers to structure their code logically and maintainably.
2. Object-Relational Mapping (ORM): Django provides a built-in ORM system that allows developers to
interact with databases using Python objects. This abstracts away the complexities of SQL queries and
facilitates database operations in a Pythonic way.
3. Admin Interface: Django comes with a powerful and customizable admin interface automatically
generated from the models defined in your application. It allows administrators to manage and update
data in the application without writing custom views or forms.
4. URL Routing: Django uses a flexible URL routing mechanism that helps developers design clean and
SEO-friendly URLs for their applications. URL routing is defined using regular expressions and mapped to
views (controller logic).
5. Template Engine: Django provides a robust template engine (using Django Template Language - DTL)
that allows developers to create HTML templates with minimal syntax and powerful template
inheritance.
6. Security: Django includes several built-in security features such as protection against SQL injection,
cross-site scripting (XSS), cross-site request forgery (CSRF), and clickjacking. It encourages secure coding
practices by default.
7.Authentication and Authorization: Django provides a flexible authentication system that allows users
to log in, log out, and manage their accounts. It also includes built-in support for permissions and user
groups, making it easy to control access to views and data.
8. Serialization: Django provides tools for serializing and deserializing Python objects (such as QuerySets
and model instances) into JSON, XML, or other formats, which is useful for building APIs and integrating
with frontend frameworks.
9. Internationalization and Localization: Django supports multiple languages and locales out-of-the-box,
allowing developers to create applications that can be easily translated into different languages.
- Settings: Configuration settings for the project (database settings, static files, middleware, etc.).
- URLs: URL routing configuration for the project.
- Models: Python classes that define data models and relationships (ORM).
- Views: Python functions or classes that handle HTTP requests and return responses.
- Templates: HTML files with Django Template Language for rendering UI.
- Static files: CSS, JavaScript, images, etc., used in the project.
1. Install Django: You can install Django using pip: pip install django
2. Create a Project: Create a new Django project using the command: django-admin startproject
myproject
3. Create Apps: Inside your project, create individual apps to handle different functionalities (e.g., users,
blog, shop).
4. Define Models: Define data models in each app to represent your application's data structure.
5. Write Views and Templates: Write views (controller logic) and templates (HTML files) to handle user
requests and render responses.
6. Configure URLs: Map URLs to views in your project's URL configuration (`urls.py`).
7. Run Development Server: Start the Django development server and test your application
locally: python manage.py runserver
Unit-5
Define inheritance in Python and elucidate its importance in code reusability and structure.
1. Single Inheritance:
- Single inheritance involves one subclass inheriting from one superclass.
- It forms a simple hierarchy where each subclass has exactly one superclass.
```python
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def bark(self):
print("Dog barks")
2. Multiple Inheritance:
- Multiple inheritance involves a subclass inheriting from multiple superclasses.
- This allows a subclass to combine features and behaviors from multiple sources.
```python
class A:
def method_A(self):
print("Method A")
class B:
def method_B(self):
print("Method B")
```python
class A:
def method_A(self):
print("Method A")
class B(A):
def method_B(self):
print("Method B")
class C(B):
def method_C(self):
print("Method C")
4. Hierarchical Inheritance:
- Hierarchical inheritance involves multiple subclasses inheriting from the same superclass.
- It forms a branching hierarchy where different subclasses specialize in different aspects.
```python
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def bark(self):
print("Dog barks")
class Cat(Animal):
def meow(self):
print("Cat meows")
# Both Dog and Cat inherit from Animal
```
5. Hybrid Inheritance:
- Hybrid inheritance combines two or more types of inheritance. For example, combining single and
multiple inheritance.
- It allows for more complex class relationships and can lead to the diamond problem, which Python
handles using the Method Resolution Order (MRO).
```python
class A:
def method_A(self):
print("Method A")
class B(A):
def method_B(self):
print("Method B")
class C(A):
def method_C(self):
print("Method C")
1. Code Reuse: Inheritance allows subclasses to inherit and reuse attributes and methods from their
superclasses. This reduces redundancy and promotes modular design, as common functionality can be
defined once in a superclass and reused across multiple subclasses.
2. Modularity: Inheritance promotes modularity by organizing classes hierarchically. Each subclass can
focus on specific aspects or behaviors, leading to a more organized and maintainable codebase.
3. Polymorphism: Inheritance supports polymorphism, where objects of different subclasses can be
treated as objects of a common superclass. This allows for flexibility in code design and enhances the
extensibility of the application.
Define inheritance in Python and elucidate its importance in code reusability and structure.
4. Encapsulation: Inheritance helps in encapsulating data and behaviors within classes. Superclasses
define a clear interface (public methods) for subclasses, hiding internal implementation details and
promoting a cleaner separation of concerns.
5. Hierarchical Structure: Inheritance facilitates the creation of a hierarchical class structure, reflecting
real-world relationships and enhancing the conceptual integrity of the codebase. This makes it easier for
developers to understand and navigate the system's architecture.
In Python, an exception is an event that occurs during the execution of a program that disrupts
the normal flow of instructions.
When a Python script encounters an error or unexpected condition that it cannot cope with, it
raises an exception.
Exceptions are objects that represent errors and provide information about what went wrong.
Exception handling with `try-except` blocks in Python allows you to anticipate and manage
potential errors effectively, ensuring that your program can handle unexpected conditions and
continue to operate reliably.
It promotes robustness, improves error reporting, and enhances the overall quality of your
software applications.
Python has a hierarchy of built-in exception classes, each representing different types of errors that can
occur during program execution. Some common built-in exceptions include:
- SyntaxError: Raised when the Python interpreter encounters a syntax error in the code.
-`TypeError: Raised when an operation or function is applied to an object of inappropriate type.
- ZeroDivisionError : Raised when division or modulo operation is performed with a divisor of zero.
- `IndexError`: Raised when trying to access an index that is out of range for a sequence (e.g., list, tuple).
- `KeyError: Raised when trying to access a dictionary key that does not exist.
- `FileNotFoundError : Raised when trying to open a file that does not exist.
- `ValueError`: Raised when a function receives an argument of correct type but inappropriate value.
- NameError : Raised when trying to access a variable that is not defined.
- AttributeError : Raised when trying to access or modify an attribute that does not exist for an object.
```python
try:
# Code block where exceptions may occur
# This could be a single statement or multiple statements
# An exception may be raised here
pass # Replace with actual code
except ExceptionType1 as e1:
# Code to handle exceptions of type ExceptionType1
# e1 is the exception object that contains information about the exception
pass # Replace with error handling code
except ExceptionType2 as e2:
# Code to handle exceptions of type ExceptionType2
pass # Replace with error handling code
else:
# Optional block that executes if no exception is raised in the try block
pass # Replace with code to execute if no exception
finally:
# Optional block that executes whether an exception occurred or not
# Useful for cleanup actions (e.g., closing files or releasing resources)
pass # Replace with cleanup code
```
Explanation of `try-except` Block Components:
1. `try` Block:
- The `try` block encloses the code that you want to monitor for exceptions.
- If any statement within the `try` block raises an exception, Python immediately jumps to the
corresponding `except` block.
2. `except` Block:
- Each `except` block specifies a particular type of exception (`ExceptionType`) that it can handle.
- When an exception of type `ExceptionType` (or its subclass) occurs in the `try` block, control moves
to the corresponding `except` block to handle the exception.
- You can have multiple `except` blocks to handle different types of exceptions separately.
3. `else` Block :
- The `else` block is optional and runs if no exceptions are raised in the `try` block.
- It is typically used to execute code that should only run if the `try` block succeeded without any
exceptions.
4. finally` Block :
- The `finally` block is optional and always runs after the `try` block, regardless of whether an exception
occurred or not.
- It is useful for releasing external resources (like files or network connections) or cleaning up
temporary data.
```python
def divide_numbers(a, b):
try:
result = a / b # Division operation that may raise exceptions
except ZeroDivisionError as e:
print(f"Error: {e}")
print("Cannot divide by zero. Please provide a non-zero divisor.")
result = None # Handle the error condition gracefully
except TypeError as e:
print(f"Error: {e}")
print("Please provide valid numbers for division.")
result = None # Handle the error condition gracefully
except Exception as e:
print(f"Unexpected Error: {e}")
result = None # Handle any unexpected errors
return result
# Example usage:
print(divide_numbers(10, 2)) # Output: 5.0
print(divide_numbers(10, 0)) # Output: Error: division by zero
# Cannot divide by zero. Please provide a non-zero divisor.
# None
print(divide_numbers(10, '2')) # Output: Error: unsupported operand type(s) for /: 'int' and 'str'
# Please provide valid numbers for division.
# None
```
In this example:
- The `divide_numbers` function attempts to divide two numbers (`a` by `b`).
- Inside the `try` block, a division operation is performed that may raise exceptions such as
`ZeroDivisionError` or `TypeError`.
- Each `except` block handles a specific type of exception, prints an error message, and gracefully
handles the error by returning `None` in case of errors.
CLASS AND OBJECTS: WHAT IS CLASS AND OBJECT AND HW TO CREATE CLASS AND OBJECT:
A class is a blueprint or template for creating objects. It encapsulates data (attributes) and
behaviors (methods) into a single unit.
Classes provide a means of bundling data and functionality together.
Creating a new class creates a new type of object, allowing new instances of that type to be
made.
Each class instance can have attributes attached to it for maintaining its state.
Class instances can also have methods (defined by their class) for modifying their state
Classes are created by keyword class.
Example:Python3
class Dog:
sound = "bark"
An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of the class
with actual values.
State: It is represented by the attributes of an object. It also reflects the properties of an object.
Behavior: It is represented by the methods of an object. It also reflects the response of an
object to other objects.
Identity: It gives a unique name to an object and enables one object to interact with other
objects.
When an object of a class is created, the class is said to be instantiated. All the instances share the
attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for
each object. A single class may have any number of instances.
Example:
# Python3 program to
# demonstrate instantiating
# a class
class Dog:
# A simple class
# attribute
attr1 = "mammal"
attr2 = "dog"
# A sample method
def fun(self):
print("I'm a", self.attr1)
print("I'm a", self.attr2)
# Driver code
# Object instantiation
Rodger = Dog()
Output:
mammal
I'm a mammal
I'm a dog
WHAT IS SELF VARIABLE:
In Python, `self` is a special parameter that is automatically passed to instance methods of a class. It
refers to the current instance of the class and allows you to access the instance's attributes and
methods.
Using `self`:
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
```
Example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
- Here, `self.name` and `self.age` refer to the instance variables `name` and `age` of the object (`self`)
that the method is being called on.
3. When calling methods on objects:
- When you call a method on an object, Python automatically passes the object itself as the `self`
argument. You don't explicitly pass `self` when calling methods.
```python
person1 = Person("Alice", 30)
person1.greet() # Automatically passes `person1` as `self`
```
Important Points:
- Instance-specific: `self` refers to the instance of the class that is being operated on. Each instance has
its own `self`, which allows for data encapsulation and instance-specific behavior.
- Convention: While `self` is not a keyword in Python, it is a widely followed convention to name the first
parameter of instance methods as `self` for clarity and consistency.
- Static and Class Methods: Note that for static methods (`@staticmethod`) and class methods
(`@classmethod`), `self` is not used as the first parameter. Instead, for class methods, `cls` is used to
refer to the class itself.
### Example:
```python
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius
circle1 = Circle(5)
print(circle1.area())
# Output: 78.5
```
In this example:
- `self.radius` refers to the `radius` attribute of the `circle1` instance when calculating the area.
- `self` allows each instance of `Circle` to maintain its own state (`radius` in this case) and perform
calculations based on its attributes.