0% found this document useful (0 votes)
16 views59 pages

Data Science Virtual Internshi1

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

Data Science Virtual Internshi1

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

DATA SCIENCE VIRTUAL INTERNSHIP

DAY-1
1.PYTHON PROGRAMMING LANGUAGE
1.1INTRODUCTION TO PYTHON:
HISTORY OF PYTHON:
➢ Python laid its foundation in the late 1980s.
➢ The implementation of Python was started in December 1989 by Guido Van
Rossum at CWI in Netherland.
➢ In February 1991, Guido Van Rossum published the code (labeled version 0.9.0) to
alternate sources.
➢ In 1994, Python 1.0 was released with new features like lambda, map, filter, and reduce.
➢ Python 2.0 added new features such as list comprehensions, garbage collection systems.
➢ On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed
to rectify the fundamental flaw of the language.
➢ ABC programming language is said to be the predecessor of Python language, which
was capable of Exception Handling and interfacing with the Amoeba Operating
System.
➢ The following programming languages influence Python:
o ABC language.
o Modula-3

WHY IT IS NAMED PYTHON?

Guido Van Rossum, the author of Python Programming Language was reading the published
scripts from “Monty Python’s Flying Circus”, a BBC comedy series from the 1970s. Van
Rossum thought he needed a name that was short, unique, and slightly mysterious, so he
decided to call the language Python.

The comedy series was creative and well random. It talks about everything. Thus it is slow and
unpredictable, which made it very interesting.

Python is also versatile and widely used in every technical field, such as Machine
Learning, Artificial Intelligence, Web Development, Mobile Application, Desktop
Application, Scientific Calculation, etc.
WHAT IS PYTHON?
Python is a general-purpose, dynamic, high-level, and interpreted programming language. It
supports Object Oriented programming approach to develop applications. It is simple and easy
to learn and provides lots of high-level data structures.

Python is an easy-to-learn yet powerful and versatile scripting language, which makes it
attractive for Application Development.

With its interpreted nature, Python's syntax and dynamic typing make it an ideal language for
scripting and rapid application development.

Python supports multiple programming patterns, including object-oriented, imperative, and


functional or procedural programming styles.

Python is not intended to work in a particular area, such as web programming. It is a


multipurpose programming language because it can be used with web, enterprise, 3D CAD,
etc.

We don't need to use data types to declare variable because it is dynamically typed, so we can
write a=10 to assign an integer value in an integer variable.

INSTALLATION OF PYTHON:

Step - 1: Visit Official Site to Download Python Installer:


All Python-related information is available on its official website. First, open the browser and
visit the official site (www.python.org) to install Python installer. Here, we can see the many
Python installer versions, but we will download the latest version of Python.
Step-2: INSTALL PYTHON
Once you have downloaded the installer, open the .exe file, such as python-3.10.11-
amd64.exe, by double-clicking it to launch the Python installer. Choose the option to
Install the launcher for all users by checking the corresponding checkbox, so that all
users of the computer can access the Python launcher application. Enable users to run
Python from the command line by checking the Add python.exe to PATH checkbox.

After Clicking the Install Now Button the setup will start installing Python on your
Windows system. You will see a window like this.
Step-3: SET UP PROCESS
After completing the setup. Python will be installed on your Windows system. You
will see a successful message.

Step-4: PYTHON ACCESS


Close the window after successful installation of Python. You can check if the
installation of Python was successful by using either the command line or the
Integrated Development Environment (IDLE), which you may have installed. To
access the command line, click on the Start menu and type “cmd” in the search bar.
Then click on Command Prompt.
python –version

STEP-5:OPENING IDLE

You can also check the version of Python by opening the IDLE application. Go to
Start and enter IDLE in the search bar and then click the IDLE app, for
example, IDLE (Python 3.10.11 64-bit). If you can see the Python IDLE window
then you are successfully able to download and installed Python on Windows.
VARIABLES IN PYTHON:
Python Variable is containers that store values. Python is not “statically typed”. We do not
need to declare variables before using them or declare their type. A variable is created the
moment we first assign a value to it. A Python variable is a name given to a memory location.
It is the basic unit of storage in a program.

Rules for Python variables

• A Python variable name must start with a letter or the underscore character.
• A Python variable name cannot start with a number.
• A Python variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ ).
• Variable in Python names are case-sensitive (name, Name, and NAME are
three different variables).
• The reserved words(keywords) in Python cannot be used to name the variable
in Python.

Declaration and Initialization of Variables

In Python, you don't need to explicitly declare the variable type. Python is a
dynamically-typed language, which means that the interpreter determines the type
of a variable at runtime. You can simply assign a value to a variable, and Python
will figure out the type.
Ex:
# Declaration and Initialization
my_number = 42
my_string = "Hello, Python!"
my_float = 3.14
my_boolean = True
# Printing the values
print(my_number)
print(my_string)
print(my_float)
print(my_boolean)
#a=b=c=10
Output:
42
Hello,Python!
3.14
True
10
10
10
PYTHON KEYWORDS:
Python keywords are unique words reserved with defined meanings and functions
that we can only apply for those functions. You'll never need to import any keyword
into your program because they're permanently present.

Python's built-in methods and classes are not the same as the keywords. Built-in
methods and classes are constantly present; however, they are not as limited in their
application as keywords.

CODE:

import keyword
print(keyword.kwlist)
OUTPUT:
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue',
'def', 'del', 'elif', 'else', 'except', 'False', 'finally', 'for', 'from', 'global', 'if', 'import',
'in', 'is', 'lambda', 'None', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'True', 'try',
'while', 'with', 'yield']

Identifiers in Python:
Identifier is a user-defined name given to a variable, function, class, module, etc.
The identifier is a combination of character digits and an underscore. They are
case-sensitive i.e., ‘num’ and ‘Num’ and ‘NUM’ are three different identifiers in
python. It is a good programming practice to give meaningful names to identifiers
to make the code understandable.
Rules for Naming Python Identifiers
• It cannot be a reserved python keyword.
• It should not contain white space.
• It can be a combination of A-Z, a-z, 0-9, or underscore.
• It should start with an alphabet character or an underscore ( _ ).
• It should not contain any special character other than an underscore ( _ ).
Examples of Python Identifiers
Valid identifiers:
• var1
• _var1
• _1_var
• var_1
Invalid Identifiers
• !var1
• 1var
• 1_var
• var#1
• var 1

OPERATORS IN PYTHON:
Operators in Python are special symbols or keywords that are used to perform
operations on operands. Operands can be variables, values, or expressions. Python
supports various types of operators, including arithmetic, comparison, logical,
assignment, bitwise, membership, and identity operators.
1.ARITHMETIC OPERATORS:
Arithmetic operators perform basic mathematical operations.
EX:
# Addition
result = 5 + 3 # result is 8
# Subtraction
result = 7 - 4 # result is 3
# Multiplication
result = 2 * 6 # result is 12
# Division
result = 8 / 2 # result is 4.0 (float)
# Floor Division
result = 7 // 3 # result is 2 (integer)
# Modulus (remainder)
result = 9 % 4 # result is 1
# Exponentiation
result = 2 ** 3 # result is 8

2.COMPARISON OPERATORS:

Comparison operators are used to compare values and return Boolean results.
EX:
# Equal to
result = (3 == 3) # result is True
# Not equal to
result = (5 != 2) # result is True
# Greater than
result = (8 > 5) # result is True
3.LOGICAL OPERATORS:

Logical operators perform logical operations and return Boolean results.


EX:
# Logical AND
result = (True and False) # result is False
# Logical OR
result = (True or False) # result is True
# Logical NOT
result = not True # result is False

4.ASSIGNMENT OPERATORS:

Assignment operators are used to assign values to variables.


EX:
# Assign value
x = 10
# Add and assign
x += 5 # equivalent to x = x + 5
# Subtract and assign
x -= 3 # equivalent to x = x - 3
# Multiply and assign
x *= 2 # equivalent to x = x * 2
# Divide and assign
x /= 4 # equivalent to x = x / 4

5.BITWISE OPERATORS:

Bitwise operators perform operations at the bit level.


EX:
# Bitwise AND
result = 5 & 3 # result is 1 (binary: 101 & 011)
# Bitwise OR
result = 5 | 3 # result is 7 (binary: 101 | 011)
# Bitwise XOR
result = 5 ^ 3 # result is 6 (binary: 101 ^ 011)
# Bitwise NOT
result = ~5 # result is -6 (binary: ~101)
# Left shift
result = 8 << 1 # result is 16 (binary: 1000 << 1)
# Right shift
result = 8 >> 1 # result is 4 (binary: 1000 >> 1)
6.MEMBERSHIP OPERATORS:

Membership operators are used to test if a value is a member of a sequence.


EX:
# Check if element is in a sequence
result = 3 in [1, 2, 3] # result is True
# Check if element is not in a sequence
result = 4 not in [1, 2, 3] # result is True

7.IDENTITY OPERATORS:

Identity operators are used to compare the memory locations of two objects.
EX:
# Check if two objects reference the same object
result = ("hello" is "hello") # result is True
# Check if two objects do not reference the same object
result = (1 is not 1.0) # result is True
DAY-2

PRECEDENCE OF OPERATORS:

Operator precedence in Python defines the order in which different operators are
evaluated in an expression. Operators with higher precedence are evaluated first. If
two operators have the same precedence, their associativity (left-to-right or right-
to-left) determines the order of evaluation.
EX:
# Example 1
result = 2 + 3 * 4
# Here, multiplication has higher precedence, so it's evaluated first.
# result = 2 + (3 * 4) = 14
# Example 2
result = (2 + 3) * 4
# Here, parentheses have the highest precedence, so the expression inside
parentheses is evaluated first.
# result = (2 + 3) * 4 = 20

PYTHON DATA TYPES:

Data types are the classification or categorization of data items. It represents the
kind of value that tells what operations can be performed on a particular data.
Since everything is an object in Python programming, data types are actually
classes and variables are instances (object) of these classes.
1.LISTS:
A list is a built-in data type in Python that represents an ordered and mutable
collection of elements. In Python, the sequence of various data types is stored in a
list. A list is a collection of different kinds of values or items. Since Python lists are
mutable, we can change their elements after forming. The comma (,) and the
square brackets [enclose the List's items] serve as separators.
Although six Python data types can hold sequences, the List is the most common
and reliable form. A list, a type of sequence data, is used to store the collection of
data. Tuples and Strings are two similar data formats for sequences.
Lists written in Python are identical to dynamically scaled arrays defined in other
languages, such as Array List in Java and Vector in C++. A list is a collection of
items separated by commas and denoted by the symbol [].
CREATION:
Lists are created using square brackets [] and can contain elements of different data
types.
EX:
my_list = [1, 2, 3, 4, 5]
mixed_list = [1, "hello", 3.14, True, [5, 6, 7]]

ACCESSING ELEMENTS:
Individual elements in a list are accessed using zero-based indexing.
EX:
first_element = my_list[0]
second_element = my_list[1]
last_element = my_list[-1]

CHARACTERISTICS OF LISTS:
o The lists are in order.
o The list element can be accessed via the index.
o The mutable type of List is
o The rundowns are changeable sorts.
o The number of various elements can be stored in a list.

List Indexing and Splitting


The indexing procedure is carried out similarly to string processing. The slice
operator [] can be used to get to the List's components.
The index ranges from 0 to length -1. The 0th index is where the List's first
element is stored; the 1st index is where the second element is stored, and so on.

CODE:
list = [1,2,3,4,5,6,7]
print(list[0])
print(list[1])
print(list[2])
print(list[3])
# Slicing the elements
print(list[0:6])
# By default, the index value is 0 so its starts from the 0th element and go for
index-1.
print(list[:])
print(list[2:5])
print(list[1:6:2])

OUTPUT:
1
2
3
4
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[3, 4, 5]
[2, 4, 6]

Python List Operations:

The concatenation (+) and repetition (*) operators work in the same way as they
were working with the strings. The different operations of list are
o Repetition
o Concatenation
o Length
o Iteration
o Membership

1. Repetition:

The redundancy administrator empowers the rundown components to be rehashed


on different occasions.
Code:
# repetition of list
# declaring the list
list1 = [12, 14, 16, 18, 20]
# repetition operator *
l = list1 * 2
print(l)
OUTPUT:
[12, 14, 16, 18, 20, 12, 14, 16, 18, 20]

2. Concatenation:
It concatenates the list mentioned on either side of the operator.

Code:
# concatenation of two lists
# declaring the lists
list1 = [12, 14, 16, 18, 20]
list2 = [9, 10, 32, 54, 86]
# concatenation operator +
l = list1 + list2
print(l)
OUTPUT:
[12, 14, 16, 18, 20, 9, 10, 32, 54, 86]

3. Length:
It is used to get the length of the list

Code:
# size of the list
# declaring the list
list1 = [12, 14, 16, 18, 20, 23, 27, 39, 40]
# finding length of the list
len(list1)
OUTPUT:
9

4. Iteration:
The for loop is used to iterate over the list elements.
Code:
# iteration of the list
# declaring the list
list1 = [12, 14, 16, 39, 40]
# iterating
for i in list1:
print(i)
OUTPUT:
12
14
16
39
40

5. Membership:
It returns true if a particular item exists in a particular list otherwise false.

Code:
# membership of the list
# declaring the list
list1 = [100, 200, 300, 400, 500]
# true will be printed if value exists
# and false if not
print(600 in list1)
print(700 in list1)
print(1040 in list1)
print(300 in list1)
print(100 in list1)
print(500 in list1)
OUTPUT:
False
False
False
True
True
True

2.TUPLES:
A comma-separated group of items is called a Python triple. The ordering, settled
items, and reiterations of a tuple are to some degree like those of a rundown, but in
contrast to a rundown, a tuple is unchanging.The main difference between the two
is that we cannot alter the components of a tuple once they have been assigned. On
the other hand, we can edit the contents of a list.
Ex:
("Suzuki", "Audi", "BMW"," Skoda ") is a tuple.

FEATURES OF TUPLES:
o Tuples are an immutable data type, meaning their elements cannot be changed
after they are generated.
o Each element in a tuple has a specific order that will never change because
tuples are ordered sequences.

Accessing Tuple Elements:

A tuple's objects can be accessed in a variety of ways.

Indexing:

Indexing We can use the index operator [] to access an object in a tuple, where the
index starts at 0.

Negative indexing:

Python's sequence objects support negative indexing.The last thing of the assortment
is addressed by - 1, the second last thing by - 2, etc

Ex:

my_tuple = ('a', 'b', 'c', 'd', 'e')

# Accessing elements using negative indexing

print(my_tuple[-1]) # Output: 'e' (last element)

print(my_tuple[-3]) # Output: 'c' (third element from the end)

print(my_tuple[-5]) # Output: 'a' (first element)

ADVANTAGES OF TUPLES:.

➢ Immutability: Elements cannot be changed after creation, ensuring data


integrity.
➢ Faster Access: Accessing elements in tuples is faster than in lists due to
immutability.
➢ Memory Efficiency: Tuples consume less memory compared to lists.
➢ Valid Dictionary Keys: Tuples can be used as keys in dictionaries due to their
immutability.
➢ Performance: Faster iteration and processing due to immutability.
➢ Multiple Return Values: Functions can return multiple values as a single
tuple.
➢ Argument Packing/Unpacking: Tuples allow for easy packing and unpacking
of function arguments.
➢ Sequence Concatenation: Tuples can be efficiently concatenated with other
tuples.
➢ Named Tuples: collections.namedtuple provides more readable tuples with
named fields.
➢ Constants: Tuples can be used to define constants in a program.

Example 1: Creating Tuples

# Creating a tuple of numbers

numbers = (1, 2, 3, 4, 5)

print(numbers) # Output: (1, 2, 3, 4, 5)

# Creating a tuple of strings

fruits = ('apple', 'banana', 'orange', 'grape')

print(fruits) # Output: ('apple', 'banana', 'orange', 'grape')

# Creating a mixed-type tuple

mixed_tuple = (1, 'hello', 3.14, True)

print(mixed_tuple) # Output: (1, 'hello', 3.14, True)

Example 2: Accessing Elements of a Tuple

numbers = (1, 2, 3, 4, 5)

# Accessing elements using indexing

print(numbers[0]) # Output: 1

print(numbers[2]) # Output: 3

# Accessing elements using negative indexing

print(numbers[-1]) # Output: 5 (last element)

print(numbers[-3]) # Output: 3 (third element from the end)

3.SETS:

Sets in Python are unordered collections of unique elements.


Key Points about Sets:

➢ Uniqueness: Sets contain only unique elements; duplicates are automatically


removed.
➢ Unordered: Elements in a set are not stored in any particular order.
➢ Mutable: Sets are mutable, meaning elements can be added or removed after
the set is created.
➢ Support for Basic Operations: Sets support operations like union, intersection,
difference, and more.

1.Creating Sets:

EX:

# Creating a set

my_set = {1, 2, 3, 4}

print(my_set) # Output: {1, 2, 3, 4}

# Creating a set from a list (removes duplicates)

my_list = [1, 2, 2, 3, 4, 4]

set_from_list = set(my_list)

print(set_from_list) # Output: {1, 2, 3, 4}

2.Adding and Removing Elements:

Ex:

# Adding elements to a set

my_set.add(4)

print(my_set) # Output: {1, 2, 3, 4}

# Removing elements from a set

my_set.remove(2)

print(my_set) # Output: {1, 3, 4}

3.Set Operations:
Ex:

set1 = {1, 2, 3}

set2 = {2, 3, 4}

# Union of sets

union = set1.union(set2)

print(union) # Output: {1, 2, 3, 4}

# Intersection of sets

intersection = set1.intersection(set2)

print(intersection) # Output: {2, 3}

# Difference between sets

difference = set1.difference(set2)

print(difference) # Output: {1}

ADVANTAGES OF SETS:

• Uniqueness: Sets contain only unique elements. Duplicates are automatically


eliminated, simplifying data deduplication tasks.
• Fast Lookup: Sets offer fast lookup times for elements due to their hash-based
implementation, making membership testing efficient, especially for large
collections.
• Set Operations: Supports set operations like union, intersection, difference,
and symmetric difference, facilitating comparisons and manipulations
between sets.
• Efficient Data Cleaning: Sets are effective for eliminating duplicates from
collections, streamlining data cleaning processes.
• Mathematical Set Theory: Ideal for applications related to mathematical set
theory, aiding in tasks involving distinct elements, common elements, and
subsets.
• Mutable Nature: While sets are mutable (elements can be added or removed),
they ensure uniqueness, preventing duplicate entries.
• Frozensets: Python includes frozensets, immutable versions of sets, useful as
dictionary keys or when immutability is desired.
• Hashing: Utilizes hashing for storing elements, resulting in rapid access times
even with a large number of elements.
DAY-3

DICTIONARY:
Dictionaries in Python are unordered collections of key-value pairs.

Key Points about Dictionaries:


❖ Key-Value Structure: Dictionaries store data in key-value pairs,where each
key is associated with a value.
❖ Unordered: Items in a dictionary are not stored in any specific order;they're
retrieved by their keys.
❖ Mutable: Dictionaries are mutable, allowing for changes such as
adding,modifying, or removing key-value pairs.
❖ Keys are Unique: Keys within a dictionary must be unique,but values can be
duplicates.
❖ Various Data Types: Keys and values can be of different data types (string,
integer, tuple, etc.).

1.CREATING DICTIONARY:

EX:
Creating an empty dictionary
empty_dict = {}
# Creating a dictionary with key-value pairs
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}
print(my_dict) # Output: {'name': 'Alice', 'age': 30, 'city': 'New York'}

