Data Science Virtual Internshi1
Data Science Virtual Internshi1
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
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.
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:
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-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.
• 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.
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:
4.ASSIGNMENT OPERATORS:
5.BITWISE OPERATORS:
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
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.
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]
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:
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.
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:
ADVANTAGES OF TUPLES:.
numbers = (1, 2, 3, 4, 5)
numbers = (1, 2, 3, 4, 5)
print(numbers[0]) # Output: 1
print(numbers[2]) # Output: 3
3.SETS:
1.Creating Sets:
EX:
# Creating a set
my_set = {1, 2, 3, 4}
my_list = [1, 2, 2, 3, 4, 4]
set_from_list = set(my_list)
Ex:
my_set.add(4)
my_set.remove(2)
3.Set Operations:
Ex:
set1 = {1, 2, 3}
set2 = {2, 3, 4}
# Union of sets
union = set1.union(set2)
# Intersection of sets
intersection = set1.intersection(set2)
difference = set1.difference(set2)
ADVANTAGES OF SETS:
DICTIONARY:
Dictionaries in Python are unordered collections of key-value pairs.
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'}
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.
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'
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")
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.
LOOPS IN PYTHON:
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
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:
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].
OUTPUT:
EX:
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.
EX:
for i in range(3): # Outer loop
for j in range(2): # Inner loop
print(f"Outer loop: {i}, Inner loop: {j}")
OUTPUT:
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:
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
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
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:
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}
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’)
OUTPUT:
[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
OUTPUT:
[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
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.
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
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')
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
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
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)
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:
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)
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
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!
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:
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]
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:
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:
INSTALLATION:
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:
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: