Chapter Two. UPDATEDpdf
Chapter Two. UPDATEDpdf
➢Many large companies use the Python programming language, including NASA, Google,
YouTube, BitTorrent, etc.
2
Why learn Python?
Python provides many useful features to the programmer:-
➢Easy to use and Read - Python's syntax is clear and easy to read, making it an
ideal language for both beginners and experienced programmers
➢Dynamically Typed - The data types of variables are determined during run-
time. We do not need to specify the data type of a variable during codes
➢Rich Standard Library - Python comes with several standard libraries that provide
ready-to-use modules and functions.
➢Wide Range of Libraries and Frameworks: Python has a vast collection of libraries and
frameworks, such as NumPy, Pandas, Django, and Flask, that can be used to solve a wide
range of problems. 4
Application area of python
➢Data Science: Data Science is a vast field, and Python is an important language
for this field because of its simplicity, ease of use, and availability of powerful
data analysis and visualization libraries like NumPy, Pandas, and Matplotlib.
➢Desktop Applications: Tkinter are useful libraries that can be used in GUI -
Graphical User Interface-based Desktop Applications. There are better
languages for this field, but it can be used with other languages for making
Applications.
➢Mobile Applications: While Python is not commonly used for creating mobile
applications, it can still be combined with frameworks like Kivy or BeeWare to
create cross-platform mobile applications.
5
Application area of python
➢Web Applications: Python is commonly used in web development on the
backend with frameworks like Django and Flask and on the front end with tools
like JavaScript HTML and CSS.
➢Machine Learning: Python is widely used for machine learning due to its
simplicity, ease of use, and availability of powerful machine learning libraries
➢Computer Vision or Image Processing Applications: Python can be used for
computer vision and image processing applications through powerful libraries
such as OpenCV and Scikit-image.
➢Gaming: Python has libraries like Pygame, which provide a platform for
developing games using Python.
DevOps: Python is widely used in DevOps for automation and scripting of
infrastructure management, configuration management, and deployment
processes
6
Python Popular Frameworks and Libraries
➢Python has wide range of libraries and frameworks widely used in various fields such
➢Web development (Server-side) - Django Flask, Pyramid, CherryPy
8
How to install Python
➢1. Visit the official website of Python https://www.python.org/downloads/ and choose your
version.
Once the download is completed, run the .exe
file to install Python. Now click on Install Now.
9
How to install Python IDE
➢1. PyCharm is a cross-platform editor developed by JetBrains. Pycharm
provides all the tools you need for productive Python development.
➢visit the website https://www.jetbrains.com/pycharm/download/ and Click the
“DOWNLOAD” link under the Community Section.
10
How to install Python IDE
➢2. Anaconda is a free and open source distribution of the Python and R
programming languages for large-scale data processing, predictive
analytics, and scientific computing.
➢An anaconda is an open-source free path that allows users to write programming in
Python language. The anaconda is termed by navigator as it includes various
applications of Python such as Spyder, Vs code, Jupiter notebook, PyCharm
➢How to install anaconda: Go to https://www.anaconda.com/download/ and
download Anaconda
11
Basic elements of Python:
➢Python Basic Syntax:-
➢There is no use of curly braces or semicolons in Python programming
language. It is an English-like language.
➢ But Python uses indentation to define a block of code. Indentation is
nothing but adding whitespace before the statement.
➢Python is a case-sensitive language, which means that uppercase and
lowercase letters are treated differently.
➢In Python, comments can be added using the '#' symbol. Any text written after
the '#' symbol is considered a comment.
➢Following triple-quoted string is also ignored by Python interpreter and can
be used as a multiline comments: example ''' This is a
multiline comment. ''' 12
Basic elements of Python:
Python print() Function
➢Python print() function is used to display output to the console or terminal.
➢It allows us to display text, variables and other data in a human readable
format.
# Displaying a string Output
print("Hello, World!")
# Displaying multiple values
name = "Aman"
age = 21
print("Name:", name, "Age:", age)
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as
long as the same type of quote starts and ends the string. 13
Python Variables:
Python Variables
➢Python variables are the reserved memory locations used to store values with in a
Python Program.
➢When you create a variable you reserve some space in the memory
➢Based on the data type of a variable, Python interpreter allocates memory and
decides what can be stored in the reserved memory
➢Python variables do not need explicit declaration to reserve memory space or you
can say to create a variable.
➢A Python variable is created automatically when you assign a value to it. The equal
sign (=) is used to assign values to variables. Print (counter)
Print(miles)
Example Print(name)
or print(coutter, miles,name)
14
Deleting Python Variables:
➢You can delete the reference to a number object by using the del statement.
The syntax of the del statement is
del var name
Example
➢You can get the data type of a Python variable using the python built-in
function type() as follows. Output
x = "Zara“
Example: Printing Variables Type y = 10
z = 10.10
print(type(x))
print(type(y))
print(type(z)) 15
Python Variables - Multiple Assignment:
➢ Python allows to initialize more than one variables in a single
statement.
➢In example A , three variables have same value.
Example A a=b=c=10 Output Output
a,b,c = 10,20,30
print (a,b,c) print (a,b,c)
17
Data Types in Python:
➢A data type represents a kind of value and determines what operations can be
done on it. It defines what type of data we are going to store in a variable.
18
Python Numeric Data Type
Python supports four different numerical types and each of them have built-in
classes in Python library, called int, bool, float and complex
19
Python Sequence Data Type
➢Sequence is a collection data type. It is an ordered collection of items. Items in the sequence
have a positional index starting with 0. It is conceptually similar to an array in C++.
➢Python strings are immutable which means when you perform an operation on
strings, you always produce a new string object of the same type, rather than
mutating an existing string
20
Python Sequence Data Type
➢A string is a non-numeric data type. Obviously, we cannot perform arithmetic
operations on it. However, operations such as slicing and concatenation can be
done.
➢Python's str class defines a number of useful methods for string processing.
Subsets of strings can be taken using the slice operator ([ ] and [:] ) with
indexes starting at 0 in the beginning of the string and working their way from
-1 at the end.
➢The plus (+) sign is the string concatenation operator and the asterisk (*) is
the repetition operator in Python.
21
Python Sequence Data Type
Example of String Data Type
Output
22
Python Sequence Data Type
2. Python List Data Type
➢A Python list contains items separated by commas and enclosed within square brackets ([]).
➢Python lists are similar to arrays in C++. One difference between them is that all the items
belonging to a Python list can be of different data type. List declaration
Output
24
Python Sequence Data Type
3. Python Tuple Data Type
➢A Python tuple consists of a number of values separated by commas. Unlike lists, however,
tuples are enclosed within parentheses (...)
➢A tuple is also a sequence, hence each item in the tuple has an index referring to its position
in the collection. The index starts from 0. Tuple declaration
Example
x=(2023, "Python", 3.11, 5+6j, 1.23E-4)
print(type(x))
<class 'tuple'>
Output
26
Python Boolean Data Types
➢Python Boolean type is one of built-in data types which represents one of the
two values either True or False.
➢Python bool() function allows you to evaluate the value of any expression and
returns either True or False based on the expression.
27
Python Input/output operations
➢Python provides us with two built-in functions to read the input from the
keyboard. The input () Function The raw_input () Function
➢When the interpreter encounters input() function, it waits for the user to enter
data from the standard input stream (keyboard)
28
Taking Numeric Input in Python
➢Let us write a Python code that inputs width and height of a rectangle from
the user and computes the area.) The reason is, Python always read the
user input as a string.
Hence, width=“45" and height=“70" are
the strings and obviously you cannot
perform multiplication of two strings.
➢ To overcome this problem, we shall
use int(), another built-in function
from Python's standard library.
➢ It converts a string object to an integer.
➢ To accept an integer input from the
user, read the input in a string, and
type cast it to integer with int()
function
29
Taking Numeric Input in Python
Let us write a Python code that accepts integer value of width and height of a
rectangle from the user and computes the area.)
➢ We can use float() function
converts a string into a float
object.
➢ Write a python program
accepts the user input and
parses it to a float variable
30
Operators in Python
➢The operator is a symbol that performs a specific operation between two
operands. Python also has some operators
1. Arithmetic operators
➢Arithmetic operators used between two operands for a particular operation. There are many
arithmetic operators. It includes the exponent (**) operator as well as the + (addition),
➢** (Exponent):- As it calculates the first operand's power to the second operand, it is an
exponent operator.
➢// (Floor division):-It provides the quotient's floor value, by dividing the two operands.
31
Operators in Python
2. Comparison operator
Comparison operators compare the values of the two operands and return a true
or false Boolean value in accordance. The example of comparison operators are
==, !=, <=, >=, >, <. Output
32
Operators in Python
3. Assignment Operators
➢Using the assignment operators, the right expression's value is assigned to the left operand.
There are some examples of assignment operators like =, +=, -=, *=, %=, **=,
Output
➢ The error occurs in the subsequent lines because you cannot use assignment operators
directly within a print() statement. Example :- A=2,b=3
print(a+=b)-----------→ error 33
Operators in Python
4. Bitwise Operators
The two operands' values are processed bit by bit by the bitwise operators. The examples of
Bitwise operators are bitwise OR (|), bitwise AND (&), bitwise XOR (^), negation (~), Left
shift (<<), and Right shift (>>).
➢ The result of AND is 1 only if both bits are 1.
➢ The result of OR is 1 if any of the two bits is 1.
➢ The result of XOR is 1 if the two bits are different.
➢ shift (<<) takes two numbers, left shifts the bits of the first
➢ Right shift (>>) takes two numbers, right shifts the Output
bits of the first operand, the second operand decides the number of places to shift.
34
➢ Bitwise NOT ( ~ ) is the only unary bitwise operator. Since take only one operand. X=-X-1
Operators in Python
5. Logical Operators
The assessment of expressions to make decisions typically uses logical operators
and The condition will also be true if the expression is true. If the two
expressions a and b are the same, then a and b must both be true.
or The condition will be true if one of the phrases is true. If a and b are the
two expressions, then an or b must be true if and is true and b is false.
not If an expression a is true, then not (a) will be false and vice versa.
Example Output
35
Operators in Python
6. Membership Operators
➢The membership of a value inside a Python data structure can be verified using
Python membership operators.
➢The result is true if the value is in the data structure; otherwise, it returns false.
Operator Description
in If the first operand cannot be found in the second operand, it is evaluated to be
true (list, tuple, or dictionary).
not in If the first operand is not present in the second operand, the evaluation is true
(list, tuple, or dictionary).
Example Output
36
Operators in Python
7. Identity Operators
Operator Description
is If the references on both sides point to the same object, it is
determined to be true.
is not If the references on both sides do not point at the same object, it
is determined to be true.
Example Output
37
Precedence and Associativity of Operators in Python
➢Errors in Python can be broadly classified into three categories:- Syntax Errors, Runtime
Errors, and Logical Errors.
1. Syntax errors :- are the grammar mistakes of the programming world. They occur when
you write code that doesn't conform to Python's syntactical rules.
➢ Forgetting a colon at the end of an if statement. Example
➢Unlike syntax or runtime errors, logical errors don't generate error messages or exceptions.
Instead, your code runs without issues, but it doesn't achieve the intended results.
def calculate_average(numbers):
total = 0
Example for num in numbers:
total += num
average = total / len(numbers) - 1
return averag
41
Control Statements
➢Python's conditional statements carry out various calculations or operations according to
whether a particular Boolean condition is evaluated as true or false.
➢Decision making is the most important aspect of almost all the programming languages. As
the name implies, decision making allows us to run a particular block of code for a particular
decision. Here, the decisions are made on the validity of the particular conditions.
Statement Description
If The if statement is used to test a specific condition. If the condition is true, a block of code (if-
block) will be executed.
If - else The if-else statement is similar to if statement except the fact that, it also provides the block of
the code for the false case of the condition to be checked.
Nested if Nested if statements enable us to use if ? else statement inside an outer if statement.
elif The elif statement enables us to check multiple conditions and execute the specific
42
Indentation in python
Indentation in Python
➢For the ease of programming and to achieve simplicity, python doesn't allow the use of
parentheses for the block level code. In Python, indentation is used to declare a block of
code.
➢If two statements are at the same indentation level, then they are the part of the same block.
➢Generally, four spaces are given to indent the statements which are a typical amount of
indentation in python.
➢Indentation is the most used part of the python language since it indicate block of code.
➢All the statements of one block are intended at the same level indentation.
43
The If statement
Exercise
1. Write a program to check the given number is positive using python?
2. Write a Simple Python Program to print the largest of the three numbers?
44
The if-else statement
if condition:
block of statements
else:
else-block
Exercise
1. Write a program to check the given number is positive or negative using python?
2. Write a Program to check whether a number is even or not using python.
45
The elif statement
The syntax of the elif- statement is given below.
if expression 1:
block of statements
elif expression 2:
block of statements
elif expression 3:
block of statements
else:
block of statements
Exercise
1. Write a python program to calculate the Grade letter of a given course by adding mid exam
and final exam result based DBU grade scale using elif ?
2. Write a python program to find the largest number from three number using nested if 46?
Looping in Python
➢Python loops allow us to execute a statement or group of statements multiple times
➢Python programming language provides the following types of loops to handle looping
requirements.
Sr.No. Name of the loop Loop Type & Description
1 While loop ➢ Repeats a statement or group of statements while a
given condition is TRUE.
➢ It tests the condition before executing the loop body.
2 For loop ➢ This type of loop executes a code block multiple
times and abbreviates the code that manages the
loop variable.
3 Nested loops ➢ We can iterate a loop inside another loop
47
Python for loop
➢Python frequently uses the Loop to iterate over iterable objects like lists, tuples, and strings.
➢for loops are used when a section of code needs to be repeated a certain number of times.
syntax syntax
for value in range(): for value in sequence:
statement statement
➢Passing the whitespace to the end parameter (end=' ') indicates that the end character has to
be identified by whitespace and not a newline.
Example:- write a python program to print a number from 1to 10 using for loop
for i in range(11): for i in range(1,11):
print(i,end=" ") print(i,end=" ")
Or Or
for i in range(11): for i in range(1,11):
print(i) print(i) 48
Python for loop
1. Write the output of the following python program? Output
for i in range(1,10,2):
print(i,end=" ")
for i in range(2,10,2):
print(i,end=" ")
2. Write a python program to display the sum of the first 100 number?
sum=0
for i in range(1,101,1):
sum=sum+i
print("the sum is",sum)
3. Write a program a python program to calculate the factorial of the given
number ? 49
For loop using list
➢Write a python program to find the sum of the square of each element of the list
using for loop? numbers = [3, 5, 23, 6, 5, 1, 2, 9, 8]
syntax
for value in sequence:
statement
Since instead of range just replace list (numbers) Output
51
Python while loop
Exercise
1. Write a Python program for checking a number is Prime number or not
2. Write a python program to find the sum of n natural number ?
3. Write a python program to calculate factorial of a number
4. Write the output of the following program Output
i=1
while i<51:
if i%5 == 0 or i%7==0 :
print(i, end=' ')
i+=1
52
Python while loop using List
Example:- Write a python program to find the sum of the given list using for loop?
numbers = [3, 5, 23, 6, 5, 1, 2, 9, 8]
Len() function
➢It's important to note that the indexing of elements in a list starts from 0, so the length of a
list is always greater than or equal to 0.
➢The len() function is efficient and commonly used for iterating over lists or performing
operations based on the size of a list
numbers = [3, 5, 23, 6, 5, 1, 2, 9, 8]
sum = 0
i=0
while i < len(numbers):
sum =sum+ numbers[i]
i += 1
print("Sum of each element:", sum)
53
Looping in Python
Python Loop Control Statements
➢ Loop control statements change execution from its normal sequence. When
execution leaves a scope, all automatic objects that were created in that scope
are destroyed.
➢ Python supports the following control statements
Sr.No. Control Statement & Description
Break statement:- Terminates the loop statement and transfers execution to the
1
statement immediately following the loop.
Continue statement :- Causes the loop to skip the remainder of its body and
2
immediately retest its condition prior to reiterating.
57
Python Nested loop
➢In python nested loop is a loop inside another loop. Syntax
Outer loop
inner loop
statement of inner loop
statement of outer loop
58
Python Nested loop
Example:- Write the output of the following python program
* * * * * * *
* * * * * * *
for i in range (1,8): * * * * * * *
for j in range(i+1): * * * * * * *
print("*",end=" ") * * * * * * *
print(" ") * * * * * * *
* * * * * * *
0
for i in range (1,8): 0 1
for j in range(1,8-i+1): 0 1 2
print("*",end=" ") 0 1 2 3
print(" ") 0 1 2 3 4
0 1 2 3 4 5
0 1 2 3 4 5 6 59
Python Nested loop
Example:- Write the output of the following python program
k = 2 * rows - 2 #let row=5
m = (2 * rows) - 2 #let row=5
for i in range(rows, -1, -1):
for i in range(0, rows):
for j in range(k, 0, -1):
for j in range(0, m):
print(end=" ")
print(end=" ")
k = k + 1
m = m - 1
for j in range(0, i + 1):
for k in range(0, i + 1):
print("*", end=" ")
print("*", end=' ')
print("")
print(" ")
60
Python Function
➢A collection of related assertions that carry out a mathematical, analytical, or
evaluative operation is known as a function
➢A function is a block of code that used to perform certain actions. which only
➢Instead of repeatedly creating the same code block for various input variables,
We can call the function and reuse the code it contains with different variables.
61
Python Function
Advantages of Python Functions
➢We can stop a program from repeatedly using the same code block by including
functions.
➢Once defined, Python functions can be called multiple times and from any
location in a program.
62
Python Function
Python Functions Declaration 1.def function_name( parameters ):
# code block
➢function_name is the function's name, which we can use to distinguish it from other
functions.
➢We will utilize this name to call the capability later in the program.
➢Name functions in Python must adhere to the same guidelines as naming variables.
Output
65
Variable Scopes
:➢When you want to use the same variable for rest of your program or module
you declare it as a global variable,
➢while if you want to use the variable in a specific function or method, you use
a local variable.
❑Let’s understand this Python variable types with the difference between local
and global variables in the below program.
1.Let us define variable in Python where the variable “f” is global in scope and
is assigned value 101 which is printed in output
2.Variable f is again declared in function and assumes local scope.
➢It is assigned value “I am learning Python.” which is printed out as an output.
This Python declare variable is different from the global variable “f” defined
earlier
66
Local & Global Variable
:3. Once the function call is over, the local variable f is destroyed. At line 12,
when we again, print the value of “f” is it displays the value of global variable
f=101
67
Local & Global Variable
:➢While Python variable declaration using the keyword global, you can
reference the global variable inside a function.
1.Variable “f” is global in scope and is assigned value 101 which is printed
69
Parameter & Arguments
What is the difference between Arguments and Parameters?
➢Both arguments and parameters are variables/ constants passed into a function. The
difference is that:
I. Arguments are the variables passed to the function in the function call.
II. Parameters are the variables used in the function definition.
III. The number of arguments and parameters should always be equal except for the variable
length argument list.
➢Positional arguments
➢Keyword arguments
➢Default arguments
➢Arbitrary arguments
71
1. Positional arguments
➢Positional or required arguments are those supplied to a function during its call in a
predetermined positional sequence.
➢The number of arguments required in the method call must be the same as those provided
in the function's definition.
Example :
def student(num1,num2,num3):
3 is assigned for num1,
sum=num1+num2-num3
5 is assigned for num2,
return sum
6 is assigned for num3,
print("the sum is ",student(3,5,6))
➢in a function call, the caller identifies the arguments by the parameter name.
Example :
➢The Python interpreter is able to use the keywords provided to match the values with
parameters 73
Positional and Keyword arguments
➢Keyword arguments must always follow positional arguments. If not, Python will raise a
syntax error:
➢Example 1 Example2
def student(num1,num2,num3):
def student(num1,num2,num3):
sum=num1+num2-num3
sum=num1+num2-num3
return sum
return sum
print("the sum is ",student(num1=7,8,num3=4))
print("the sum is ",student(10,num2=7,num3=4))
74
3. Default arguments
➢Default values indicate that the function argument will take that value if no argument value
: is passed during the function call.
➢The default value is assigned by using the assignment(=) operator of the form parameter
Example :1 Example:2
➢In example to make non-default argument follows default argument error, since default
argument must be assign right to left 75
4. Arbitrary or variable length arguments
➢Arbitrary or Variable-length Arguments process a function for more arguments than you
: specified while defining the function.
➢An asterisk (*) is placed before the variable name that holds the values of all nonkeyboard
variable arguments.
def student(*numbers):
Example : sum=0
for i in numbers:
sum=i+sum
return sum
print("the sum is ",student(4,6))
print("the sum is ",student(5,3,7,1))
print("the sum is ",student(10,9,11)) 76
Parameter passing
➢There are two methods of invoking/ calling functions-Call by value and Call by reference.
➢The default value is assigned by using the assignment(=) operator of the form parameter
➢ When the values of arguments are passed into parameters in the function, the values are
copied into parameters. This method is called "Call by value".
➢In this method, arguments and parameters are different and are stored in different memory
locations.
➢Changes done on parameters inside the function do not affect the arguments in the program
and vice versa.
77
Parameter passing
➢When the addresses of the arguments are passed into parameters instead of values, this
method of invoking a function is called "Call by Reference".
➢Both the arguments and parameters refer to the same memory location.
➢Changes to the parameters (pointers) will affect the values of the arguments in the program.
78
Parameter passing in python
➢Python’s argument-passing model is neither “Pass by Value” nor “Pass by Reference” but it
is “Pass by Object Reference or Call by assignment”. In Python, every single entity is an
object. Objects are divided into Mutable and Immutable objects.
➢What happens in Python when we assign a value to a variable is different from other
languages like C ,C++ or Java.
➢Mutable objects are those objects/ data types in Python that we can modify after creating
them Example : Lists, Dictionaries, Sets
➢Immutable objects, on the other hand, are objects that can't be modified once created.
➢ List is mutable object ,As you can observe, when created with the name a, it is saved in
the address “2891662300096“ and the value is 23,45,89.
➢ Using append(), we altered it by appending another value 49. It is still in the same
memory location and the value is updated to 23,45,89,49 , meaning the same object is
modified.
80
Parameter passing
Immutable Objects: example : Output
a = 20
print(id(a))
print(a)
a += 23
print(id(a))
print(a)
➢ An int object is immutable, meaning we can't modify it once created. You might
wonder we still added 23 in the above code.
➢ Observe that the object when created is not the same object after adding. Both are in
different memory locations and different value which means they are different objects.
81
Parameter passing
➢So, how are arguments passed to the parameters when a function is invoked?
With all the knowledge about assignment or Object Reference operation in Python:
➢The passing is like a "Call by Reference" if the arguments are mutable.
➢The passing is like "Call by Value" if the arguments are immutable.
82
Nested Function
➢Nested (or inner) functions are functions defined within other functions that allow us to
directly access the variables and names defined in the enclosing function.
➢simply use the def keyword to initialize another function within a function to define a
nested function. Java, C, C++ not support nested function, but python and JavaScript
support nested function def arithmetic_operation():
x="wellcome"
Example: print("the outer function is",x)
def add(x, y):
return x + y
a=int(input("enter the value"))
b=int(input("enter the value"))
print("the sum is ",add(a,b))
arithmetic_operation() 83
Module in python
➢A file containing a set of function you want to include in your application.
➢We employ modules to divide complicated programs into smaller, more understandable
pieces. Modules also allow for the reuse of code.
➢To create a module just save the code with the file extension .py
84
Module in python
Example first create the module save in second import the module and use
def add(a,b):
return a+b import calcu
def sub(a,b): print(calcu.add(4,5))
return a-b print(calcu.sub(6,8))
def div(a,b): print(calcu.div(4,5))
return a/b print(calcu.mult(6,8))
def mult(a,b): print(calcu.flo(4,5))
return a*b print(calcu.mod(6,8))
def expo(a,b): print(calcu.expo(6,8))
return a**b
def flo(a,b): the module you created and imported must be in the same folder
return a//b
def mod(a,b):
return a%b 85
Python Built in Function (Python version3.12.2)
➢Python comes with a wide range of built-in functions that are readily
available for you to use without needing to import any additional libraries.
➢The max() function returns the largest of its arguments or largest number from the iterable
(list or tuple).
➢The function min() returns the smallest of its arguments i.e. the value closest to negative
infinity, or smallest number from the iterable (list or tuple)
➢The pow() function returns x raised to y. It is equivalent to x**y. The function has third
optional argument mod. If given, it returns (x**y) % mod value
➢round() is a built-in function in Python. It returns x rounded to n digits from the decimal
point.
87
Python Built in Function (Python version3.12.2)
➢The sum() function returns the sum of all numeric items in any iterable (list or tuple).
➢eval():- Runs Code Within Program by accept input from the user
88
Python built in Function by imported libraries
➢Python's built-in functions that are provided by imported libraries. Python has a wide range
of libraries that extend its functionality.
➢To import the libraries use import keyword and include libraries
Example
3. Turtle (import turtle):-Turtle is a Python library which used to create graphics, pictures,
and games. 90
Python built in Function by imported libraries
4. datetime(import datetime):- Get the current date and time.
Example
Example
import statistics
datasets = [5, 2, 7, 4, 2, 6, 8]
x = statistics.mean(datasets)
print("Mean is :", x)
91
Python Packages
➢One of the key features of Python is the ability to create and access packages, which are
collections of modules that can be reused across different projects.
➢Python packages are groups of modules that may be used in several applications.
➢Packages in Python can be easily created and accessed using the built-in package manager
Python also provides a built-in package manager, pip ,conda that can be used to install and
manage packages.
A command-line programm called Pip, conda may be used to add, delete, and update
packages in Python. "pip instal package name“ and “conda instal package name“ is the
syntax to use when installing a package using pip and conda.
92
Python Packages
➢For example, if you want to install the "numpy" package, the command would be "pip
install numpy". Pip can also be used to update and remove packages.
➢ The syntax for updating a package is "pip install --upgrade package_name" and
➢2. Pandas: Pandas is a powerful library for data manipulation and analysis.
93
Python Packages
3. Matplotlib: For data visualization, Matplotlib is a go-to library.
4. Scikit-learn: It offers simple and efficient tools for data mining and data analysis, including
various algorithms for classification, regression, clustering, and dimensionality reduction.
5.TensorFlow or PyTorch: These libraries are crucial for deep learning and neural network-
based tasks. with support for GPU acceleration.
➢These packages form the backbone of many Python projects in fields ranging from
scientific computing and data analysis to machine learning and artificial intelligence.
94