2.Accessing and Modifying elements:

Ex:
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}
# Accessing values using keys
print(my_dict['name']) # Output: 'Alice'
# Modifying values
my_dict['age'] = 31
print(my_dict) # Output: {'name': 'Alice', 'age': 31, 'city': 'New York'}
# Adding new key-value pairs
my_dict['gender'] = 'Female'
print(my_dict) # Output: {'name': 'Alice', 'age': 31, 'city': 'New York', 'gender':
'Female'}
# Removing key-value pairs
del my_dict['city']
print(my_dict) # Output: {'name': 'Alice', 'age': 31, 'gender': 'Female'}
3.Dictionary Methods:

Ex:
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}
# Get keys and values
keys = my_dict.keys()
values = my_dict.values()
print(keys) # Output: dict_keys(['name', 'age', 'city'])
print(values) # Output: dict_values(['Alice', 30, 'New York'])
# Check if a key exists
print('age' in my_dict) # Output: True
# Clearing a dictionary
my_dict.clear()
print(my_dict) # Output: {}

Advantages of Dictionary:

❖ Fast Data Retrieval: Dictionaries use keys to store and retrieve values,
allowing for rapid access regardless of the size of the dictionary. This makes
them highly efficient for data retrieval tasks.
❖ Flexibility in Data Structure: Dictionaries can store various data types as
values, including integers, strings, lists, other dictionaries, etc., providing
flexibility in structuring data.
❖ Uniqueness of Keys: Each key in a dictionary must be unique, ensuring that
data retrieval is based on a specific and distinct identifier.
❖ Mutable Nature: Dictionaries are mutable; this means elements (key-value
pairs) can be added, removed, or modified, allowing for dynamic changes in
data.
❖ Mapping and Association: Dictionaries are ideal for creating associations
between different pieces of related data. For instance, mapping a student's
ID to their information.

STRINGS:

