Project
Project
beginners course
Ambala College of Engineering & Applied Research
A Training Report
Submitted in the partial fulfilment of requirement for the award
of the degree of
Bachelor of Technology
(Computer Science and Engineering)
Submitted to
Ambala College of Engineering & Applied Research
i
Student Declaration
I, Ayesha, Roll No 2323007, hereby declare that the work done by me on “Python
Fundamentals beginners course” from July,2024 to August, 2024, is a record of
original work for the partial fulfillment of the requirements for the award of the degree,
Bachelor of Technology(Computer Science & Engineering).
Dated:
ii
Declaration by the supervisors
This is to certify that Ayesha, 2323007 from Ambala College of Engineering & Applied
Research, Devsthali, Ambala, has worked as a trainee in Ambala College of Engineering
& Applied Research on “Python Fundamentals beginners course” under my
supervision from July, 2024 to August, 2024. It is further stated that the work carried out
by the student is a record of original work to the best of my knowledge for the partial
fulfillment of the requirements of the award of the degree Bachelor of
Technology(Computer Science & Engineering).
Dated:
iii
certificate
iv
Acknowledgement
I would like to place on record with my deep sense of gratitude to my training instructor Er.
Seema Rani and Er. Diksha for the stimulating guidance, continuous encouragement and
supervision for the submission of the training report and presentation. Thank you so much for
all of the academic, professional and personal advice that you have given me. The completion
of this training would not have been possible without the boundless encouragement and
support of my family. From you all, I have learned to take pride in my work and to enjoy the
simple pleasure of a job well done.
Ayesha
(2323007)
v
Table of Contents
8. Conclusion 62
9. References 63
vi
Chapter – 01
Introduction to the Company/ Institute
1.1 Introduction:
Ambala College of Engineering and Applied Research (ACE) stands out as a
leading institution dedicated to shaping the future of engineering and
technology. Here are some key highlights that make ACE a premier choice for
aspiring engineers
Industry Collaboration
Ambala College of Engineering and Applied Research maintains strong ties
with the industry, facilitating internships, training programs, and placement
opportunities for students. These collaborations ensure that students gain
practical experience and are well-prepared for the professional world.
Holistic Development
The college places a strong emphasis on the holistic development of students.
In addition to academic pursuits, Ambala College of Engineering and Applied
Research offers a variety of extracurricular activities, including sports, cultural
7
events, and technical clubs. These activities help students develop leadership
skills, teamwork, and a well-rounded personality.
1.3 Purpose of Internship/Training:
8
Chapter – 02
Introduction to Python
2.1 Introduction:
Python is a versatile and widely-used programming language renowned for its
simplicity, readability, and extensive range of libraries and frameworks. It was
created by Guido van Rossum and first released in 1991. Python's popularity
has grown exponentially, making it a top choice for various applications
including web development, data analysis, artificial intelligence, scientific
computing, automation, and more.
One of Python's key strengths lies in its elegant syntax, which emphasizes
human-readable code. This characteristic not only accelerates development but
also encourages collaboration among developers. Python's dynamic typing
system allows variables to change data types during runtime, enhancing
flexibility but requiring careful attention to type-related errors.
For data science and analytics, Python's libraries like NumPy, Pandas, and
Matplotlib provide essential tools for efficient numerical operations, data
manipulation, and data visualization. For machine learning and artificial
intelligence, libraries like TensorFlow, PyTorch, and Scikit-learn offer robust
frameworks to build and train models.
Select Version:
Choose the version of Python you want to install. As of my knowledge cutoff
in September 2021, Python 3 is recommended as Python 2 is no longer
supported.
Download Installer:
Click on the download link for the version you've chosen. Choose the
appropriate installer for your operating system (Windows, macOS, or Linux).
Run Installer:
Locate the downloaded installer file and run it.
Complete Installation:
Follow the installation prompts, and the installer will set up Python on your
system.
Verifying Installation:
Open Command Prompt or Terminal:
On Windows, press Win + R, type cmd, and press Enter. On macOS and
Linux, search for "Terminal" in your applications.
Python comes with a package manager called "pip" that allows you to easily
install additional packages or libraries. After installing Python, you can use pip
to install packages. For example, to install a package named "numpy," you
would run:
pip install numpy
Remember that package management and best practices might evolve over
time, so it's a good idea to refer to the official Python documentation or other
reliable sources for the most up-to-date information.
11
and more. Variables provide a way to reference data by a name, making it
easier to manipulate and work with values in your programs.
Naming Convention: Variable names can consist of letters (both uppercase and
lowercase), digits, and underscores. They must start with a letter or
underscore, followed by any combination of characters.
Reserved Words: Avoid using reserved words (also known as keywords) like
if, else, while, etc., as variable names, as they have special meanings in
Python.
Variable Reassignment:
You can change the value of a variable after it has been assigned:
age = 25
age = 30 # Reassigning the value
Multiple Assignment:
You can assign multiple variables in a single line:
12
x, y, z = 10, 20, 30
Variable Scope:
The scope of a variable refers to where it can be accessed in your code.
Variables can have local scope (within a function) or global scope (accessible
throughout the entire program).
2.4 Constants:
While Python doesn't have true constants, conventionally, constants are named
in uppercase and not meant to be changed:
PI = 3.14
Creating Strings:
You can create strings by enclosing text within single or double quotes:
name = "Alice"
message = 'Hello, world!'
String Concatenation:
You can combine strings using the + operator:
greeting = "Hello"
name = "Alice"
full_greeting = greeting + " " + name
String Length:
You can find the length of a string using the built-in len() function:
text = "Hello, world!"
length = len(text) # Returns 13
Accessing Characters:
13
Individual characters in a string can be accessed using indexing, where the
index starts from 0:
word = "Python"
first_letter = word[0] # Returns 'P'
Slicing:
You can extract a portion of a string using slicing:
text = "Hello, world!"
substring = text[0:5] # Returns "Hello"
String Methods:
Python provides numerous built-in methods to manipulate and work with
strings:
String Formatting:
Python offers several ways to format strings:
f-strings: Allow you to embed expressions inside string literals for dynamic
formatting.
.format(): A method to format strings by substituting placeholders with
values.
% operator: A legacy way of string formatting.
String Escaping:
If you need to include special characters within a string, you can use escape
sequences, such as \" for double quote and \' for single quote.
Multiline Strings:
14
Triple-quoted strings (''' or """) allow you to create multiline strings:
multiline_text = """
This is a multiline
string in Python.
"""
String Immutability:
Strings are immutable, meaning once they are created, their contents cannot be
changed. However, you can create new strings based on existing ones.
Arithmetic Operators:
Arithmetic operators perform basic mathematical operations:
+: Addition
-: Subtraction
*: Multiplication
/: Division
%: Modulo (remainder)
**: Exponentiation (power)
//: Floor Division (result is the quotient without the decimal part)
Comparison Operators:
Comparison operators compare values and return a Boolean result (True or
False):
==: Equal to
!=: Not equal to
<: Less than
>: Greater than
<=: Less than or equal to
15
>=: Greater than or equal to
Logical Operators:
Logical operators are used to combine Boolean values or expressions:
and: Logical AND (returns True if both operands are True)
or: Logical OR (returns True if at least one operand is True)
not: Logical NOT (returns the opposite Boolean value)
Assignment Operators:
Assignment operators are used to assign values to variables:
=: Assign value
+=: Add and assign
-=: Subtract and assign
*=: Multiply and assign
/=: Divide and assign
%=: Modulo and assign
**=: Exponentiate and assign
//=: Floor divide and assign
Identity Operators:
Identity operators compare the memory addresses of two objects:
is: Returns True if both operands refer to the same object
is not: Returns True if both operands refer to different objects
Membership Operators:
Membership operators check if a value is present in a sequence (e.g., string,
list, tuple):
in: Returns True if the value is in the sequence
not in: Returns True if the value is not in the sequence
Bitwise Operators:
Bitwise operators perform operations on the binary representations of integers:
&: Bitwise AND
|: Bitwise OR
^: Bitwise XOR
~: Bitwise NOT
16
<<: Left shift
>>: Right shift
Operator Precedence:
Operators have precedence levels that determine the order in which operations
are performed. Parentheses can be used to control the order explicitly.
Python is dynamically typed, which means you don't need to explicitly declare
a variable's type. Python determines the data type based on the assigned value.
Common data types include:
2.71 List
Lists are one of the most versatile and commonly used data structures in
Python. They are used to store collections of items, which can be of different
data types, including numbers, strings, and even other lists.
Creating Lists:
Lists are created by enclosing items in square brackets [ ], separated by
commas:
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "orange"]
mixed_list = [42, "hello", 3.14, True]
List Methods:
Python provides a variety of built-in methods to manipulate lists:
append(item): Adds an item to the end of the list.
insert(index, item): Inserts an item at a specific index.
remove(item): Removes the first occurrence of the specified item.
pop(index): Removes and returns the item at the specified index.
len(list): Returns the number of items in the list.
sort(): Sorts the items in ascending order.
reverse(): Reverses the order of items.
List Slicing:
You can extract a portion of a list using slicing:
numbers = [1, 2, 3, 4, 5]
subset = numbers[1:4] # [2, 3, 4]
List Concatenation:
Lists can be concatenated using the + operator:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2 # [1, 2, 3, 4, 5, 6]
Nested Lists:
Lists can contain other lists as elements, creating nested lists:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
List Comprehensions:
18
List comprehensions provide a concise way to create lists based on existing
lists:
squares = [x ** 2 for x in range(10)]
2.72 Tuple
Tuples are another fundamental data structure in Python that allow you to store
a collection of items. Similar to lists, tuples can hold multiple values, but they
have a few key differences.
Creating Tuples:
Tuples are created by enclosing items in parentheses (), separated by commas:
point = (3, 5)
colors = ("red", "green", "blue")
mixed_tuple = (42, "hello", 3.14)
Immutable Nature:
One of the main differences between tuples and lists is that tuples are
immutable, meaning their contents cannot be changed after creation:
point = (3, 5)
point[0] = 10 # This will result in an error
Tuple packing is the process of creating a tuple with multiple values, and tuple
unpacking is the process of assigning the values of a tuple to multiple
variables:
Advantages of Tuples:
Immutable: Tuples are suitable for data that should not be changed
accidentally.
Performance: Due to their immutability, tuples are slightly faster than lists in
certain operations.
Hashable: Tuples can be used as keys in dictionaries, which require
immutability.
Use Cases:
Tuples are often used to represent items that should remain constant
throughout the program's execution, such as coordinates, RGB color values,
and database records.
2.73 Sets
A set is an unordered collection of unique elements in Python. Sets are useful
for storing and manipulating data when you want to ensure that each element
is unique and unordered.
Creating Sets:
Sets are created using curly braces {} or the built-in set() constructor:
fruits = {"apple", "banana", "orange"}
numbers = set([1, 2, 3, 4, 5])
Unique Elements:
Sets automatically eliminate duplicate values, ensuring that each element is
unique:
my_set = {1, 2, 2, 3, 3, 3} # Results in {1, 2, 3}
Set Operations:
Sets support various mathematical operations:
union(): Returns a new set with all unique elements from both sets.
intersection(): Returns a new set with elements common to both sets.
20
difference(): Returns a new set with elements present in the first set but not
in the second.
symmetric_difference(): Returns a new set with elements that are in either of
the sets, but not in both.
Modifying Sets:
Sets are mutable, allowing you to add and remove elements:
fruits = {"apple", "banana", "orange"}
fruits.add("grape") # Adds "grape" to the set
fruits.remove("banana") # Removes "banana" from the set
2.74 Dictionaries
Dictionaries are versatile data structures that allow you to store and manage
key-value pairs. Each value is associated with a unique key, enabling efficient
and fast retrieval of values based on their keys.
Creating Dictionaries:
Dictionaries are created using curly braces {} and specifying key-value pairs
separated by colons ::
person = {"name": "Alice", "age": 25, "city": "New York"}
scores = {"math": 95, "science": 89, "history": 75}
Dictionary Methods:
Dictionaries provide various methods for working with their keys and values:
Defining Functions:
Functions are defined using the def keyword, followed by the function name,
parameters in parentheses, and a colon. The function body is indented below:
def greet(name):
print("Hello, " + name)
Function Parameters:
Parameters are placeholders for values that you pass to the function when it's
called. Functions can have zero or more parameters:
def add(x, y):
return x + y
Function Calling:
To call a function, use its name followed by parentheses, and provide the
required arguments:
greet("Alice")
22
sum_result = add(3, 5)
Return Statements:
Functions can return values using the return statement. If no return statement is
used, the function returns None by default:
def square(x):
return x ** 2
Scope of Variables:
Variables defined inside a function are local to that function and have a limited
scope. They don't affect variables with the same names outside the function.
Default Parameters:
You can provide default values for function parameters. These default values
are used when the corresponding argument is not provided during function
call:
def greet(name="Guest"):
print("Hello, " + name)
Lambda Functions:
Lambda functions (also known as anonymous functions) are concise, one-line
functions defined using the lambda keyword:
square = lambda x: x ** 2
Built-in Functions:
Python comes with a rich set of built-in functions that perform various
operations, such as len(), print(), max(), and min().
23
2.9 Object Oriented Programming in Python
Object-Oriented Programming (OOP) is a programming paradigm that focuses
on organizing code into objects, which are instances of classes. Classes define
the blueprint for creating objects with attributes (data) and methods
(functions).
Class: A class is a blueprint or template that defines the structure and behavior
of objects. It defines attributes (variables) and methods (functions) that objects
of that class will have.
Attributes: Attributes are variables that hold data within an object. They
define the characteristics or properties of an object.
Methods: Methods are functions defined within a class that perform specific
actions or provide functionalities related to the class.
def bark(self):
print(f"{self.name} is barking")
Creating Objects:
Objects are created based on class definitions using the constructor (usually
the __init__ method):
dog1 = Dog("Buddy", 3)
dog2 = Dog("Max", 5)
Inheritance:
Subclasses can inherit attributes and methods from a superclass:
class Labrador(Dog):
def __init__(self, name, age, color):
super().__init__(name, age)
self.color = color
Polymorphism:
25
Chapter – 03
Introduction to Seaborn
1. Installation
26
To install Seaborn, you can use the following pip command:
Code -
pip install seaborn
2. Importing Seaborn
You can import Seaborn into your Python script or Jupyter Notebook as follows:
Code -
import seaborn as sns
import matplotlib.pyplot as plt
3. Key Features
Built-in Themes and Color Palettes: Seaborn comes with several themes
and color palettes that improve the aesthetic appeal of your plots.
Statistical Estimations: Seaborn can automatically perform statistical
estimations and plot the results, such as confidence intervals.
Complex Plots Made Simple: Seaborn simplifies the creation of complex
visualizations, including heatmaps, violin plots, and pair plots.
Data-Aware Plotting: Seaborn works seamlessly with Pandas DataFrames
and supports categorical data visualization.
Code -
sns.scatterplot(data=df, x='variable1', y='variable2')
plt.show()
Code -
sns.lineplot(data=df, x='time', y='value')
plt.show()
Code -
sns.barplot(data=df, x='category', y='value')
plt.show()
Code -
sns.boxplot(data=df, x='category', y='value')
plt.show()
Code -
sns.violinplot(data=df, x='category', y='value')
plt.show()
Code -
sns.histplot(data=df['variable'])
plt.show()
Code -
sns.kdeplot(data=df['variable'])
plt.show()
Code -
sns.heatmap(data=corr_matrix, annot=True, cmap='coolwarm')
plt.show()
28
clustermap: Plots a hierarchically clustered heatmap.
Code -
sns.clustermap(data=df.corr(), cmap='viridis')
plt.show()
Code -
sns.pairplot(df)
plt.show()
Code -
g = sns.FacetGrid(df, col="category")
g.map(sns.histplot, "value")
plt.show()
5. Customizing Plots
Code -
sns.set_style('whitegrid')
sns.set_palette('muted')
Adding Titles and Labels: You can add titles, labels, and other annotations
using Matplotlib functions.
Code -
plt.title('Title of the Plot')
plt.xlabel('X-axis Label')
29
plt.ylabel('Y-axis Label')
Figure Size and Aspect Ratio: Control the figure size using
Code –
plt.figure(figsize=(10, 6))
Code -
sns.barplot(data=df, x='column1', y='column2')
7. Saving Plots
You can save your Seaborn plots using Matplotlib’s savefig function.
Code -
plt.savefig('plot.png')
Seaborn is widely used in data science for exploratory data analysis (EDA), data
cleaning, and visualization of statistical relationships. It’s particularly useful for
visualizing distributions, relationships between variables, and understanding data
at a glance.
9. Conclusion
30
Chapter – 04
Introduction to Numpy
4.1 Introduction:
NumPy, short for Numerical Python, is a fundamental package for numerical
and scientific computing in Python. It provides support for arrays, matrices,
and a wide range of mathematical operations, making it an essential tool for
data manipulation, analysis, and computation in various scientific and
engineering domains.
31
Arrays: NumPy introduces the ndarray (n-dimensional array) data structure,
which is the core of its functionality. Arrays can be of various dimensions and
hold elements of the same data type.
Array Indexing and Slicing: NumPy provides powerful ways to index and
slice arrays, allowing you to extract, modify, and manipulate subsets of data
efficiently.
32
Creating Arrays:
You can create arrays using various methods, such as np.array(), np.zeros(),
np.ones(), np.arange(), and more:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
zeros_arr = np.zeros((2, 3))
ones_arr = np.ones((3, 3))
Array Operations:
NumPy supports element-wise operations, broadcasting, and mathematical
functions:
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
sum_result = a + b
product_result = a * b
square_root = np.sqrt(a)
Linear Algebra:
NumPy offers extensive linear algebra capabilities:
matrix_product = np.dot(A, B)
eigenvalues, eigenvectors = np.linalg.eig(A)
Hence,
33
NumPy is a cornerstone of scientific computing in Python, providing essential
tools for handling numerical data, performing advanced mathematical
operations, and working with arrays and matrices. Its efficiency and rich set of
functionalities make it a valuable asset for data analysis, machine learning,
simulations, and a wide range of scientific endeavors. NumPy's seamless
integration with other libraries like SciPy, Matplotlib, and Pandas enhances its
utility in the broader Python ecosystem.
34