Strings in Python are sequences of characters, enclosed within single (' '), double ("
"), or triple (''' ''' or """ """) quotes.

KEY POINTS OF STRINGS:

❖ Immutable: Strings in Python are immutable, meaning they cannot be


changed after creation. Operations on strings create new strings.
❖ Sequence of Characters: Consist of a sequence of characters, including
letters, numbers, symbols, and spaces.
❖ Indexing and Slicing: Characters within a string can be accessed using
indexing and slicing.
❖ Various Operations: Strings support various operations like concatenation,
repetition, and formatting.
❖ Escape Characters: Allows the inclusion of special characters using escape
sequences (e.g., '\n' for a new line, '\t' for a tab).
❖ String Methods: Python provides numerous built-in methods for string
manipulation and formatting.

Creating and Accessing Strings:

Ex:
# Creating strings
single_quoted = 'Hello, World!'
double_quoted = "Hello, World!"
# Accessing characters using indexing
print(single_quoted[0]) # Output: 'H'
print(double_quoted[-1]) # Output: '!'
# Slicing strings
print(single_quoted[0:5]) # Output: 'Hello'

String concatenation and repetition:

Ex:
string1 = 'Hello'
string2 = 'World'
# Concatenation
concatenated_string = string1 + ', ' + string2 + '!'
print(concatenated_string) # Output: 'Hello, World!'
# Repetition
repeated_string = string1 * 3
print(repeated_string) # Output: 'HelloHelloHello'

String Methods:
Ex:
my_string = 'Hello, World!'
# Length of a string
print(len(my_string)) # Output: 13
# Changing case
print(my_string.lower()) # Output: 'hello, world!'
print(my_string.upper()) # Output: 'HELLO, WORLD!'
# Finding and replacing
print(my_string.find('World')) # Output: 7
print(my_string.replace('Hello', 'Hi')) # Output: 'Hi, World!'
DAY-4

CONDITIONAL STATEMENTS:

Conditional statements are fundamental in programming and logic. They allow you
to execute certain code or actions based on whether a condition is true or false.

IF CONDITION:
In Python, the if statement is used to conditionally execute a block of code based
on whether a given condition is true. If the condition is true, the code inside the if
block will be executed. If the condition is false, the code inside the if block will be
skipped.

SYNTAX:

if condition:
# code to be executed if the condition is true

IF-ELSE CONDITION:
if-else conditions are fundamental in programming as they provide a way to
execute different blocks of code based on whether a condition is true or false. It
allows your program to take one of two paths based on the evaluation of a
condition.
SYNTAX:

if condition:
# code to be executed if the condition is true
else:
# code to be executed if the condition is false

EX:

x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")

In this example, if x is greater than 5, the program will print "x is greater than 5".
Otherwise, it will print "x is not greater than 5".
ELSE IF CONDITION:
The "else if" condition in Python is represented by elif. It allows you to check
multiple conditions in sequence after an initial if statement.

SYNTAX:

if condition1:
# code to be executed if condition1 is true
elif condition2:
# code to be executed if condition2 is true
elif condition3:
# code to be executed if condition3 is true
else:
# code to be executed if none of the conditions are true

EX:

x = 10
if x > 10:
print("x is greater than 10")
elif x < 10:
print("x is less than 10")
else:
print("x is equal to 10")

In this example:
o If x is greater than 10, it prints "x is greater than 10".
o If x is less than 10, it prints "x is less than 10".
o If neither condition is true, it prints "x is equal to 10".
The elif statement allows you to chain multiple conditions after an initial if
statement, providing a way to check and respond to various scenarios sequentially.

NESTED IF CONDITIONS:
Nested if statements in Python refer to having one if statement inside another. This
means you can have an if statement within the block of code executed when
another if statement is true.

SYNTAX:

if condition1:
# code block executed if condition1 is true
if condition2:
# code block executed if both condition1 and condition2 are true
else:
# code block executed if condition1 is true but condition2 is false
else:
# code block executed if condition1 is false

This structure demonstrates how one if statement can be nested within another. The
inner if statement is only evaluated if the outer if statement's condition is True. If
the outer condition is False, the interpreter moves to the else block associated with
the outer if statement.

EX:

x = 10
y=5
if x > 5:
print("x is greater than 5")
if y > 2:
print("y is also greater than 2")
else:
print("y is not greater than 2")
else:
print("x is not greater than 5")

MIND MAP OF PYTHON:

Python, known for its simplicity and readability, comprises fundamental concepts
like data types (numeric, text, boolean), control structures (loops, conditionals),
and functions. Advanced aspects include object-oriented programming (OOP),
error handling with exceptions, modules, functional programming tools, and
iterators/generators. It boasts extensive libraries for diverse purposes: data science
(NumPy, Pandas), visualization (Matplotlib), machine learning (TensorFlow), web
frameworks (Flask, Django), and more. Python finds applications in web
development, data analysis, machine learning, scripting, and automation.
Supported by powerful tools and environments such as IDEs (PyCharm, VS Code),
package managers (pip), virtual environments (venv, conda), and debugging tools
(pdb), Python offers a robust ecosystem for various domains and levels of
expertise.

A mind map of Python serves as a visual representation outlining the


comprehensive landscape of the Python programming language. It systematically
organizes and illustrates various components, functionalities, and applications
within Python, offering a structured overview of its:
➢ Core Concepts: Covers fundamental aspects like data types (numeric, text,
boolean), variables, operators, control structures (if-else, loops), functions,
and input/output handling.
➢ Advanced Features: Includes more intricate topics such as object-oriented
programming (OOP), error handling (exceptions), modules, functional
programming tools, generators/iterators, and comprehensions.
➢ Libraries and Frameworks: Encompasses a wide array of third-party
libraries and frameworks catering to data science, visualization, machine
learning, web development, and more.
➢ Application Areas: Explores the practical domains where Python finds
extensive usage, including web development, data analysis, machine
learning, scripting, and automation.
➢ Tools and Environments: Highlights the various tools, development
environments (IDEs), package managers, virtual environments, and
debugging tools that augment Python's development process.

LOOPS IN PYTHON:

In Python, loops are used to execute a block of code repeatedly as long as a


specified condition is true. There are mainly two types of loops: for loops and
while loops.

FOR LOOP:
The for loop is used to iterate over a sequence (like a list, tuple, string, or range) or
any iterable object.

SYNTAX:
for item in sequence:
# code block to be executed for each item
EX:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)

WHILE LOOP:
The while loop repeats a block of code as long as a specified condition is True.

SYNTAX:
while condition:
# code block to be executed as long as the condition is true

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

Loop Control Statements:


Python also provides loop control statements:

❖ break: Terminates the loop.


❖ continue: Skips the current iteration and continues with the next one.
❖ pass: Acts as a placeholder, doing nothing when executed. It's used when a
statement is syntactically required but you don’t want any code to execute.

RANGE FUNCTION:
In Python, the range() function is used to generate a sequence of numbers. It's
commonly used with loops to iterate a specific number of times or to generate a
sequence of numbers within a certain range.

SYNTAX:
range(stop)
range(start, stop[, step])

EXAMPLES:

1. Using range() in a for loop:


EX:
for i in range(5):
print(i)
This will print numbers from 0 to 4.
2. Specifying start, stop, and step:

EX:
for i in range(1, 10, 2):
print(i)
This will print odd numbers from 1 to 9 (start at 1, increment by 2).
3. Creating a list using range():
EX:
my_list = list(range(5))
print(my_list)
This will create a list [0, 1, 2, 3, 4].

NESTED FOR LOOPS:


Nested for loops in Python allow you to have one loop inside another loop. This
setup is commonly used when dealing with multidimensional data structures like
nested lists or when you need to perform operations on every combination of
elements from multiple sequences.
EX:
matrix = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]
for row in matrix:
for element in row:
print(element, end=' ')
print() # New line after each row
OUTPUT:
123
456
789
CONTINUE STATEMENT:
In Python, the continue statement is used inside loops to skip the current iteration
and continue with the next iteration of the loop. When the continue statement is
encountered within a loop, the remaining code inside the loop for that particular
iteration is skipped, and the loop moves to the next iteration.
SYNTAX:
for item in sequence:
if condition:
continue
# code here will be executed unless the continue statement is triggered
EX:
for i in range(5):
if i == 2:
continue
print(i)
OUTPUT:
0
1
3
4
BREAK:
In Python, the break statement is used to immediately terminate a loop when a
certain condition is met. When the break statement is encountered within a loop, it
exits the loop's execution, regardless of whether the loop's conditions have been
fully satisfied or not.
SYNTAX:
for item in sequence:
if condition:
break
# code here will be executed unless the break statement is triggered
EX:
for i in range(5):
if i == 3:
break
print(i)
OUTPUT: 0 1 2
PASS:
In Python, the pass statement is a null operation that does nothing when executed.
It's used as a placeholder when syntactically a statement is required, but no action
is needed or intended to be taken.
SYNTAX:
if condition:
pass
EX:
for i in range(5):
if i == 2:
pass
else:
print(i)
OUTPUT:
0
1
3
4
CIRCULATE THE VALUE OF N VARIABLE:
"Circulating" the value of a variable in Python often refers to cycling through a
range of values. Let's break down how you might achieve this:
Objective: Create a program that circulates the value of a variable n within a
defined range, displaying each rotated value.
Approach: We'll use a loop to repeatedly update the value of n and print each
rotated value.
EX:
# Current value of n
n=5
# Rotating the value of n by 1
n = (n + 1) % 10 # Modulo 10 ensures the value stays within a range (e.g., 0-9)
print("Rotated value of n:", n) # Output the rotated value of n
OUTPUT:
Rotated value of n: 6
This code will output the rotated value of n, which in this case is 6 because the
initial value of n was 5, and it was rotated by 1.
DISTANCE BETWEEN TWO POINTS:
The distance between two points in a 2-dimensional space (x, y) can be calculated
using the Euclidean distance formula. This formula derives the straight-line
distance between the two points.
EX:
import math
# Function to calculate distance between two points
def distance_between_points(x1, y1, x2, y2):
return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
# Example points
point1 = (1, 3)
point2 = (4, 7)
# Unpack coordinates
x1, y1 = point1
x2, y2 = point2
# Calculate distance
distance = distance_between_points(x1, y1, x2, y2)
print(f"The distance between {point1} and {point2} is: {distance}")
OUTPUT:
The distance between (1, 3) and (4, 7) is: 5.0
DAY-5

FOR ELSE LOOP:


In Python, the for...else loop is a construct that allows the execution of an else
block after the completion of a for loop, but only if the loop completes normally
without any break statements being encountered.
EX:
# Example using for...else loop to check for prime numbers
numbers = [6, 7, 11, 13, 15]
for num in numbers:
for i in range(2, num): # Check for factors
if num % i == 0:
print(f"{num} is not a prime number.")
break
else:
print(f"{num} is a prime number.")

OUTPUT:

6 is not a prime number.


7 is a prime number.
11 is a prime number.
13 is a prime number.
15 is not a prime number.

ENUMERATING THE OBJECTS OF A LIST WITH SEQUENTIAL:

Enumerating objects within a list using sequential numbering can be achieved in


Python using the enumerate() function. This function returns both the index and the
corresponding value of each item within an iterable, such as a list.

EX:

# Example of enumerating objects in a list with sequential numbering


my_list = ['apple', 'banana', 'orange', 'grape']
for index, fruit in enumerate(my_list, start=1):
print(f"Object {index}: {fruit}")

OUTPUT:
Object 1: apple
Object 2: banana
Object 3: orange
Object 4: grape
WHILE LOOP:
The while loop in Python is used to execute a block of code as long as a specified
condition is true. It continues iterating as long as the condition remains true.

EX:
# Example using a while loop to count from 1 to 5
count = 1
while count <= 5:
print(count)
count += 1

OUTPUT:
1
2
3
4
5

This example demonstrates how the while loop continues to execute as long as the
condition (count <= 5) remains true, incrementing count in each iteration until the
condition is no longer satisfied.

NESTED LOOPS:
Nested loops in Python refer to having one loop inside another. This is a common
technique used when you need to iterate over multiple dimensions or perform
repetitive tasks in a structured manner.

NESTED FOR LOOP:


Nested for loops refer to a situation where one for loop is placed inside another.
This structure allows for more complex iterations, such as traversing through
elements in a 2D array or generating patterns.

EX:
for i in range(3): # Outer loop
for j in range(2): # Inner loop
print(f"Outer loop: {i}, Inner loop: {j}")

OUTPUT:

Outer loop: 0, Inner loop: 0


Outer loop: 0, Inner loop: 1
Outer loop: 1, Inner loop: 0
Outer loop: 1, Inner loop: 1
Outer loop: 2, Inner loop: 0
Outer loop: 2, Inner loop: 1

NESTED WHILE LOOP:


Nested while loops involve one while loop placed within another while loop. This
arrangement allows for more intricate control flow and repetitive operations.

EX:
outer = 1
while outer <= 3: # Outer loop
inner = 1
while inner <= 2: # Inner loop
print(f"Outer loop: {outer}, Inner loop: {inner}")
inner += 1
outer += 1

OUTPUT:

Outer loop: 1, Inner loop: 1


Outer loop: 1, Inner loop: 2
Outer loop: 2, Inner loop: 1
Outer loop: 2, Inner loop: 2
Outer loop: 3, Inner loop: 1
Outer loop: 3, Inner loop: 2

VARIABLE LENGTH POSITIONAL ARGUMENTS:

In Python, you can handle a variable number of positional arguments within a


function using the *args syntax. This allows you to pass an arbitrary number of
arguments to a function.
EX:
def add_numbers(*args):
result = 0
for num in args:
result += num
return result
# Passing different numbers of arguments
sum1 = add_numbers(1, 2, 3)
sum2 = add_numbers(1, 2, 3, 4, 5)
print(sum1) # Output: 6
print(sum2) # Output: 15
VARIABLE LENGTH KEYWORD ARGUMENTS:
In Python, you can handle a variable number of keyword arguments using
**kwargs. This allows you to pass an arbitrary number of keyword arguments to a
function.

EX:
def print_values(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
# Passing different numbers of keyword arguments
print_values(a=1, b=2)
print_values(x=10, y=20, z=30)

OUTPUT:
a: 1
b: 2
x: 10
y: 20
z: 30

PRINT RIGHT TRIANGLE PATTERN:


PATTERNS:
Patterns in Python can be created using nested loops to control the structure and
repetition of characters or symbols.

EX:
def right_angle_triangle(n):
for i in range(1, n + 1):
print("* " * i)
# Example call with n=5
right_angle_triangle(5)

OUTPUT:
*
**
***
****
*****
Explanation:
• The right_angle_triangle function takes an argument n, which determines
the height of the triangle (number of rows).
• It uses a loop to iterate from 1 to n, inclusive.
• In each iteration, it prints i asterisks followed by spaces, creating a right-
angled triangle
DAY-6

FUNCTIONAL CALL STACK:


In Python, the call stack operates similarly to other programming languages. When
a function is called, a frame for that function is added to the call stack, and it's
removed when the function completes its execution.

EX:
def function_a():
print("Starting function_a")
function_b()
print("Back to function_a")
def function_b():
print("Starting function_b")
# Simulate a nested function call
function_c()
print("Back to function_b")
def function_c():
print("Inside function_c")
# Starting point of the program
print("Initial call to function_a")
function_a()
print("Program completed")

OUTPUT:

Initial call to function_a


Starting function_a
Starting function_b
Inside function_c
Back to function_b
Back to function_a
Program completed

LOCALS:
In Python, the locals() function returns a dictionary containing the current local
symbol table. It represents the local namespace and includes all variables,
functions, and their values within the current scope.

EX:

def example_function():
a = 10
b = "Hello"
print("Locals inside example_function:", locals())
example_function()

OUTPUT:
Locals inside example_function: {'a': 10, 'b': 'Hello'}

GLOBALS:
In Python, the globals() function returns a dictionary representing the global
symbol table. This dictionary contains all the variables, functions, and their values
defined in the global scope of the program.

EX:
global_var = "I am a global variable"
def example_function():
local_var = "I am a local variable"
print("Globals inside example_function:", globals())
example_function()

OUTPUT:
Globals inside example_function: {'__name__': '__main__', '__doc__': None,
'__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader
object at 0x7f84cf2b30d0>, '__spec__': None, '__annotations__': {}, '__builtins__':
<module 'builtins' (built-in)>, 'global_var': 'I am a global variable',
'example_function': <function example_function at 0x7f84cf29e700>}

RECURSION FUNCTION:
A recursive function in programming is a function that calls itself within its own
definition. It's a powerful technique used to solve problems where the solution
depends on solutions to smaller instances of the same problem.

EX:
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
# Calculate factorial of 5
number = 5
result = factorial(number)
print(f"The factorial of {number} is {result}")

OUTPUT:
The factorial of 5 is 120
LIST COMPREHENSION:
List comprehension is a concise way to create lists in Python. It allows you to
create a new list by iterating over an existing iterable (such as a list, tuple, string,
etc.) and applying an expression to each element.

EX:
squares = [x ** 2 for x in range(1, 6)]
print(squares)

OUTPUT:
[1, 4, 9, 16, 25]

DICTIONARY COMPREHENSION:
Dictionary comprehension is similar to list comprehension, but it creates
dictionaries instead of lists. It allows you to generate dictionaries using a concise
and readable syntax by iterating over iterable objects and defining key-value pairs.

EX:
squares_dict = {x: x ** 2 for x in range(1, 6)}
print(squares_dict)

OUTPUT:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

ZIP AND UNZIP:


ZIP:
The zip() function takes multiple iterables and aggregates them into a single
iterable of tuples. Each tuple contains elements from the input iterables at the same
index.

EX:
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
zipped = zip(list1, list2)
# zipped is now an iterable of tuples
for item in zipped:
print(item)

OUTPUT:
(1, 'a')
(2, 'b')
(3, 'c')
UNZIP:
To "unzip," you can use the zip() function in conjunction with the unpacking
operator *. This allows you to separate the elements back into individual lists or
iterables.

EX:
zipped = [(1, 'a'), (2, 'b'), (3, 'c')]
numbers,letters = list(zip(*zipped))
# unzipped contains separate lists
print(“numbers”,numbers)
print(“letters”,letters)

OUTPUT:
Numbers:(1,2,3)
Letters:(‘a’,’b’,’c’)

BUILT-IN SORT FUNCTIONS:


In Python, there are several ways to sort lists and other iterable objects. Here are
some of the built-in sorting functions and methods available:

Using sorted() function:


EX:
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_list = sorted(my_list)
print(sorted_list)

OUTPUT:
[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

Using sort() method:


EX:
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
my_list.sort()
print(my_list)

OUTPUT:
[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

Sorting in Descending Order:


EX:
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
# Using sorted() for descending order
sorted_desc = sorted(my_list, reverse=True)
print(sorted_desc)
# Using sort() method for descending order
my_list.sort(reverse=True)
print(my_list)

OUTPUT:
[9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]
[9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]

LAMBDA FUNCTION:
Lambda functions, also known as anonymous functions, are small, unnamed
functions in Python that can have any number of arguments but can only have one
expression. They are defined using the lambda keyword and are often used when a
simple function is needed for a short period of time.

EX:
square = lambda x: x ** 2
result = square(5)
print(result)

OUTPUT:
25

MAP() FUNCTION:
The map() function in Python applies a specified function to each item in an
iterable (like a list) and returns an iterator that yields the results. It takes two
arguments: the function you want to apply and the iterable you want to apply it to.

EX:
numbers = [1, 2, 3, 4, 5]
doubled_numbers = list(map(lambda x: x * 2, numbers))
print(doubled_numbers)

OUTPUT:
[2, 4, 6, 8, 10]

FILTER():
The filter() function in Python is used to filter elements from an iterable (like a list)
based on a specified function. It returns an iterator that yields the elements for
which the function returns True.

EX:
# Function to check if a number is even
def is_even(num):
return num % 2 == 0
# List of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Using filter to get even numbers from the list
even_numbers = filter(is_even, numbers)
# Converting the iterator to a list to see the results
result = list(even_numbers)
print(result)

OUTPUT:
[2, 4, 6, 8, 10]
DAY-7

ITERATOR:
An iterator in Python represents a sequence of data, allowing you to traverse
through elements one by one. It provides a way to access the elements of a
collection without needing to know the underlying structure of that collection.

Iterators implement two essential methods: __iter__() and __next__(). The


__iter__() method returns the iterator object itself, and the __next__() method
returns the next element in the sequence. Once all elements are exhausted, it raises
a StopIteration exception.

EX:
# Define an iterable class
class MyIterator:
def __init__(self, data):
self.data = data
self.index = 0
def __iter__(self):
return self
def __next__(self):
if self.index < len(self.data):
current = self.data[self.index]
self.index += 1
return current
else:
raise StopIteration
# Creating an instance of the iterator
my_list = [1, 2, 3, 4, 5]
my_iterator = MyIterator(my_list)
# Using the iterator to access elements
for element in my_iterator:
print(element)

OUTPUT:
1
2
3
4
5

GENERATOR:
Generators in Python are a convenient way to create iterators using a special type
of function or expression. They allow you to generate a sequence of values over
time without storing them in memory all at once. Generators use the yield keyword
to produce a series of values when iterated upon.

EX:
def even_numbers(limit):
num = 0
while num < limit:
yield num
num += 2
# Using the generator to print even numbers up to 10
gen = even_numbers(10)
for number in gen:
print(number)

OUTPUT:
0
2
4
6
8

FILE HANDLING AND ITS OPERATIONS:


File handling in Python involves various operations to read from and write to files.
Here are some fundamental file operations:

1.OPENING A FILE:
To open a file, use the open() function. It requires at least two arguments: the file
name/path and the mode ('r' for reading, 'w' for writing, 'a' for appending, 'r+' for
both reading and writing, etc.).

SYNTAX:
# Open a file in read mode
file = open('filename.txt', 'r')

2.READING FROM A FILE:


You can read the contents of a file using various methods like read(), readline(), or
readlines().
SYNTAX:
# Reading the entire file
content = file.read()
# Reading a single line
line = file.readline()
# Reading all lines into a list
lines = file.readlines()
3.WRITING TO A FILE:
To write data to a file, open it in 'w' mode or 'a' mode (to append).

SYNTAX:
# Open a file in write mode and write content
with open('filename.txt', 'w') as file:
file.write('This is some content to be written.')

4.CLOSING A FILE:
It's good practice to close the file once you're done using it to free up system
resources.

SYNTAX:
file.close()

EXCEPTION HANDLING:
Exception handling in programming is a mechanism that allows you to gracefully
manage errors or exceptional situations that might occur during program execution.
In Python, exception handling involves using try, except, else, and finally blocks to
handle different types of exceptions.

SYNTAX:
try:
with open('filename.txt', 'r') as file:
content = file.read()
print(content)
except FileNotFoundError:
print("The file doesn't exist.")
except Exception as e:
print("An error occurred:", e)

EX:
try:
# Code that might raise an exception
result = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
# Handle the specific type of exception (division by zero in this case)
print("Division by zero is not allowed")
except Exception as e:
# A more generic exception handler to catch any other exceptions
print(f"An error occurred: {e}")
finally:
# This block is executed regardless of whether an exception occurred or not
print("Cleanup or final tasks")
OUTPUT:
Division by zero is not allowed
Cleanup or final tasks

USER DEFINED EXCEPTIONS:


User-defined exceptions allow developers to create their own custom exception
types in programming languages. This is particularly useful when you need to
handle specific error conditions that aren't covered by the built-in exceptions.

EX:
# Define a custom exception class
class CustomError(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return f'CustomError: {self.message}'
# Use the custom exception
def divide(a, b):
if b == 0:
raise CustomError("Division by zero is not allowed")
return a / b
# Handling the custom exception
try:
result = divide(10, 0) # This will raise CustomError
except CustomError as e:
print(e) # Print the custom error message

OUTPUT:
CustomError: Division by zero is not allowed
DAY-8

CLASS AND OBJECT:


CLASS:
In Python, a class is a user-defined data type that contains both the data itself and
the methods that may be used to manipulate it. In a sense, classes serve as a
template to create objects. They provide the characteristics and operations that the
objects will employ.

Suppose a class is a prototype of a building. A building contains all the details


about the floor, rooms, doors, windows, etc. we can make as many buildings as we
want, based on these details. Hence, the building can be seen as a class, and we can
create as many objects of this class.

SYNTAX:
class ClassName:
#statement_suite

EX:
class Person:
def __init__(self, name, age):
# This is the constructor method that is called when creating a new Person
object
# It takes two parameters, name and age, and initializes them as attributes of
the object
self.name = name
self.age = age
def greet(self):
# This is a method of the Person class that prints a greeting message
print("Hello, my name is " + self.name)

OBJECT:
An object is a particular instance of a class with unique characteristics and
functions. After a class has been established, you may make objects based on it. By
using the class constructor, you may create an object of a class in Python. The
object's attributes are initialised in the constructor, which is a special procedure
with the name __init__.

SYNTAX:
# Declare an object of a class
object_name = Class_Name(arguments)
EX:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print("Hello, my name is " + self.name)
# Create a new instance of the Person class and assign it to the variable person1
person1 = Person("Ayan", 25)
person1.greet()

INHERITANCE:
Inheritance is an important aspect of the object-oriented paradigm. Inheritance
provides code reusability to the program because we can use an existing class to
create a new class instead of creating it from scratch.
In inheritance, the child class acquires the properties and can access all the data
members and functions defined in the parent class.

TYPES:
1.SINGLE INHERITANCE:
A subclass inherits from only one super class.
Ex:
# Parent class (base class)
class Vehicle:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def display_info(self):
return f"Vehicle: {self.year} {self.make} {self.model}"
# Child class (derived class)
class Car(Vehicle):
def __init__(self, make, model, year, num_doors):
super().__init__(make, model, year)
self.num_doors = num_doors
def car_info(self):
return f"{self.display_info()}, Doors: {self.num_doors}"
# Creating an instance of the derived class
my_car = Car("Toyota", "Corolla", 2020, 4)
# Accessing methods and properties
print(my_car.car_info())
2.MULTIPLE INHERITANCE:
This inheritance enables a child class to inherit from more than one parent class.
This type of inheritance is not supported by java classes, but python does support
this kind of inheritance.

EX:
#parent class 1
class A:
demo1=0
def fun1(self):
print(self.demo1)
#parent class 2
class B:
demo2=0
def fun2(self):
print(self.demo2)
#child class
class C(A, B):
def fun3(self):
print(“Hey there, you are in the child class”)
# Main code
c = C()
c.demo1 = 10
c.demo2 = 5
c.fun3()
print(“first number is : “,c.demo1)
print(“second number is : “,c.demo2)

3.MULTI LEVEL INHERITANCE:


In multilevel inheritance, the transfer of the properties of characteristics is done to
more than one class hierarchically. To get a better visualization we can consider it
as an ancestor to grandchildren relation or a root to leaf in a tree with more than
one level.

EX:
#parent class 1
class vehicle:
def functioning(self):
print(“vehicles are used for transportation”)
#child class 1
class car(vehicle):
def wheels(self):
print(“a car has 4 wheels”)
#child class 2
class electric_car(car):
def speciality(self):
print(“electric car runs on electricity”)
electric=electric_car()
electric.speciality()
electric.wheels()
electric.functioning()

4.HIERARCHICAL INHERITANCE:
This inheritance allows a class to host as a parent class for more than one child
class or subclass. This provides a benefit of sharing the functioning of methods
with multiple child classes, hence avoiding code duplication.

EX:
#parent class
class Parent:
def fun1(self):
print(“Hey there, you are in the parent class”)
#child class 1
class child1(Parent):
def fun2(self):
print(“Hey there, you are in the child class 1”)
#child class 2
class child2(Parent):
def fun3(self):
print(“Hey there, you are in the child class 2”)
#child class 3
class child3(Parent):
def fun4(self):
print(“Hey there, you are in the child class 3”)
# main program
child_obj1 = child3()
child_obj2 = child2()
child_obj3 = child1()
child_obj1.fun1()
child_obj1.fun4()
child_obj2.fun1()
child_obj2.fun3()
child_obj3.fun1()
child_obj3.fun2()

5.HYBRID INHERITANCE:
An inheritance is said hybrid inheritance if more than one type of inheritance is
implemented in the same code. This feature enables the user to utilize the feature
of inheritance at its best. This satisfies the requirement of implementing a code that
needs multiple inheritances in implementation.
EX:
class A:
def fun1(self):
print(“Hey there, you are in class A”)class B(A):
def fun2(self):
print(“Hey there, you are in class B”)class C(A):
def fun3(self):
print(“Hey there, you are in class C”)class D(C,A): #line 13
def fun4(self):
print(“Hey there, you are in the class D”)#main program
ref = D()
ref.fun4()
ref.fun3()
ref.fun1()

POLYMORPHISM:
Polymorphism is a key feature that allows objects of different data types to be
treated as objects of a common type. It enables you to write more flexible and
reusable code by providing a consistent interface to different types of objects.

EX:

class Dog:
def sound(self):
return "Woof!"
class Cat:
def sound(self):
return "Meow!"
def make_sound(animal):
print(animal.sound())
dog = Dog()
cat = Cat()
make_sound(dog) # Output: Woof!
make_sound(cat) # Output: Meow!

ADVANTAGES:

➢ Code Reusability: Polymorphism allows you to write functions or methods


that can work with objects of various types, promoting code reuse. You can
create generic functions that can operate on different objects sharing a
common interface.
➢ Flexibility and Extensibility: It enables you to design more flexible code that
can accommodate new classes or types without modifying existing code.
You can add new classes that adhere to the common interface, and the code
will work seamlessly with these new types.
➢ Readability and Maintainability: By using polymorphism, code becomes
more readable and easier to maintain. Since it operates based on a shared
interface, understanding and modifying the code is more straightforward.
➢ Encourages Abstraction: Polymorphism encourages the use of abstract
classes or interfaces, promoting good design practices by focusing on
behaviors and abstract concepts rather than specific implementations.
➢ Enhances Polymorphic Behavior: With features like method overriding and
method overloading, Python allows for more sophisticated polymorphic
behavior, enabling subclasses to provide their own implementation of
methods.

MODULES:
In Python, modules are files containing Python code that can be imported and used
in other Python files. They serve as containers for functions, classes, and variables,
allowing you to organize code into reusable components.

TYPES:
1.BUILT-IN MODULES:
These are modules that come pre-installed with Python. Examples include math,
os, random, datetime, etc.

EX:
import math
result = math.sqrt(25)
print("Square root:", result)

2.STANDARD LIBRARY MODULES:


Python's standard library consists of numerous modules covering a wide range of
functionalities. They are available for use without needing to install them
separately. Examples include sys, os, datetime, json, etc.

EX:
import datetime
current_time = datetime.datetime.now()
print("Current time:", current_time)
3.THIRD PARTY MODULES:
These modules are developed by third-party developers and are not part of the
standard Python installation. They extend Python's capabilities for various
purposes and can be installed using package managers like pip.

EX:
import requests
response = requests.get('https://www.example.com')
print("Status Code:", response.status_code)

PACKAGE:
In Python, a package is a way of organizing related modules into a single directory
hierarchy. Packages are directories that contain a special file called __init__.py,
and they can contain modules, sub-packages, and other resources.

TO CREATE A PACKAGE:
1.CREATE A DIRECTORY STRUCTURE:
Start by creating a directory for your package. Within that directory, you can create
Python files that will be part of your package.

EX:
my_package/

├── __init__.py
├── module1.py
└── module2.py

2. The __init__.py File:


This file can be empty, but it signifies that the directory is a Python package. It can
also include initialization code that will be executed when the package is imported.
EX:
# __init__.py
# Initialization code (optional)

3.Using the Package:


from my_package import module1, module2
module1.function1()
module2.function2()

4.SUB PACKAGES:
Packages can also contain sub-packages. For instance, within my_package, you
might have another package sub_package:
EX:

my_package/

├── __init__.py
├── module1.py
├── module2.py
└── sub_package/
├── __init__.py
├── module3.py
└── module4.py

REGULAR EXPRESSIONS:
Regular expressions (regex) are powerful tools used to search, match, and
manipulate text based on patterns. In Python, the re module is used for working
with regular expressions.

EX:

import re
text = "Example of text with the word 'example' and 'exercise'."
pattern = r'ex' # This regex pattern looks for the substring 'ex'
matches = re.findall(pattern, text)
print(matches) # Output: ['ex', 'ex', 'ex']
DAY-9

1.REPLACE STRING:
In Python, you can replace parts of a string using various methods. The
str.replace() method is one of the simplest ways to perform string replacement.

EX:
# Original string
original_string = "Hello, World! Hello, Universe!"
# Replacing 'Hello' with 'Hi'
new_string = original_string.replace('Hello', 'Hi')
print(new_string)

OUTPUT:
Hi, World! Hi, Universe!

2.REMOVE WHITE SPACES:


To remove white spaces from a string in Python, you can use the replace() method
or various other techniques.

EX:
# Original string with spaces
original_string = "This is a string with spaces"
# Removing spaces using replace
new_string = original_string.replace(" ", "")
print(new_string)

OUTPUT:
Thisisastringwithspaces

NUMPY:
NumPy is a powerful Python library used for numerical computing. It provides
support for multidimensional arrays, along with a collection of mathematical
functions to operate on these arrays efficiently.

INSTALLATION:

PIP INSTALL NUMPY

IMPORTING NUMPY:

Import numpy as np
EX:
import numpy as np
# Creating arrays
arr_1d = np.array([1, 2, 3, 4, 5])
arr_2d = np.array([[1, 2, 3], [4, 5, 6]])
# Basic operations
result_add = arr_1d + arr_1d
result_mul = arr_1d * arr_1d
dot_product = np.dot(arr_1d, arr_1d)
arr_2d_transpose = arr_2d.T
# NumPy functions
total = np.sum(arr_1d)
mean_val = np.mean(arr_1d)
std_dev = np.std(arr_1d)
reshaped_array = arr_1d.reshape((5, 1))
# Indexing and Slicing
element = arr_1d[0]
slice_arr = arr_1d[1:4]
# Displaying output
print("Array 1D:", arr_1d)
print("Array 2D:\n", arr_2d)
print("Addition:", result_add)
print("Multiplication:", result_mul)
print("Dot Product:", dot_product)
print("Transpose of 2D Array:\n", arr_2d_transpose)
print("Total:", total)
print("Mean:", mean_val)
print("Standard Deviation:", std_dev)
print("Reshaped Array:\n", reshaped_array)
print("Element at index 0:", element)
print("Sliced Array:", slice_arr)

OUTPUT:
Array 1D: [1 2 3 4 5]
Array 2D:
[[1 2 3]
[4 5 6]]
Addition: [ 2 4 6 8 10]
Multiplication: [ 1 4 9 16 25]
Dot Product: 55
Transpose of 2D Array:
[[1 4]
[2 5]
[3 6]]
Total: 15
Mean: 3.0
Standard Deviation: 1.4142135623730951
Reshaped Array:
[[1]
[2]
[3]
[4]
[5]]
Element at index 0: 1
Sliced Array: [2 3 4]

NUMPY BROAD CASTING:


Broadcasting in NumPy is a powerful feature that allows for arithmetic operations
between arrays of different shapes.

EX:
import numpy as np
# Creating arrays
arr_broadcast = np.array([[1, 2, 3], [4, 5, 6]])
scalar_broadcast = 10
# Broadcasting: adding a scalar to a 2D array
result_broadcast = arr_broadcast + scalar_broadcast
# Displaying arrays and result
print("Array:\n", arr_broadcast)
print("Scalar:\n", scalar_broadcast)
print("Result of Broadcasting:\n", result_broadcast)

OUTPUT:
Array:
[[1 2 3]
[4 5 6]]
Scalar:
10
Result of Broadcasting:
[[11 12 13]
[14 15 16]]

DATA STRUCTURES:
ARRAYS:

Arrays provide a versatile way to store and manipulate collections of data in


programming languages. The operations available may vary slightly depending on
the programming language, but the basic concepts remain similar across most
languages.

Python's standard library has array module. The array class in it allows you to
construct an array of three basic types, integer, float and Unicode characters.
SYNTAX:

import array
obj = array.array(typecode[, initializer])

Parameters
• typecode − The typecode character used to create the array.
• initializer − array initialized from the optional value, which must be a list, a
bytes-like object, or iterable over elements of the appropriate type.

EX:
import array as arr
# creating an array with integer type
a = arr.array('i', [1, 2, 3])
print (type(a), a)
# creating an array with char type
a = arr.array('u', 'BAT')
print (type(a), a)
# creating an array with float type
a = arr.array('d', [1.1, 2.2, 3.3])
print (type(a), a)

OUTPUT:
<class 'array.array'> array('i', [1, 2, 3])
<class 'array.array'> array('u', 'BAT')
<class 'array.array'> array('d', [1.1, 2.2, 3.3])

Arrays are sequence types and behave very much like lists, except that the type of
objects stored in them is constrained.
DAY-10

PANDAS:

Pandas is a versatile library in Python for data manipulation and analysis.

INSTALLATION:

Pip install pandas

Ex:
import pandas as pd
# Creating a DataFrame
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'David'],
'Age': [25, 30, 22, 35],
'City': ['New York', 'San Francisco', 'Los Angeles', 'Chicago']
}
df = pd.DataFrame(data)
# Displaying the DataFrame
print("Original DataFrame:")
print(df)
print("\n")
# Filtering data based on a condition (age greater than 25)
filtered_data = df[df['Age'] > 25]
print("Filtered Data (Age > 25):")
print(filtered_data)
print("\n")
# Adding a new column
df['Country'] = 'USA'
print("DataFrame with Added 'Country' Column:")
print(df)

OUTPUT:
Original DataFrame:
Name Age City
0 Alice 25 New York
1 Bob 30 San Francisco
2 Charlie 22 Los Angeles
3 David 35 Chicago
Filtered Data (Age > 25):
Name Age City
1 Bob 30 San Francisco
3 David 35 Chicago
DataFrame with Added 'Country' Column:
Name Age City Country
0 Alice 25 New York USA
1 Bob 30 San Francisco USA
2 Charlie 22 Los Angeles USA
3 David 35 Chicago USA

ADVANTAGES:

❖ DataFrame & Series: Offers powerful data structures, DataFrame (2D) and
Series (1D), for flexible data handling.
❖ Ease of Data Handling: Simplifies reading/writing data from/to various file
formats and handles missing data efficiently.
❖ Data Manipulation: Provides extensive functionalities for filtering,
transforming, aggregating, and cleaning data.
❖ Flexible Operations: Handles large datasets, supports merging/joining, and
offers robust reshaping capabilities.
❖ Time Series Analysis: Excellent support for time-based data analysis,
including date range generation and statistical analysis.
❖ Integration: Seamlessly integrates with other Python libraries like NumPy,
Matplotlib, and scikit-learn.
❖ Performance: Optimized for high performance, leveraging NumPy arrays
and suitable for rapid data analysis.
❖ Customization: Allows the application of custom functions and methods to
data, enabling tailored data processing.
❖ Data Visualization: Basic plotting functionalities and integration with
Matplotlib for creating various visualizations.
❖ Documentation: Well-documented with extensive examples, making it
accessible for users of all levels.
❖ Community Support: Large user community, active development, ensuring
continuous improvement and support.

DISADVANTAGES:

❖ High Memory Usage: Handling large datasets can consume significant


memory, impacting performance on machines with limited resources.
❖ Performance Issues: Operations on massive datasets might be slower
compared to specialized big data processing tools like Apache Spark.
❖ Limited Handling of Some Data Types: Not as efficient with certain data
types like images, audio, or video data compared to specialized libraries.
❖ Mutable DataFrames: Mutable nature of DataFrame objects can lead to
unexpected errors if not handled carefully during operations.
❖ Complex Operations: Advanced operations might require a deep
understanding of Pandas functionalities, resulting in a steeper learning curve
for some users.
❖ Lack of Native Parallel Processing: Pandas lacks native support for parallel
processing, potentially affecting performance in computations.
❖ Challenges with Missing Data: Managing missing values in large datasets
might be challenging despite Pandas providing tools for handling missing
data.

DATA FRAMES:

DataFrames are tabular data structures commonly used in data manipulation and
analysis, especially in Python with libraries like Pandas. They resemble a table
with rows and columns, where each column can hold different types of data
(strings, integers, floats, etc.).

For instance, in Pandas, you can create a DataFrame from various sources such as
dictionaries, lists, NumPy arrays, or by reading data from files like CSV, Excel,
SQL databases, etc. Once created, you can perform operations like filtering rows,
selecting columns, aggregating data, joining multiple DataFrames, and much more.

EX:
import pandas as pd
# Creating a DataFrame from a dictionary
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'David'],
'Age': [25, 30, 35, 40],
'City': ['New York', 'San Francisco', 'Los Angeles', 'Chicago']
}
df = pd.DataFrame(data)
print(df)

OUTPUT:

Name Age City


0 Alice 25 New York
1 Bob 30 San Francisco
2 Charlie 35 Los Angeles
3 David 40 Chicago

You might also like