0% found this document useful (0 votes)
3 views221 pages

Python Programming

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)
3 views221 pages

Python Programming

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

Python Programming

UNIT I

Getting Started with Python:Introduction to Python, Python Keywords,


Identifiers, Variables, Comments, Data Types, Operators, Input and Output,
Type Conversion, Debugging. Flow of Control, Selection, Indentation,
Repetition, Break and Continue Statement, Nested Loops.
Strings: String Operations, Traversing a String, String handling Functions.
UNIT II

Functions: Functions, Built-in Functions, User Defined Functions, recursive


functions, Scope of a Variable
Python and OOP: Defining Classes, Defining and calling functions passing
arguments, Inheritance, polymorphism, Modules– date time, math, Packages.
Exception Handling: Exception in python, Types of Exception, User-defined
Exceptions.
UNIT III

List:Introduction to List, List Operations, Traversing a List, List Methods and


Built-in Functions. Tuples and Dictionaries: Introduction to Tuples, Tuple
Operations, Tuple Methods and Builtin Functions, Nested Tuples. Introduction
to Dictionaries, Dictionaries are Mutable, Dictionary Operations, Traversing a
Dictionary, Dictionary Methods and Built-in functions.

UNIT IV

Introduction to NumPy :Array, NumPy Array, Indexing and Slicing,


Operations on Arrays, Concatenating Arrays, Reshaping Arrays, Splitting
Arrays, Statistical Operations on Arrays.
Data Handling: Introduction to Python Libraries, Series, Data Frame,
Importing and Exporting Data between CSV Files and Data Frames.

UNIT V

Plotting Data using Matplotlib : Introduction, Plotting using Matplotlib –


Linechart, Barchart, Histogram, Scatter Chart, Pie Chart.
Database Connectivity: Importing MySQL for Python, connecting with a
database, forming a query in MySQL, Passing a query to MySQL.

Page No:- 1
Introduction To Python

Python is a widely used general-purpose, high-level programming language. It


was created by Guido van Rossum in 1991 and further developed by the
Python Software Foundation. It was designed with an emphasis on code
readability, and its syntax allows programmers to express their concepts in
fewer lines of code. Python is a programming language that lets you work
quickly and integrate systems more efficiently. There are two major Python
versions: Python 2 and Python 3. Both are quite different.

According to reports, Python is now the most popular programming language


among developers because of its high demands in the tech realm.

****************
Features in Python

1. Free and Open Source : Python language is freely available at the official
website and you can download .
2. Easy to code : Python is a high-level programming language. Python is
very easy to learn the language as compared to other languages like C, C#,
Javascript, Java, etc.
3. Easy to Read: As you will see, learning Python is quite simple. Python’s
syntax is really straightforward.
4. Object-Oriented Language: One of the key features of Python is Object-
Oriented programming. Python supports object-oriented language and
concepts of classes, object encapsulation, etc.
5. GUI Programming Support: Graphical User interfaces can be made using
a module such as PyQt5, PyQt4, wxPython, or Tk in Python. PyQt5 is the most
popular option for creating graphical apps with Python.
6. High-Level Language: Python is a high-level language. When we write
programs in Python, we do not need to remember the system architecture, nor
do we need to manage the memory.
7. Large Community Support: Python has gained popularity over the
years. Our questions are constantly answered by the enormous StackOverflow
community. These websites have already provided answers to many questions
about Python, so Python users can consult them as needed.
Page No:- 2
8. Easy to Debug: Excellent information for mistake tracing. You will be able
to quickly identify and correct the majority of your program’s issues once you
understand how to interpret Python’s error traces.
9. Python is a Portable language: Python language is also a portable
language. For example, if we have Python code for Windows and if we want to
run this code on other platforms such as Linux, Unix, and Mac. then we do not
need to change it, we can run this code on any platform.
10. Python is an Integrated language :Python is also an Integrated
language because we can easily integrate Python with other languages like
C, C++, etc.
11. Interpreted Language: Python is an Interpreted Language because
Python code is executed line by line at a time. like other languages C,
C++, Java, etc. there is no need to compile Python code this makes it easier to
debug our code. The source code of Python is converted into an immediate
form called bytecode.
12. Large Standard Library : Python has a large standard library that
provides a rich set of modules and functions.
13. Dynamically Typed Language: Python is a dynamically-typed language.
That means the type (for example- int, double, long, etc.) for a variable is
decided at run time not in advance because of this feature we don’t need to
specify the type of variable.
14. Frontend and backend development: With a new project py script, you
can run and write Python codes in HTML with the help of some simple tags
<py-script>, <py-env>, etc. This will help you do frontend development work
in Python like javascript. Backend is the strong forte of Python it’s extensively
used for this work cause of its frameworks like Django and Flask.
15. Allocating Memory Dynamically: In Python, the variable data type does
not need to be specified. The memory is automatically allocated to a variable
at runtime when it is given a value.
***********************************************
Methods to Run a Script in Python
There are various methods to Run a Python script, we will go through some
generally used methods for running a Python script:
 Interactive Mode
 Command Line
 Text Editor (VS Code)
 IDE (PyCharm)

Page No:- 3
1. Run Python Script Interactively
 In Python Interactive Mode, you can run your script line by line in a
sequence. To enter an interactive mode, you will have to open
Command Prompt on your Windows machine, type ‘python’ and
press Enter.

Example1: Using Print Function


Run the following line in the interactive mode:
print('Hello World !')

Output:

Example 2: Using Interactive Execution


Run the following lines one by one in the interactive mode.
name = "Pooja"
print("My name is " + name)
Output: My name is Pooja

Example 3: Interactive Mode Comparison


Run the following lines one by one in the interactive mode.
a=1
b=3
if a > b:
print("a is Greater")
else:
print("b is Greater")
Output:

Page No:- 4
Note: To exit from this mode, press ‘Ctrl+Z’ and then press ‘Enter’ or type
‘exit()’ and then press Enter.

2. Run Python Script by the Command Line


Running Python scripts on Windows via the command line provides a direct
and efficient way to execute code. It allows for easy navigation to the script’s
directory and initiation, facilitating quick testing and automation.
Example 1: Using Script Filename
To run Python in the terminal, store it in a ‘.py’ file in the command line, we
have to write the ‘python’ keyword before the file name in the command
prompt. In this way we can run Python programs in cmd.
python [Link]
You can write your own file name in place of ‘[Link]’.
Output:

Example 2: Redirecting output


To run a Python script in Terminal from the command line, navigate to the
script’s directory and use the python script_name.py command. Redirecting
output involves using the > symbol followed by a file name to capture the
script’s output in a file. For example, python script_name.py > [Link]
redirects the standard output to a file named “[Link].”
Output :
Page No:- 5
3. Run a Script in Python using a Text Editor
To run Python script on a text editor like VS Code (Visual Studio Code) then
you will have to do the following:
 Go to the extension section or press ‘Ctrl+Shift+X’ on Windows, then
search and install the extension named ‘Python’ and ‘Code Runner’.
Restart your vs code after that.
 Now, create a new file with the name ‘[Link]’ and write the below
code in it:
print('Hello World!')
 Then, right-click anywhere in the text area and select the option that
says ‘Run Code’ or press ‘Ctrl+Alt+N’ to run the code.
Output:

4. Run Python Scripts using an IDE


To run Python script on an IDE (Integrated Development Environment)
like PyCharm, you will have to do the following:
 Create a new project.
 Give a name to that project as ‘GfG’ and click on Create.
 Select the root directory with the project name we specified in the last
step. Right-click on it, go to New, anto, and click on the ‘Python file’
option. Then give the name of the file as ‘hello’ (you can specify any
name as per your project requirement). This will create a ‘[Link]’ file
in the project root directory.
Note: You don’t have to specify the extension as it will take it automatically.

Page No:- 6
 Now write the below Python script to print the message:
print('Hello World !')
 To run this Python script, Right click and select the ‘Run File in Python
Console’ option. This will open a console box at the bottom and show the
output there. We can also run using the Green Play Button at the top
right corner of the IDE.

Output:

We have covered 4 different methods to run Python scripts on your device. You
can use any of the above methods depending on your device. Running Python
scripts is a very basic and easy task. It helps you in sharing your work and
accessing other source work for learning.
****************************************

Page No:- 7
Python Keywords
Keywords in Python are reserved words that have special meanings and serve
specific purposes in the language syntax.

Rules for Keywords in Python


 Python keywords cannot be used as the names of variables, functions,
and classes or any other identifier.
 Python keywords cannot be used as identifiers.
 All the keywords in Python should be in lowercase except True and False.
List of Keywords in Python

and break elif for in Not True

as class else from is or try

assert continue except global lambda pass while

Async def False if None raise with

Await del finally import nonlocal return yield

***************************************
Identifiers
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.
We can also use the Python string isidentifier() method to check whether a
string is a valid identifier or not.
Rules for Naming Python Identifiers
 It cannot be a reserved python keyword.
 It should not contain white space.

Page No:- 8
 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
 var1
 _var1
 _1_var
 var_1

*******************
Python Variables
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.
# An integer assignment
age=45

# A floating point
salary=1456.8

# A string
name="pooja"

Page No:- 9
print(age)
print(salary)
print(name)

Global and Local Python Variables

Local variables in Python are the ones that are defined and declared inside a
function. We can not call this variable outside the function.
Python
# This function uses local variable s
def f():
s = "Welcome geeks"
print(s)
f()

Output: Welcome geeks

*********************************************

Global variables in Python are the ones that are defined and declared outside
a function, and we need to use them inside a function.

def f():
print(s)

# Global scope
s = "I love pooja"
f()

Output:
I love pooja

*****************************************************

Global keyword in Python

Python global is a keyword that allows a user to modify a variable outside of


the current scope. It is used to create global variables from a non-global scope
i.e inside a function. Global keyword is used inside a function only when we
want to do assignments or when we want to change a variable. Global is not
needed for printing and accessing.

Rules of global keyword

 If a variable is assigned a value anywhere within the function’s body, it’s


assumed to be local unless explicitly declared as global.
 Variables that are only referenced inside a function are implicitly global.
 We use a global in Python to use a global variable inside a function.
 There is no need to use a global keyword in Python outside a function.

Page No:- 10
Example:

Python program to modify a global value inside a function.


Python
x = 15

def change():

# using a global keyword


global x

# increment value of a by 5
x=x+5
print("Value of x inside a function :", x)

change()
print("Value of x outside a function :", x)

Output:

Value of x inside a function : 20


Value of x outside a function : 20
********************************************
Comment statements in python
Comments in Python are the lines in the code that are ignored by the
interpreter during the execution of the program.
Comments enhance the readability of the code and help the programmers to
understand the code very carefully. It also helps in collaborating with other
developers as adding comments makes it easier to explain the code.
Types of Comments in Python
There are three types of comments in Python:
 Single line Comments
 Multiline Comments
 String Literals
 Docstring Comments
1. Single-Line Comments
 Python single-line comment starts with the hashtag symbol (#) with no
white spaces and lasts till the end of the line.
 If the comment exceeds one line then put a hashtag on the next line and
continue the Python Comment.

Page No:- 11
 Python’s single-line comments are proved useful for supplying short
explanations for variables, function declarations, and expressions. See
the following code snippet demonstrating single line comment:
Example : # Print “Python!” is a new subject
2. Multi-Line Comments
Python does not provide the option for multiline comments. However, there are
different ways through which we can write multiline comments.
a) Multiline comments using multiple hash tags (#)
We can multiple hash tags (#) to write multiline comments in Python. Each
and every line will be considered as a single-line comment.
Example: # Python program to demonstrate
# multiline comments
3. String Literals

Python ignores the string literals that are not assigned to a variable so we can
use these string literals as Python Comments.
a) Single-line comments using string literals
On executing the above code we can see that there will not be any output so
we use the strings with triple quotes(“””) as multiline comments.
4. Docstring
 Python docstring is the string literals with triple quotes that are
appeared right after the function.
 It is used to associate documentation that has been written with Python
modules, functions, classes, and methods.
 It is added right below the functions, modules, or classes to describe
what they do. In Python, the docstring is then made available via the
doc attribute.
Example : def multiply(a, b):
"""Multiplies the value of a and b"""
return a*b
# Print the docstring of multiply function
print(multiply. doc )

****************************
Page No:- 12
Constants
Constant variable the name itself says that it is constant. We have to define a
constant variable at the time of declaration. After that, we will not able to
change the value of a constant variable. In some cases, constant variables are
very useful.
Creating constant variables, functions, objects is allowed in languages like
c++, Java. But in python creating constant variable, it is not allowed. There is
no predefined type for a constant variable in Python. But we can
use pconst library for that.

# import module
from pconst import const

# declare constants
[Link] = "PYTHON"
const.COMPANY_NAME = 'VHDC'

# display
print([Link])
print(const.COMPANY_NAME)

Output:
PYTHON
VHDC
*************************************************
Python Data Types
Python 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, Python
data types are classes and variables are instances (objects) of these classes.

Page No:- 13
1. Numeric Data Types in Python
The numeric data type in Python represents the data that has a numeric value.
A numeric value can be an integer, a floating number, or even a complex
number. These values are defined as Python int , Python float , and Python
complex classes in Python .
 Integers – This value is represented by int class. It contains positive or
negative whole numbers (without fractions or decimals). In Python,
there is no limit to how long an integer value can be.
 Float – This value is represented by the float class. It is a real number
with a floating-point representation. It is specified by a decimal point.
Optionally, the character e or E followed by a positive or negative integer
may be appended to specify scientific notation.
 Complex Numbers – A complex number is represented by a complex
class. It is specified as (real part) + (imaginary part)j . For example –
2+3j
2. Dictionary Data Type in Python

A dictionary in Python is an unordered collection of data values, used to store


data values like a map, unlike other Python Data Types that hold only a
single value as an element, a Dictionary holds a key: value pair. Key-value is
provided in the dictionary to make it more optimized. Each key-value pair in
a Dictionary is separated by a colon : , whereas each key is separated by a
‘comma’.

Create a Dictionary in Python

In Python, a Dictionary can be created by placing a sequence of elements


within curly {} braces, separated by ‘comma’. Values in a dictionary can be
of any data type and can be duplicated, whereas keys can’t be repeated and
must be immutable. The dictionary can also be created by the built-in
function dict(). An empty dictionary can be created by just placing it in curly
braces{}. Note – Dictionary keys are case sensitive, the same name but
different cases of Key will be treated distinctly.

Example: This code creates and prints a variety of dictionaries. The first
dictionary is empty. The second dictionary has integer keys and string values.
The third dictionary has mixed keys, with one string key and one integer key.
The fourth dictionary is created using the dict() function, and the fifth
dictionary is created using the [(key, value)] syntax

Page No:- 14
3. Boolean Data Type in Python
Python Data type with one of the two built-in values, True or False. Boolean
objects that are equal to True are truthy (true), and those equal to False are
falsy (false). However non-Boolean objects can be evaluated in a Boolean
context as well and determined to be true or false. It is denoted by the class
bool.

Note – True and False with capital ‘T’ and ‘F’ are valid booleans otherwise
python will throw an error.

4. Set Data Type in Python


In Python Data Types, a Set is an unordered collection of data types that is
iterable, mutable, and has no duplicate elements. The order of elements in a
set is undefined though it may consist of various elements.
Create a Set in Python
Sets can be created by using the built-in set() function with an iterable object
or a sequence by placing the sequence inside curly braces, separated by
a ‘comma’. The type of elements in a set need not be the same, various
mixed-up data type values can also be passed to the set.

Example: The code is an example of how to create sets using different types
of values, such as strings , lists , and mixed values

5. Sequence Data Types in Python


The sequence Data Type in Python is the ordered collection of similar or
different Python data types. Sequences allow storing of multiple values in an
organized and efficient fashion. There are several sequence data types of
Python:
 Python String
 Python List
 Python Tuple
String Data Type
Strings in Python are arrays of bytes representing Unicode characters. A string
is a collection of one or more characters put in a single quote, double-quote, or
triple-quote. In Python, there is no character data type Python, a character is a
string of length one. It is represented by str class.

Page No:- 15
Creating String
Strings in Python can be created using single quotes, double quotes, or even
triple quotes.
Example: This Python code showcases various string creation methods. It
uses single quotes, double quotes, and triple quotes to create strings with
different content and includes a multiline string. The code also demonstrates
printing the strings and checking their data types.

List Data Type


Lists are just like arrays, declared in other languages which is an ordered
collection of data. It is very flexible as the items in a list do not need to be of
the same type.
Creating a List in Python
Lists in Python can be created by just placing the sequence inside the square
brackets[].

Tuple Data Type


Just like a list, a tuple is also an ordered collection of Python objects. The only
difference between a tuple and a list is that tuples are immutable i.e. tuples
cannot be modified after it is created. It is represented by a tuple class.
Creating a Tuple in Python
In Python Data Types, tuples are created by placing a sequence of values
separated by a ‘comma’ with or without the use of parentheses for grouping
the data sequence. Tuples can contain any number of elements and of any
datatype (like strings, integers, lists, etc.). Note: Tuples can also be created
with a single element, but it is a bit tricky. Having one element in the
parentheses is not sufficient, there must be a trailing ‘comma’ to make it a
tuple.
********************************************************
Python Operators
Operators refer to special symbols that perform operations on values and
variables. The operands in python, one of the programming languages, refer
to the values on which the operator operates. Most noteworthy, operators can
carry out arithmetic, relational, and logical operations.
 OPERATORS: These are the special symbols. Eg- + , * , /, etc.
 OPERAND: It is the value on which the operator is applied.

Page No:- 16
Types of Operators in Python
1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Identity Operators and Membership Operators
Arithmetic Operators in Python
Python Arithmetic operators are used to perform basic mathematical
operations like addition, subtraction, multiplication, and division.

Operator Description Syntax

+ Addition: adds two operands x+y

– Subtraction: subtracts two operands x–y

* Multiplication: multiplies two operands x*y

/ Division (float): divides the first operand by the second x/y

Division (floor): divides the first operand by the


// x // y
second

Modulus: returns the remainder when the first operand


% x%y
is divided by the second

** Power: Returns first raised to power second x ** y

Programme :
a=7
b=2
# addition
print ('Sum: ', a + b)
# subtraction
print ('Subtraction: ', a - b)
# multiplication
print ('Multiplication: ', a * b)
# division

Page No:- 17
print ('Division: ', a / b)
# floor division
print ('Floor Division: ', a // b)

# modulo
print ('Modulo: ', a % b)

# a to the power b
print ('Power: ', a ** b)
output
Sum: 9
Subtraction: 5
Multiplication: 14
Division: 3.5
Floor Division: 3
Modulo: 1
Power: 49
************************************************************
Comparison of Python Operators
In Python Comparison of Relational operators compares the values. It either
returns True or False according to the condition.

Operator Description Syntax

Greater than: True if the left operand is greater


> x>y
than the right

Less than: True if the left operand is less than the


< x<y
right

!= Not equal to – True if operands are not equal x != y

Greater than or equal to True if the left operand is


>= x >= y
greater than or equal to the right

Less than or equal to True if the left operand is


<= x <= y
less than or equal to the right

Page No:- 18
Programme:
a=5
b=2
print (a > b) # True
outout
True

******************************************
Logical Operators in Python
Python Logical operators perform Logical AND, Logical OR, and Logical
NOT operations. It is used to combine conditional statements.

Operator Description Syntax

and Logical AND: True if both the operands are true x and y

Logical OR: True if either of the operands is


or x or y
true

not Logical NOT: True if the operand is false not x

Programme:
a = True
b = False
print(a and b)
print(a or b)
print(not a)

Output
False
True
False
****************************

Page No:- 19
Bitwise Operators in Python
Python Bitwise operators act on bits and perform bit-by-bit operations. These
are used to operate on binary numbers.

Operator Description Syntax

& Bitwise AND x&y

| Bitwise OR x|y

~ Bitwise NOT ~x

^ Bitwise XOR x^y

>> Bitwise right shift x>>

<< Bitwise left shift x<<

*******************************
Bitwise Operators in Python
A bitwise operator is a character that manipulates individual bits in a binary
pattern, rather than bytes or larger units of data. Bitwise operators are used to
perform actions on data at the bit level, such as setting, clearing, or toggling
bits in a bit field.
The various bitwise operations with the values of ‘a’ and ‘b’. It performs
bitwise AND (&), OR (|), NOT (~), XOR (^), right shift (>>), and left
shift (<<) operations and prints the results. These operations manipulate the
binary representations of the numbers.
Python
a = 10
b=4
print(a & b)
print(a | b)
print(~a)
print(a ^ b)
print(a >> 2)

Page No:- 20
print(a << 2)

Output
0
14
-11
14
2
40
**************************************
Assignment Operators in Python
Python Assignment operators are used to assign values to the variables.

Operator Description Syntax

Assign the value of the right side of the


= x=y+z
expression to the left side operand

Add AND: Add right-side operand with


+= left-side operand and then assign to left a+=b a=a+b
operand

Subtract AND: Subtract right operand


-= from left operand and then assign to left a-=b a=a-b
operand

Multiply AND: Multiply right operand


*= with left operand and then assign to left a*=b a=a*b
operand

Divide AND: Divide left operand with


/= right operand and then assign to left a/=b a=a/b
operand

Modulus AND: Takes modulus using left


%= and right operands and assign the result a%=b a=a%b
to left operand

//= Divide(floor) AND: Divide left operand a//=b a=a//b

Page No:- 21
Operator Description Syntax

with right operand and then assign the


value(floor) to left operand

Exponent AND: Calculate exponent(raise


**= power) value using operands and assign a**=b a=a**b
value to left operand

Performs Bitwise AND on operands and


&= a&=b a=a&b
assign value to left operand

Performs Bitwise OR on operands and


|= a|=b a=a|b
assign value to left operand

Performs Bitwise xOR on operands and


^= a^=b a=a^b
assign value to left operand

Performs Bitwise right shift on operands


>>= a>>=b a=a>>b
and assign value to left operand

Performs Bitwise left shift on operands a <<= b a= a


<<=
and assign value to left operand << b

a = 10
b=a
print(b)
b += a
print(b)
b -= a
print(b)
b *= a
print(b)
b <<= a
print(b)
Output
10
20
10
100
Page No:- 22
102400
********************************************

Identity Operators in Python


In Python, is and is not are the identity operators both are used to check if
two values are located on the same part of the memory. Two variables that are
equal do not imply that they are identical.
is True if the operands are identical
is not True if the operands are not identical
a = 10
b = 20
c=a
print(a isnot b)
print(a is c)

Output
True
True
****************************
Membership Operators in Python
In Python, in and not in are the membership operators that are used to test
whether a value or variable is in a sequence.
in True if value is found in the sequence

not in True if value is not found in the sequence


x = 24
y = 20
list = [10, 20, 30, 40, 50]

Page No:- 23
if (x notin list):
print("x is NOT present in given list")
else:
print("x is present in given list")
if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")

Output
x is NOT present in given list
y is present in given list
********************
Ternary Operator in Python
in Python, Ternary operators also known as conditional expressions are
operators that evaluate something based on a condition being true or false. It
was added to Python in version 2.5.
It simply allows testing a condition in a single line replacing the multiline if-
else making the code compact.

Syntax : [on_true] if [expression] else [on_false]


a, b = 10, 20
min = a if a < b else b
print(min)
Output:

10
*********************************

Page No:- 24
Precedence and Associativity of Operators in Python
In Python, Operator precedence and associativity determine the priorities of
the operator.
Operator Precedence in Python
This is used in an expression with more than one operator with different
precedence to determine which operation to perform first.
Let’s see an example of how Operator Precedence in Python works:
Example: The code first calculates and prints the value of the expression 10
+ 20 * 30, which is 610. Then, it checks a condition based on the values of
the ‘name’ and ‘age’ variables. Since the name is “Pooja” and the condition
is satisfied using the or operator, it prints “Hello! Welcome.”
expr = 10 + 20 * 30
print(expr)
name = "Alex"
age = 0

if name == "Pooja" or name == "John" and age >= 2:


print("Hello! Welcome.")
else:

print("Good Bye!!")
Output: 610
Hello! Welcome.
****************************
Operator Associativity in Python
If an expression contains two or more operators with the same precedence
then Operator Associativity is used to determine. It can either be Left to Right
or from Right to Left.
print(100 / 10 * 10)
print(5 - 2 + 3)
print(5 - (2 + 3))
print(2 ** 3 ** 2)

Page No:- 25
Output
100.0
6
0
512
***********************************
Input and Output in Python

Understanding input and output operations is fundamental to Python


programming. With the print() function, you can display output in various
formats, while the input() function enables interaction with users by gathering
input during program execution.

The print() function allows us to display text, variables, and expressions on


the console

Print Single variable

print("Hello, World!")

Output
Hello, World!

Print Multiple variable

name = "Mynu"
age = 30
print("Name:", name, "Age:", age)

output:
Name: Mynu Age: 30

***************
Output Formatting

Output formatting in Python with various techniques including the format()


method, manipulation of the sep and end parameters, f-strings, and the
versatile % operator. These methods enable precise control over how data is
displayed, enhancing the readability and effectiveness of your Python
programs.

Page No:- 26
Example 1: Using Format()

amount = 150.75

print("Amount: ${:.2f}".format(amount))

Output

Amount: $150.75

*******************

Using sep and end parameter

# end Parameter with '@'


print("Python", end='@')
print("GeeksforGeeks")

# Seprating with Comma


print('G', 'F', 'G', sep='')

# for formatting a date


print('09', '12', '2016', sep='-')

# another example
print('pratik', 'geeksforgeeks', sep='@')

Output

Python@GeeksforGeeks
GFG
09-12-2016
pratik@geeksforgeeks

*******************
Using f-string

name = 'Pooja'
age = 23
print(f"Hello, My name is {name} and I'm {age} years old.")

Output ;
Hello, My name is Pooja and I'm 23 years old.

******************

Page No:- 27
Using % Operator
We can use ‘%’ operator. % values are replaced with zero or more value of
elements. The formatting using % is similar to that of ‘printf’ in the C
programming language.
 %d –integer
 %f – float
 %s – string
 %x –hexadecimal
 %o – octal
# Taking input from the user
num = int(input("Enter a value: "))
add = num + 5
# Output
print("The sum is %d" %add)
Output
Enter a value: 50The sum is 55
********************
Take Multiple Input in Python
The code takes input from the user in a single line, splitting the values entered
by the user into separate variables for each value using the split() method.
Then, it prints the values with corresponding labels, either two or three, based
on the number of inputs provided by the user.
# taking two inputs at a time
x, y = input("Enter two values: ").split()
print("Number of boys: ", x)
print("Number of girls: ", y)
# taking three inputs at a time

x, y, z = input("Enter three values: ").split()


print("Total number of students: ", x)
print("Number of boys is : ", y)
print("Number of girls is : ", z)

Page No:- 28
Output
Enter two values : 5 10
Number of boys : 5
Number of girls : 10
Enter three values : 5 10 15
Total number of students: 5
Number of boys is : 10
Number of girls is : 15
************************
Python input() function is used to take user input. By default, it returns the
user input in form of a string.
name = input("Enter your name: ")
print("Hello,", name, "! Welcome!")
Output
Enter your name: samyukta
Hello, samyukta ! Welcome!
*****************************
Type conversion
Python defines type conversion functions to directly convert one data type to
another which is useful in day-to-day and competitive programming.
There are two types of Type Conversion in Python:
1. Python Implicit Type Conversion
2. Python Explicit Type Conversion

Implicit Type Conversion in Python

In Implicit type conversion of data types in Python, the Python interpreter


automatically converts one data type to another without any user
involvement.
x = 10

print("x is of type:",type(x))

y = 10.6
print("y is of type:",type(y))

z=x+y

print(z)

Page No:- 29
print("z is of type:",type(z))

Output
x is of type: <class 'int'>
y is of type: <class 'float'>
20.6
z is of type: <class 'float'>
**************
Explicit Type Conversion in Python
In Explicit Type Conversion in Python, the data type is manually changed by
the user as per their requirement. With explicit type conversion, there is a risk
of data loss since we are forcing an expression to be changed in some specific
data type.

# initializing string
s = "10010"
# printing string converting to int base 2
c = int(s,2)
print ("After converting to integer base 2 : ", end="")
print (c)
# printing string converting to float
e = float(s)
print ("After converting to float : ", end="")
print (e)

Output:
After converting to integer base 2 : 18
After converting to float : 10010.0
************************************************
Debugging in Python

Debugging in Python is the process of finding and fixing errors in Python


code. It involves examining the code, running it in a controlled environment,
and analyzing and fixing any issues.

Page No:- 30
How does debugging in Python work?

1. Identify errors: Programmers study the code to determine why it's not
working as expected.
2. Use a debugger: Programmers use a debugger to run the code and
analyze it step by step.
3. Set breakpoints: Programmers can set breakpoints to pause the
execution of the code at specific points.
4. Analyze the program state: Programmers can analyze the state of the
program at specific points.

5. Fix the issue: Programmers can fix the issue by making changes to the
code.

Tools for debugging in Python

1. Python debugger: A debugging environment that supports setting


breakpoints, stepping through code, and inspecting the stack
2. Apidog: An API debugging tool that allows users to send requests,
inspect responses, and debug APIs
3. Visual Studio Code: A tool that allows users to debug Python apps

***************************
Python - Control Flow

Python program control flow is regulated by various types of conditional


statements, loops, and function calls. By default, the instructions in a
computer program are executed in a sequential manner, from top to bottom,
or from start to end. However, such sequentially executing programs can
perform only simplistic tasks. We would like the program to have a decision-
making ability, so that it performs different steps depending on different
conditions.
Most programming languages including Python provide functionality to control
the flow of execution of instructions. Normally, there are two type of control
flow statements in any programming language and Python also supports them.

Decision Making Statements

Decision making statements are used in the Python programs to make them
able to decide which of the alternative group of instructions to be executed,
depending on value of a certain Boolean expression.
The following diagram illustrates how decision-making statements work −

Page No:- 31
The if Statements

Python provides if..elif..else control statements as a part of decision marking.


It consists of three different blocks, which are if block, elif (short of else if)
block and else block.

Example
Following is a simple example which makes use of if..elif..else. You can try to
run this program using different marks and verify the result.

marks = 80
result = ""
if marks < 30:
result = "Failed"
elif marks > 75:
result = "Passed with distinction"
else:
result = "Passed" print(result)

This will produce following result:

Passed with distinction


*******************************************************
The match Statement

Python supports Match-Case statement, which can also be used as a part of


decision making. If a pattern matches the expression, the code under that
case will execute.

Example
Following is a simple example which makes use of match statement.
def checkVowel(n):
match n: case 'a': return "Vowel alphabet"
case 'e': return "Vowel alphabet"
case 'i': return "Vowel alphabet"
case 'o': return "Vowel alphabet"
case 'u': return "Vowel alphabet"
case _: return "Simple alphabet"
print (checkVowel('a'))
print (checkVowel('m'))
print (checkVowel('o'))

This will produce following result:

Vowel alphabet
Simple alphabet
Vowel alphabet

Page No:- 32
Loops or Iteration Statements

Most of the processes require a group of instructions to be repeatedly


executed. In programming terminology, it is called a loop. Instead of the next
step, if the flow is redirected towards any earlier step, it constitutes a loop.

The following diagram illustrates how the looping works –

If the control goes back unconditionally, it forms an infinite loop which is not
desired as the rest of the code would never get executed.
In a conditional loop, the repeated iteration of block of statements goes on till
a certain condition is met. Python supports a number of loops like for loop,
while loop which we will study in next chapters.

The for Loop

The for loop iterates over the items of any sequence, such as a list, tuple or a
string .

Example
Following is an example which makes use of For Loop to iterate through an
array in Python:
words = ["one", "two", "three"]
for x in words:
print(x)

This will produce following result:


one
two
three

The while Loop


The while loop repeatedly executes a target statement as long as a given
boolean expression is true.
Example
Following is an example which makes use of While Loop to print first 5
numbers in Python:

Page No:- 33
i=1
while i< 6:
print(i)
i += 1
This will produce following result:
1
2
3
4
5

Jump Statements

The jump statements are used to jump on a specific statement by breaking the
current flow of the program. In Python, there are two jump
statements break and continue.
The break Statement
It terminates the current loop and resumes execution at the next statement.

Example
x=0
while x < 10:
print("x:", x)
if x == 5:
print("Breaking...")
break
x += 1
print("End")
This will produce following result:
x: 0
x: 1
x: 2
x: 3
x: 4
x: 5
Breaking...
End

The continue Statement

It skips the execution of the program block and returns the control to the
beginning of the current loop to start the next iteration.

Example

The following example demonstrates the use of continue statement −


for letter in "Python":

Page No:- 34
# continue when letter is 'h'
if letter == "h":
continue
print("Current Letter :", letter)

This will produce following result:


Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
********************************************************
Indentation in Python
In Python, indentation is used to define blocks of code. It tells the Python
interpreter that a group of statements belongs to a specific block. All
statements with the same level of indentation are considered part of the same
block. Indentation is achieved using whitespace (spaces or tabs) at the
beginning of each line.

if 10 > 5:
print("This is true!")
print("I am tab indentation")

print("I have no indentation")

Output : This is true!


I am tab indentation
I have no indentation

 The first two print statements are indented by 4 spaces, so they belong
to the if block.
 The third print statement is not indented, so it is outside the if block.

**************************************************
Conditional Statements?
Conditional Statements are statements in Python that provide a choice for the
control flow based on a condition. It means that the control flow of the Python
program will be decided based on the outcome of the condition.
Types of Conditional Statements in Python
1. If Conditional Statement in Python
2. If else Conditional Statements in Python
3. Nested if..else Conditional Statements in Python
4. If-elif-else Conditional Statements in Python
5. Ternary Expression Conditional Statements in Python

Page No:- 35
1. If Conditional Statement in Python
If the simple code of block is to be performed if the condition holds then the if
statement is used. Here the condition mentioned holds then the code of the
block runs otherwise not.
Syntax of If Statement:
if condition:
# Statements to execute if
# condition is true
Python
# if statement example
if 10 > 5:

print("10 greater than 5")


print("Program ended")

Output
10 greater than 5
Program ended
******************************************************

2. If else Conditional Statements in Python


In a conditional if Statement the additional block of code is merged as an else
statement which is performed when if condition is false.
Syntax of Python If-Else:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
# if..else statement example
x=3
if x == 4:
print("Yes")
else:
print("No")

Page No:- 36
Output
No
**********************************************************
3. Nested if..else Conditional Statements in Python
Nested if..else means an if-else statement inside another if statement. Or in
simple words first, there is an outer if statement, and inside it another if – else
statement is present and such type of statement is known as nested if
statement. We can use one if or else if statement inside another if or else if
statements.
Python
# if..else chain statement
letter = "A"
if letter == "B":
print("letter is B")
else:

if letter == "C":
print("letter is C")
else:
if letter == "A":
print("letter is A")
else:
print("letter isn't A, B and C")

Output
letter is A
****************************
4. If-elif-else Conditional Statements in Python
The if statements are executed from the top down. As soon as one of the
conditions controlling the if is true, the statement associated with that if is
executed, and the rest of the ladder is bypassed. If none of the conditions is
true, then the final “else” statement will be executed.

Page No:- 37
# if-elif statement example
letter = "A"
if letter == "B":
print("letter is B")
elif letter == "C":
print("letter is C")
elif letter == "A":
print("letter is A")
else:

print("letter isn't A, B or C")

Output
letter is A
****************************
5. Ternary Expression Conditional Statements in Python
The Python ternary Expression determines if a condition is true or false and
then returns the appropriate value in accordance with the result. The ternary
Expression is useful in cases where we need to assign a value to a variable
based on a simple condition, and we want to keep our code more concise — all
in just one line of code.
Syntax of Ternary Expression
Syntax: [on_true] if [expression] else [on_false]
expression: conditional_expression | lambda_expr
Python
# Python program to demonstrate nested ternary operator
a, b = 10, 20
print("Both a and b are equal" if a == b else "a is greater than b"
if a > b else "b is greater than a")

Output : b is greater than a


********************************************************

Page No:- 38
Iterative statements in python
A loop is a programming element that repeats a section of code until a specific
condition is met or a set number of times has been reached. Loops are
essential for saving time and reducing errors when performing repetitive
tasks.
Python loops and understand their working with the help of examp – For
loop and While loop to handle looping requirements. Loops in Python
provides three ways for executing the loops.
While all the ways provide similar basic functionality, they differ in their syntax
and condition-checking time. In this article, we will look at Python loops and
understand their working with the help of examples.
1. While Loop in Python
A while loop is used to execute a block of statements repeatedly until a given
condition is satisfied. When the condition becomes false, the line immediately
after the loop in the program is executed.
Python While Loop Syntax:
while expression:
statement(s)
programme:
count = 0
while (count < 3):
count = count + 1
print("Hello")

Output: Hello
Hello
Hello

**************************
for loop
A for loop in Python is a programming construct that executes a block of code
repeatedly until a condition is met.
For Loop Syntax:
for iterator_var in sequence:
statements(s)

Page No:- 39
n=4
for i in range(0, n):
print(i)
Output: 0
1
2
3
****************************************
Nested Loops in Python
A nested loop has one or more loops within the body of another loop. The two
loops are referred to as outer loop and inner loop. The outer loop controls the
number of the inner loop's full execution. More than one inner loop can exist in
a nested loop.
Nested Loops Syntax:
for iterator_var in sequence:
for iterator_var in sequence:
statements(s)
statements(s)
syntax
while expression:
while expression:
statement(s)
statement(s)
programme:

from future import print_function


for i in range(1, 5):
for j in range(i):

print(i, end=' ')


print()
Output

1
22
333

Page No:- 40
4444
*************************
Python break statement
break statement in Python is used to bring the control out of the loop when
some external condition is triggered. break statement is put inside the loop
body (generally after if condition). It terminates the current loop, i.e., the loop
in which it appears, and resumes execution at the next statement immediately
after the end of that loop. If the break statement is inside a nested loop, the
break will terminate the innermost loop.
for i in range(10):
print(i)
if i == 2:

break
Output:
0
1
2
*************************
Continue Statement
The continue statement in Python returns the control to the beginning of the
loop.
Example: This Python code iterates through the characters of the
string ‘geeksforgeeks’. When it encounters the characters ‘e’ or ‘s’, it uses
the continue statement to skip the current iteration and continue with the next
character. For all other characters, it prints “Current Letter :” followed by the
character. So, the output will display all characters except ‘e’ and ‘s’, each on
a separate line.
for letter in 'geeksforgeeks':
if letter == 'e' or letter == 's':
continue

print('Current Letter :', letter)


Output ; Current Letter : g
Current Letter : k
Current Letter : f
Current Letter : o
Current Letter : r

Page No:- 41
Current Letter : g
Current Letter : k
*************************************
Python Nested Loops
In Python programming language there are two types of loops which are for
loop and while loop. Using these loops we can create nested loops in Python.
Nested loops mean loops inside a loop.
x = [1, 2]
y = [4, 5]
for i in x:
for j in y:
print(i, j)
Output:
1 4
1 5
2 4
2 5
********************
What are some common operations you can perform on strings in
Python?
Strings in Python are one of the most versatile and commonly used data types.
They represent sequences of characters and come with a wide range of built-in
methods that allow for easy manipulation, transformation, and analysis.
Python provides a variety of string operations that make it easy to perform
tasks such as concatenation, searching, slicing, and formatting. Understanding
these operations is crucial for handling text efficiently in Python programming.
Here are some common operations you can perform on strings in Python:
1. Concatenation: String concatenation allows you to join two or more
strings together using the + operator.
Example:
stri- "Hello"

str2= "World"

result=strl+""+str2 #Concatenating with a space in between

print(result)
#Output: Hello World

Page No:- 42
2. Repetition: You can repeat a string multiple times using the * operator.
This is useful when you want to create repeating patterns or messages.
Example:
greeting = "Hi!"
repeated greeting * 3
print(repeated) # Output: Hi! Hi! Hi!

3. String Length: The len() function is used to get the length of a string, ie,
the number of characters it contains.
Example:
my string "Python"
length = len(my_string)
print(length)
# Output: 6
4. String Slicing: Slicing allows you to extract a portion of a string using the
slicong syntax string/[Link]). The start index is inclusive, while the end
index is exclusive
Example:
my_string "Python"
substring my_string[1:4] # Extracts characters from index 1 to 3
print(substring)
#Output: yth

5. Changing Case: Python provides built-in methods to change the case of


strings
upper(): Converts all characters to uppercase.
lower(): Converts all characters to lowercase.
title(): Converts the first character of each word to uppercase.
Example:my string "hello world"
print(my_string upper()) # Output: HELLO WORLD
print(my_string.lower()) # Output: hello world
print(my_string.title()) #Output: Hello World

Page No:- 43
6. String Search and Replace: Searching:
 The find() method searches for a substring within a string and returns
the index of the first occurrence. If the substring is not found, it returns
-1.
 Replacing: The replace() method replaces all occurrences of a specified
substring with another substring.
Example:
text "I love Python programming"
index [Link]("Python")
print(index) #Output: 7
replaced [Link]("Python", "Java")
print(replaced) #Output: I love Java programming
7. String Splitning and Joining:
 Splitting: The split() method splits a string into a list based on a
specified delimite (default is whitespace).
 Joining: The join() method is used to join elements of a list into a single
string, with each element separated by a specified delimiter.
Example:
sentence "Python is fun"
words [Link]() # Splitting by space
print(words) # Output: ['Python', 'is', 'fun']
joined sentence = "-".join(words) # Joining with hyphens
print(joined_sentence) # Output: Python-is-fun
8. Checking String Contents:
Python provides methods to check the characteristics of strings:
isalnum(): Returns True if the string contains only alphanumeric characters
(letters a numbers).
isalpha(): Returns True if the string contains only letters.
isdigit(): Returns True if the string contains only digits.
Example:
my_string = "Python123"
print(my_string.isalnum()) # Output: True
print(my_string.isalpha()) # Output: False

*************************

Page No:- 44
Traversing a string in python
Traversing a string means accessing all the elements of the string one after the
other by using the subscript. A string can be traversed using for loop or while
loop.
There are several methods to do this, but we will focus on the most efficient
one. The simplest way is to use a loop.
1. Using a for loop:
This is the most straightforward and Pythonic way to iterate over each
character in a string:
my_string = "Hello, world!"
for char in my_string:
print(char)
Output:
H
e
l
l
o
,

w
o
r
l
d
!

2. Using a while loop:


You can also use a while loop with an index to access characters by their
position:
my_string = "Hello, world!"
index = 0

while index < len(my_string):


print(my_string[index])
index += 1

Page No:- 45
Output:
H
e
l
l
o
,
w
o
r
l
d
!

3. Using enumerate():
The enumerate() function adds a counter to an iterable, making it useful for
keeping track of the index while iterating:
my_string = "Hello, world!"
for index, char in enumerate(my_string):
print(f"Character at index {index}: {char}")
Output:
Character at index 0: H
Character at index 1: e
Character at index 2: l
Character at index 3: l
Character at index 4: o
Character at index 5: ,
Character at index 6:
Character at index 7: w
Character at index 8: o
Character at index 9: r
Character at index 10: l
Page No:- 46
Character at index 11: d
Character at index 12: !
4. Using range():

The range() function generates a sequence of numbers, which can be used as


indices to access characters in the string:
my_string = "Hello, world!"
for i in range(len(my_string)):
print(my_string[i])

Output:
H
e
l
l
o
,

w
o
r
l
d
!

**************************************
In Python, strings are used for representing textual data. A string is a
sequence of characters enclosed in either single quotes ('') or double quotes
(“”). The Python language provides various built-in methods and functionalities
to work with strings efficiently.

String Methods

Python string methods is a collection of in-built Python functions that


operates on lists.
Python string is a sequence of Unicode characters that is enclosed in
quotation marks.

Page No:- 47
The in-built string functions i.e. the functions provided by Python to operate
on strings.
List of String Methods in Python

Here is the list of in-built Python string methods, that you can use to
perform actions on string:

Functio
n Description
Name

Converts the first character of the string to a capital (uppercase)


letter.
name="pooja"
capitalize() print([Link]())

Output
POOJA

Implements case less string matching

string ="MYNUDDINS-S"
casefold()
print("lowercase string: ", [Link]())

Output:
lowercase string: mynuddin-s

Pad the string with the specified character.

string ="Mynuddin-s"

new_string =[Link](24)
center()
print("After padding String is: ", new_string)

Output:
After padding String is: mynuddin-s

Returns the number of occurrences of a substring in the string.

my_string = "Apple"
count() char_count =
my_string.count('A')
print(char_count)
Output

Page No:- 48
Function
Name Description

encode() Encodes strings with the specified encoded scheme

Returns “True” if a string ends with the given suffix


string="geeksforgeeks"
print([Link]("geeks"))
endswith()
Output
True

Specifies the amount of space to be substituted with the “\t”


symbol in the string

expandtabs string ="\t\tCenter\t\t"


() print([Link]())

Output:
Center

Returns the lowest index of the substring if it is found


word='find me if you can'
print([Link]('me'))
find()
Output
5

Formats the string for printing it to console


name="Ram"
age=22
message="My name is {0} and I am {1} years \
old. {1} is my favorite \
format()
number.".format(name,age)
print(message)
Output
My name is Ram and I am 22 years old. 22 is my favorite
number.

Formats specified values in a string using a dictionary

format_ma a ={'x':'John', 'y':'Wick'}


p() print("{x}'s last name is {y}".format_map(a))

Output:

Page No:- 49
Function
Name Description

John's last name is Wick

Returns the position of the first occurrence of a substring in a


string

string = 'random'
index()
print("index of 'and' in string:", [Link]('and'))

Output
Index of 'and' in string: 1

Checks whether all the characters in a given string is


alphanumeric or not.

string ="abc123"
isalnum()
print([Link]())

Output:
True

Returns “True” if all characters in the string are alphabets.

string ="geeks"
isalpha() print([Link]())

Output: True

Returns true if all characters in a string are decimal.

print("100".isdecimal())
isdecimal()
Output
True

Returns “True” if all characters in the string are digits

print("101".isdigit())
isdigit()
Output:
True

isidentifier(
Check whether a string is a valid identifier or not
)

Page No:- 50
Function
Name Description

string ="Coding_101"
print([Link]())

Output:
True

Checks if all characters in the string are lowercase.

print("geeks".islower())
islower()
Output:
True

Returns “True” if all characters in the string are numeric


characters.

string ="123456789"
isnumeric() result =[Link]()
print(result)

Output:
True

Returns “True” if all characters in the string are printable or the


string is empty.

string ='My name is Ayush'


print([Link]())
string ='My name is \n Ayush'
isprintable( print([Link]())
) string =''
print( [Link]())

Output:
True
False
True

Returns “True” if all characters in the string are whitespace


characters.

isspace() string ="\n\t\n"


print([Link]())

Output:

Page No:- 51
Function
Name Description

True

Returns “True” if the string is a title cased string.

string ="Geeks"
istitle() print([Link]())

Output:
True

Checks if all characters in the string are uppercase.

print(("GEEKS").isupper())
isupper()
Output:
True

Returns a concatenated String.


str='-'.join('hello')
join() print(str)# Output: h-e-l-l-o
Output:
h-e-l-l-o

Left aligns the string according to the width specified

string ='geeks'
length =8
fillchar ='*'
ljust()
print([Link](length, fillchar))

Output:
***geeks

Converts all uppercase characters in a string into lowercase

string ="ConvErT ALL tO LoWErCASe"


print([Link]())
lower()

Output
convert all to lowercase

Page No:- 52
Function
Name Description

Returns the string with leading characters removed

string ="++++x...y!!z* geeksforgeeks"


lstrip() print([Link]("+.!*xyz"))

Output:
geeksforgeeks

maketrans(
Returns a translation table.
)

Splits the string at the first occurrence of the separator

str="I love Geeks for geeks"


partition() print([Link]("for"))

Output:
('I love Geeks ', 'for', ' geeks')

Replaces all occurrences of a substring with another substring.


string="Hello World"
new_string=[Link]("Hello","Good Bye")
replace() print(new_string)

Output
Good Bye World

Returns the highest index of the substring.

string ="GeeksForGeeks"
rfind() print([Link]("Geeks"))

Output:
8

rindex() Returns the highest index of the substring inside the string

rjust() Right aligns the string according to the width specified

rpartition() Split the given string into three parts

rsplit() Split the string from the right by the specified separator

Page No:- 53
Function
Name Description

rstrip() Removes trailing characters

splitlines() Split the lines at line boundaries

startswith(
Returns “True” if a string starts with the given prefix
)

strip() Returns the string with both leading and trailing characters

swapcase() Converts all uppercase characters to lowercase and vice versa

title() Convert string to title case

translate() Modify string according to given translation mappings

Converts all lowercase characters in a string into uppercase

original_text ="lisT Upper"


upper_text =original_text.upper()
upper()
print(upper_text)

Output
LIST UPPER

Returns a copy of the string with ‘0’ characters padded to the


zfill()
left side of the string

************************
UNIT-II
Python Function

Python Functions is a block of statements that return the specific task. The
idea is to put some commonly or repeatedly done tasks together and make a
function so that instead of writing the same code again and again for different
inputs, we can do the function calls to reuse code contained in it over and over
again.
Advantages of Python Functions
o Once defined, Python functions can be called multiple times and from
any location in a program.

Page No:- 54
o Our Python program can be broken up into numerous, easy-to-follow
functions if it is significant.
o The ability to return as many outputs as we want using a variety of
arguments is one of Python's most significant achievements.

Creating a Function in Python


We can define a function in Python, using the def keyword. We can add any
type of functionalities and properties to it as we require.
# A simple Python function
def fun():
print("Welcome to Vishwa Hitha Degree College, Mpl")
*****************
Types of Functions in Python

In Python, there are various types of functions that you can use to perform
different operations. Here are some of the most commonly used types of
functions in Python:

Built-in Functions: These functions are built into the Python language and
can be used without the need for additional code. Some examples of built-in
functions are print(), len(), sum(), min(), max(), etc.

User-defined Functions: You create these functions to perform a specific


task. You can define your functions using the def keyword followed by the
function name, parameter(s), and the code block that performs the desired
operation.

Recursive Functions: These functions call themselves to perform a task


repeatedly until a certain condition is met. Recursive functions can be useful in
situations where a problem can be broken down into smaller sub-problems.

Page No:- 55
Lambda Functions: These are small anonymous functions that can be
defined in a single line of code. Lambda functions are often used for quick,
simple operations that don’t require a full function definition.
Higher-Order Functions: These are functions that take other functions as
arguments and/or return functions as output. Higher-order functions can be
used to create more complex operations by combining simpler functions.

Python Built-in Functions List

Built-in functions in Python are pre-defined functions that are part of the
Python interpreter and are available to use without any additional installation
or import. They are designed to perform common tasks and are faster than
regular functions because they don't need to go through an extra step before
being called.

Function Name Description

Python abs() Return the absolute value of a number

It takes an asynchronous iterable as an argument


Python aiter()
and returns an asynchronous iterator for that iterable

Return true if all the elements of a given iterable(


Python all() List, Dictionary, Tuple, set, etc) are True else it
returns False

Returns true if any of the elements of a given


Python any() iterable( List, Dictionary, Tuple, set, etc) are True
else it returns False

used for getting the next item from an asynchronous


Python anext()
iterator

Returns a string containing a printable representation


Python ascii()
of an object

Python bin() Convert integer to a binary string

Return or convert a value to a Boolean value i.e.,


Python bool()
True or False

Python It is used for dropping into the debugger at the call


breakpoint() site during runtime for debugging purposes

Page No:- 56
Function Name Description

Python Returns a byte array object which is an array of given


bytearray() bytes

Converts an object to an immutable byte-


Python bytes()
represented object of a given size and data

Returns True if the object passed appears to be


Python callable()
callable

Returns a string representing a character whose


Python chr()
Unicode code point is an integer

Python
Returns a class method for a given function
classmethod()

Python compile() Returns a Python code object

Python complex() Creates Complex Number

Python delattr() Delete the named attribute from the object

Python dict() Creates a Python Dictionary

Returns a list of the attributes and methods of any


Python dir()
object

Takes two numbers and returns a pair of numbers


Python divmod()
consisting of their quotient and remainder

Python Adds a counter to an iterable and returns it in a form


enumerate() of enumerating object

Parses the expression passed to it and runs Python


Python eval()
expression(code) within the program

Python exec() Used for the dynamic execution of the program

Filters the given sequence with the help of a function


Python filter() that tests each element in the sequence to be true or
not

Python float() Return a floating-point number from a number or a

Page No:- 57
Function Name Description

string

Python format() Formats a specified value

Python
Returns immutable frozenset
frozenset()

Python getattr() Access the attribute value of an object

Returns the dictionary of the current global symbol


Python globals()
table

Check if an object has the given named attribute and


Python hasattr()
return true if present

Python hash() Encode the data into an unrecognizable value

Display the documentation of modules, functions,


Python help()
classes, keywords, etc

Convert an integer number into its corresponding


Python hex()
hexadecimal form

Python id() Return the identity of an object

Python input() Take input from the user as a string

Python int() Converts a number in a given base to decimal

Python
Checks if the objects belong to a certain class or not
isinstance()

Python
Check if a class is a subclass of another class or not
issubclass()

Python iter() Convert an iterable to an iterator

Python len() Returns the length of the object

Python list() Creates a list in Python

Page No:- 58
Function Name Description

Returns the dictionary of the current local symbol


Python locals()
table

Returns a map object(which is an iterator) of the


Python map() results after applying the given function to each item
of a given iterable

Returns the largest item in an iterable or the largest


Python max()
of two or more arguments

Python
Returns memory view of an argument
memoryview()

Returns the smallest item in an iterable or the


Python min()
smallest of two or more arguments

Python next() Receives the next item from the iterator

Python object() Returns a new object

returns an octal representation of an integer in a


Python oct()
string format.

Python open() Open a file and return its object

Returns the Unicode equivalence of the passed


Python ord()
argument

Python pow() Compute the power of a number

Python print() Print output to the console

Python property() Create a property of a class

Python range() Generate a sequence of numbers

Python repr() Return the printable version of the object

Returns an iterator that accesses the given sequence


Python reversed()
in the reverse order

Page No:- 59
Function Name Description

Rounds off to the given number of digits and returns


Python round()
the floating-point number

Convert any of the iterable to a sequence of iterable


Python set()
elements with distinct elements

Python setattr() Assign the object attribute its value

Python slice() Returns a slice object

Returns a list with the elements in a sorted manner,


Python sorted()
without modifying the original sequence

Python
Converts a message into the static message
staticmethod()

Python str() Returns the string version of the object

Python sum() Sums up the numbers in the list

Python super() Returns a temporary object of the superclass

Python tuple() Creates a tuple in Python

Python type() Returns the type of the object

Returns the dict attribute for a module, class,


Python vars()
instance, or any other object

Python zip() Maps the similar index of multiple containers

Python
Imports the module during runtime
import ()

Python abs() Function Example


# An integer
var = -94
print('Absolute value of integer is:', abs(var))
Output:
Absolute value of integer is: 94
**************

Page No:- 60
Working of all() with Lists
# All elements of list are true
l = [4, 5, 1]
print(all(l))

# All elements of list are false


l = [0, 0, False]
print(all(l))

Output
True
False
***************
Python any() Function Example

# a List of boolean values


l = [False, False, True, False, False]
print(any(l))

Output:
True

***********************
Usage of Python ascii() Function
print(ascii("¥"))
Output
'\xa5'
***************
bin() in Python
x = bin(42)
print(x)
Output
0b101010
****************

bool() in Python

x = bool(1)
print(x)
y = bool()
print(y)

Output
True
False
************
breakpoint() function in Python

def debugger(a, b):

Page No:- 61
# adding a breakpoint()
breakpoint()
result = a / b
return result

print(debugger(5, 0))

Output:

***************
chr() Function in Python
num = 97
print("ASCII Value of 97 is: ", chr(num))

Output
ASCII Value of 97 is: a
*****************
complex() Function in Python
print(complex(1, 2))
Output:
(1+2j)
**************
eval() Function in Python Example
print(eval('1+2'))
print(eval("sum([1, 2, 3, 4])"))

Output
3
10
*************

filter Function Example


# function that filters vowels
def fun(variable):
letters = ['a', 'e', 'i', 'o', 'u']
if (variable in letters):
return True
else:
return False

# sequence
sequence = ['g', 'e', 'e', 'j', 'k', 's', 'p', 'r']

# using filter function


filtered = filter(fun, sequence)

print('The filtered letters are:')


for s in filtered:
Page No:- 62
print(s)
Output:
The filtered letters are:
e
e
***********

input() Function

name = input("What is your name? ")


print("Hello, " + name + "!")

Output
What is your name? GFG
Hello, GFG!
**************
String len() Function
# Python program to demonstrate the use of
# len() method

# with tuple
tup = (1,2,3)
print(len(tup))

# with list
l = [1,2,3,4]
print(len(l))

Output
3
4
***************
min() function

numbers = [23,25,65,21,98]
print(min(numbers))
Output
21
max() function

var1 = 4
var2 = 8
var3 = 2

max_val = max(var1, var2, var3)


print(max_val)

Output
8

Page No:- 63
print() Function

name = “John”
age = 30

print(“Name:”, name)
print(“Age:”, age)

Output
Name: John
Age: 30
*****************************************
Python User defined functions
A function is a set of statements that take inputs, do some specific
computation, and produce output. The idea is to put some commonly or
repeatedly done tasks together and make a function so that instead of writing
the same code again and again for different inputs, we can call the function.
Functions that readily come with Python are called built-in functions. Python
provides built-in functions like print(), etc. but we can also create your own
functions. These functions are known as user defines functions.
All the functions that are written by any of us come under the category of
user-defined functions. Below are the steps for writing user-defined functions
in Python.
 In Python, a def keyword is used to declare user-defined functions.
 An indented block of statements follows the function name and
arguments which contains the body of the function.
Syntax:
def function_name():
statements
.
# Declaring a function
def fun():
print("Inside function")
# Driver's code
# Calling function
fun()
Output:
Inside function
**********************************

Page No:- 64
Python Parameterized Function
The function may take arguments(s) also called parameters as input within the
opening and closing parentheses, just after the function name followed by a
colon.
Syntax:
def function_name(argument1, argument2, ...):
statements
.

def evenOdd( x ):
if (x % 2 == 0):
print("even")
else:
print("odd")
# Driver code
evenOdd(2)
evenOdd(3)
Output:
even
odd
*******************************************
Recursion in Python
Recursion involves a function calling itself directly or indirectly to solve a
problem by breaking it down into simpler and more manageable parts.
In Python, recursion is widely used for tasks that can be divided into identical
subtasks.
def factorial(n):
if n == 1:

return 1
else:
return n * factorial(n-1)
print(factorial(5))
Output: 120
*************************************

Page No:- 65
Python Scope of Variables

In Python, variables are the containers for storing data values. Unlike other
languages like C/C++/JAVA, 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.

Python Scope variable


The location where we can find a variable and also access it if required is called
the scope of a variable.

Python Local variable


Local variables are those that are initialized within a function and are unique to
that function. It cannot be accessed outside of the function. Let’s look at how
to make a local variable.

def f():

# local variable
s = "I love Geeksforgeeks"
print(s)

# Driver code
f()

Output
I love Geeksforgeeks
************************

Python Global variables

Global variables are the ones that are defined and declared outside any
function and are not specified to any function. They can be used by any part of
the program.

Example:

# This function uses global variable s


def f():
print(s)
# Global scope
s = "I love Geeksforgeeks"
f()

Output: I love Geeksforgeeks


*******************

Page No:- 66
Global and Local Variables with the Same Name

Now suppose a variable with the same name is defined inside the scope of the
function as well then it will print the value given inside the function only and
not the global value.

# This function has a variable with


# name same as s.
def f():
s = "Me too."
print(s)

# Global scope
s = "I love Geeksforgeeks"
f()
print(s)

Output:
Me too.
I love Geeksforgeeks

****************************************************
Python Classes
A class in Python is a user-defined template for creating objects. It bundles
data and functions together, making it easier to manage and use them. When
we create a new class, we define a new type of object. We can then create
multiple instances of this object type.
Classes are created using class keyword. Attributes are variables defined inside
the class and represent the properties of the class. Attributes can be accessed
using the dot . operator (e.g., MyClass.my_attribute).
Create a Class
# define a class
class Dog:
sound = "bark" # class attribute

Create Object
An Object is an instance of a Class. It represents a specific implementation of
the class and holds its own data.
class Dog:
sound = "bark"

Page No:- 67
# Create an object from the class
dog1 = Dog()
# Access the class attribute
print([Link])
*****************************************************
Calling a Function in Python
After creating a function in Python we can call it by using the name of the
functions Python followed by parenthesis containing parameters of that
particular function. Below is the example for calling def function Python.
Python
# A simple Python function
def fun():
print("Welcome to Vishwa Hitha Degree College, Mpl")
# Driver code to call a function
fun()
Output:
Welcome to Vishwa Hitha Degree College, Mpl
*********************
Python Function with Parameters
If you have experience in C/C++ or Java then you must be thinking about
the return type of the function and data type of arguments. That is possible in
Python as well (specifically for Python 3.5 and above).
Python Function Syntax with Parameters
def function_name(parameter: data_type) -> return_type:
"""Docstring"""
# body of the function
return expression
The following example uses arguments and parameters that you will learn later
in this article so you can come back to it again if not understood.
Python
def add(num1: int, num2: int) -> int:
"""Add two numbers"""

Page No:- 68
num3 = num1 + num2
return num3
# Driver code
num1, num2 = 5, 15
ans = add(num1, num2)
print(f"The addition of {num1} and {num2} results {ans}.")
Output:
The addition of 5 and 15 results 20.
****************
Python Function Arguments
Arguments are the values passed inside the parenthesis of the function. A
function can have any number of arguments separated by a comma.
In this example, we will create a simple function in Python to check whether
the number passed as an argument to the function is even or odd.
Python
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
evenOdd(2)
evenOdd(3)
Output:
even
odd
*****************
Inheritance in Python
Inheritance is a fundamental concept in object-oriented programming (OOP)
that allows a class (called a child or derived class) to inherit attributes and
methods from another class (called a parent or base class). This promotes
code reuse, modularity, and a hierarchical class structure.

Page No:- 69
Inheritance allows us to define a class that inherits all the methods and
properties from another class.
Syntax for Inheritance
class ParentClass:
# Parent class code here
pass
class ChildClass(ParentClass):

# Child class code here


pass
Explanation of Python Inheritance Syntax

1. Parent Class:
 This is the base class from which other classes inherit.
 It contains attributes and methods that the child class can reuse.
2. Child Class:
 This is the derived class that inherits from the parent class.
 The syntax for inheritance is class ChildClass(ParentClass).
 The child class automatically gets all attributes and methods of the
parent class unless overridden.
Parent Class
In object-oriented programming, a parent class (also known as a base
class) defines common attributes and methods that can be inherited by
other classes. These attributes and methods serve as the foundation for
the child classes. By using inheritance, child classes can access and
extend the functionality provided by the parent class.
Child Class
A child class (also known as a subclass) is a class that inherits properties
and methods from its parent class. The child class can also introduce
additional attributes and methods, or even override the ones inherited
from the parent.
Types of Python Inheritance
1. Single Inheritance: A child class inherits from one parent class.
2. Multiple Inheritance: A child class inherits from more than one
parent class.

Page No:- 70
3. Multilevel Inheritance: A class is derived from a class which is also
derived from another class.
4. Hierarchical Inheritance: Multiple classes inherit from a single
parent class.
5. Hybrid Inheritance: A combination of more than one type of
inheritance.
Single Inheritance:
Single inheritance enables a derived class to inherit properties from a
single parent class, thus enabling code reusability and the addition of
new features to existing code.

# Python program to demonstrate single inheritance


# Base class
class Parent:

def func1(self):
print("This function is in parent class.")
# Derived class
class Child(Parent):
def func2(self):
print("This function is in child class.")
# Driver's code
object = Child()
object.func1()
object.func2()
Output:
This function is in parent class.
This function is in child class.
********************************

Page No:- 71
Multiple Inheritance:
When a class can be derived from more than one base class this type of
inheritance is called multiple inheritances. In multiple inheritances, all
the features of the base classes are inherited into the derived class.

# Python program to demonstrate multiple inheritance


# Base class1
class Mother:
mothername = ""
def mother(self):
print([Link])
# Base class2
class Father:
fathername = ""
def father(self):
print([Link])
# Derived class
class Son(Mother, Father):
def parents(self):
print("Father :", [Link])
print("Mother :", [Link])
# Driver's code
s1 = Son()
[Link] = "Mynu"

Page No:- 72
[Link] = "pooja"
[Link]()
Output: Father : Mynu

Mother : pooja
*****************************
Multilevel Inheritance :
In multilevel inheritance, features of the base class and the derived class
are further inherited into the new derived class. This is similar to a
relationship representing a child and a grandfather.

# Python program to demonstrate multilevel inheritance


class Animal:
def speak(self):
print("Animal Speaking")
#The child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
#The child class Dogchild inherits another child class Dog
class DogChild(Dog):
def eat(self):
print("Eating bread...")
d = DogChild()
[Link]()
[Link]()
[Link]()
Output:

dog barking
Animal Speaking
Eating bread...
*************************

Page No:- 73
Hierarchical Inheritance:
When more than one derived class are created from a single base this type of
inheritance is called hierarchical inheritance. In this program, we have a parent
(base) class and two child (derived) classes.

# Python program to demonstrate # Hierarchical inheritance # Base class


class Parent:
def func1(self):

print("This function is in parent class.")


# Derived class1
class Child1(Parent):
def func2(self):
print("This function is in child 1.")
# Derivied class2
class Child2(Parent):
def func3(self):
print("This function is in child 2.")
# Driver's code
object1 = Child1()
object2 = Child2()
object1.func1()
object1.func2()
object2.func1()
object2.func3()

Page No:- 74
Output:
This function is in parent class.
This function is in child 1.
This function is in parent class.
This function is in child 2.
************************

Hybrid Inheritance:
Inheritance consisting of multiple types of inheritance is called hybrid
inheritance.

# Python program to demonstrate hybrid inheritance


class School:
def func1(self):

print("This function is in school.")


class Student1(School):
def func2(self):

print("This function is in student 1. ")


class Student2(School):
def func3(self):
print("This function is in student 2.")
class Student3(Student1, School):
def func4(self):
print("This function is in student 3.")
# Driver's code
object = Student3()
object.func1()
object.func2()
Page No:- 75
Output:
This function is in school.
This function is in student 1.
************************
Polymorphism in Python
Polymorphism is a foundational concept in programming that allows entities
like functions, methods or operators to behave differently based on the type of
data they are handling. Derived from Greek, the term literally means “many
forms”.
Python’s dynamic typing and duck typing make it inherently polymorphic.
Functions, operators and even built-in objects like loops exhibit polymorphic
behavior.
Polymorphism in Built-in Functions
Python’s built-in functions exhibit polymorphism, adapting to various data
types.
print(len("Hello")) # String length
print(len([1, 2, 3])) # List length
print(max(1, 3, 2)) # Maximum of integers
print(max("a", "z", "m")) # Maximum in strings

output
5
3
3
z
*****************
Polymorphism in Functions
Duck typing enables functions to work with any object regardless of its type.
def add(a, b):
return a + b
print(add(3, 4)) # Integer addition
print(add("Hello, ", "World!")) # String concatenation
print(add([1, 2], [3, 4])) # List concatenation

Page No:- 76
output:
7
Hello, World!
[1, 2, 3, 4]
******************
Polymorphism in Operators
Operator Overloading
In Python, operators like + behave polymorphically, performing
addition, concatenation or merging based on the data type.

print(5 + 10) # Integer addition


print("Hello " + "World!") # String concatenation
print([1, 2] + [3, 4]) # List concatenation

output
15
Hello World!
[1, 2, 3, 4]
*****************************
Types of Polymorphism
Compile-time Polymorphism

 Found in statically typed languages like Java or C++, where the behavior
of a function or operator is resolved during the program’s compilation
phase.
 Examples include method overloading and operator overloading, where
multiple functions or operators can share the same name but perform
different tasks based on the context.
 In Python, which is dynamically typed, compile-time polymorphism is not
natively supported. Instead, Python uses techniques like dynamic typing
and duck typing to achieve similar flexibility.
Runtime Polymorphism
 Occurs when the behavior of a method is determined at runtime based
on the type of the object.
 In Python, this is achieved through method overriding: a child class can
redefine a method from its parent class to provide its own specific
implementation.
 Python’s dynamic nature allows it to excel at runtime polymorphism,
enabling flexible and adaptable code.
****************************************************

Page No:- 77
Python Modules
Python Module is a file that contains built-in functions, classes,its and
variables. There are many Python modules, each with its specific work.
A Python module is a file containing Python definitions and statements. A
module can define functions, classes, and variables. A module can also include
runnable code.
Grouping related code into a module makes the code easier to understand and
use. It also makes the code logically organized.

Create a Python Module


To create a Python module, write the desired code and save that in a file
with .py extension.
# A simple module, [Link]
def add(x, y):
return (x+y)
def subtract(x, y):
return (x-y)
************
Import module in Python
We can import the functions, and classes defined in a module to another
module using the import statement in some other Python source file.
When the interpreter encounters an import statement, it imports the module if
the module is present in the search path.
# importing module [Link]
import calc
print([Link](10, 2))
Output:
12

**************

Page No:- 78
Python Import From Module
Python’s from statement lets you import specific attributes from a
module without importing the module as a whole.
Import Specific Attributes from a Python module
# importing sqrt() and factorial from the
# module math

from math import sqrt, factorial


# if we simply do "import math", then
# [Link](16) and [Link]()
# are required.
print(sqrt(16))
print(factorial(6))
Output:

4.0
720
**************
Import all Names
The * symbol used with the import statement is used to import all the names
from a module to a current namespace.
Syntax:
from module_name import *
# importing sqrt() and factorial from the module math
from math import *

# if we simply do "import math", then


# [Link](16) and [Link]()
# are required.
print(sqrt(16))
print(factorial(6))
Output
4.0
720
**********************************************
Page No:- 79
Python DateTime module
Python Datetime module supplies classes to work with date and time. These
classes provide several functions to deal with dates, times, and time intervals.
Date and DateTime are an object in Python, so when you manipulate them,
you are manipulating objects and not strings or timestamps.
The DateTime module is categorized into 6 main classes –
 date – An idealized naive date, assuming the current Gregorian calendar
always was, and always will be, in effect. Its attributes are year, month,
and day. you can refer to – Python DateTime – Date Class
 time – An idealized time, independent of any particular day, assuming
that every day has exactly 24*60*60 seconds. Its attributes are hour,
minute, second, microsecond, and tzinfo. You can refer to – Python
DateTime – Time Class
 date-time – It is a combination of date and time along with the attributes
year, month, day, hour, minute, second, microsecond, and tzinfo. You
can refer to – Python DateTime – DateTime Class
 timedelta – A duration expressing the difference between two date, time,
or datetime instances to microsecond resolution. You can refer to –
Python DateTime – Timedelta Class
 tzinfo – It provides time zone information objects. You can refer to –
Python – [Link]()
 timezone – A class that implements the tzinfo abstract base class as a
fixed offset from the UTC (New in version 3.2). You can refer to –
Handling timezone in Python
Python Date Class
The date class is used to instantiate date objects in Python. When an object of
this class is instantiated, it represents a date in the format YYYY-MM-DD. The
constructor of this class needs three mandatory arguments year, month, and
date.
Python Date class Syntax
class [Link](year, month, day)
Date object representing data in Python
from datetime import date
my_date = date(1996, 12, 11)

print("Date passed as argument is", my_date)

Page No:- 80
Output:
Date passed as argument is 1996-12-11
******************
Get the Current Date
To return the current local date today() function of the date class is used.
today() function comes with several attributes (year, month, and day). These
can be printed individually.
today = [Link]()

print("Today's date is", today)


Output
Today's date is 2021-08-19
************************
Get Today’s Year, Month, and Date
We can get the year, month, and date attributes from the date object using the
year, month and date attribute of the date class.

from datetime import date


# date object of today's date
today = [Link]()

print("Current year:", [Link])


print("Current month:", [Link])
print("Current day:", [Link])

Output
Current year: 2021
Current month: 8
Current day: 19
*************************

Page No:- 81
Get Date from Timestamp
We can create date objects from timestamps y=using the fromtimestamp()
method. The timestamp is the number of seconds from 1st January 1970 at
UTC to a particular date.
from datetime import datetime
# Getting Datetime from timestamp
date_time = [Link](1887639468)
print("Datetime from timestamp:", date_time)
Output
Datetime from timestamp: 2029-10-25 16:17:48

*******************
Convert Date to String
We can convert date object to a string representation using two functions
isoformat() and strftime().
from datetime import date
# calling the today function of date class
today = [Link]()
# Converting the date to the string
Str = [Link](today)
print("String Representation", Str)
print(type(Str))

Output
String Representation 2021-08-19
<class 'str'>
List of Date Class Methods

Function Name Description

ctime() Return a string representing the date

fromisocalendar() Returns a date corresponding to the ISO calendar

Page No:- 82
Function Name Description

Returns a date object from the string representation of


fromisoformat()
the date

Returns a date object from the proleptic Gregorian


fromordinal()
ordinal, where January 1 of year 1 has ordinal 1

fromtimestamp() Returns a date object from the POSIX timestamp

isocalendar() Returns a tuple year, week, and weekday

isoformat() Returns the string representation of the date

Returns the day of the week as an integer where


isoweekday()
Monday is 1 and Sunday is 7

Changes the value of the date object with the given


replace()
parameter

Returns a string representation of the date with the


strftime()
given format

timetuple() Returns an object of type time.struct_time

today() Returns the current local date

Return the proleptic Gregorian ordinal of the date,


toordinal()
where January 1 of year 1 has ordinal 1

Returns the day of the week as integer where Monday is


weekday()
0 and Sunday is 6

List of Time class Methods

Function Name Description

dst() Returns [Link]() is tzinfo is not None

Returns a time object from the string representation of


fromisoformat()
the time

isoformat() Returns the string representation of time from the time

Page No:- 83
Function Name Description

object

Changes the value of the time object with the given


replace()
parameter

Returns a string representation of the time with the given


strftime()
format

tzname() Returns [Link]() is tzinfo is not None

utcoffset() Returns [Link]() is tzinfo is not None

List of Datetime Class Methods

Function Name Description

Returns the DateTime object containing timezone


astimezone()
information.

Combines the date and time objects and return a


combine()
DateTime object

ctime() Returns a string representation of date and time

date() Return the Date class object

Returns a datetime object from the string


fromisoformat()
representation of the date and time

Returns a date object from the proleptic Gregorian


fromordinal() ordinal, where January 1 of year 1 has ordinal 1. The
hour, minute, second, and microsecond are 0

fromtimestamp() Return date and time from POSIX timestamp

isocalendar() Returns a tuple year, week, and weekday

isoformat() Return the string representation of date and time

Returns the day of the week as integer where Monday


isoweekday()
is 1 and Sunday is 7

Page No:- 84
Function Name Description

now() Returns current local date and time with tz parameter

replace() Changes the specific attributes of the DateTime object

Returns a string representation of the DateTime


strftime()
object with the given format

Returns a DateTime object corresponding to the date


strptime()
string

time() Return the Time class object

timetuple() Returns an object of type time.struct_time

timetz() Return the Time class object

today() Return local DateTime with tzinfo as None

Return the proleptic Gregorian ordinal of the date,


toordinal()
where January 1 of year 1 has ordinal 1

tzname() Returns the name of the timezone

utcfromtimestamp() Return UTC from POSIX timestamp

utcoffset() Returns the UTC offset

utcnow() Return current UTC date and time

Returns the day of the week as integer where Monday


weekday()
is 0 and Sunday is 6

*********************************************
Python Math Module
Math Module consists of mathematical functions and constants. It is a built-in
module made for mathematical tasks.
The math module provides the math functions to deal with basic operations
such as addition(+), subtraction(-), multiplication(*), division(/), and
advanced operations like trigonometric, logarithmic, and exponential functions.

Page No:- 85
Math Module is an in-built Python library made to simplify mathematical tasks
in Python.
It consists of various mathematical constants and functions that can be used
after importing the math module.
List of Mathematical function in Math Module
Here is the list of all mathematical functions in math module, you can use
them when you need it in program:

Function
Name Description

Returns the smallest integral value greater than the number

import math

x = 33.7

ceil(x) # returning the ceil of 33.7


print ("The ceil of 33.7 is : ", end ="")
print ([Link](x))

Output:
The ceil of 33.7 is : 34

Returns the number with the value of ‘x’ but with the sign of ‘y’

import math

def func():
a=5
b = -7

copysign(x
, y) # implementation of copysign
c = [Link](a, b)

return c

print (func())

Output :
-5.0

Page No:- 86
Function
Name Description

Returns the absolute value of the number

import math

x = -33.7
fabs(x)
# returning the fabs of 33.7
print ("The fabs of 33.7 is : ", end ="")
print ([Link](x))

Output:
The fabs of 33.7 is : 33.7

Returns the factorial of the number

import math

x=5
factorial(x
) # returning the factorial
print ("The factorial of 5 is : ", end ="")
print ([Link](x))

Output:
The factorial of 5 is : 120

Returns the greatest integral value smaller than the number


floor(x)

gcd(x, y) Compute the greatest common divisor of 2 numbers

fmod(x, y) Returns the remainder when x is divided by y

frexp(x) Returns the mantissa and exponent of x as the pair (m, e)

fsum(itera Returns the precise floating-point value of sum of elements in an


ble) iterable

isfinite(x) Check whether the value is neither infinity not Nan

Page No:- 87
Function
Name Description

isinf(x) Check whether the value is infinity or not

isnan(x) Returns true if the number is “nan” else returns false

ldexp(x, i) Returns x * (2**i)

modf(x) Returns the fractional and integer parts of x

trunc(x) Returns the truncated integer value of x

exp(x) Returns the value of e raised to the power x(e**x)

expm1(x) Returns the value of e raised to the power a (x-1)

log(x[, b]) Returns the logarithmic value of a with base b

log1p(x) Returns the natural logarithmic value of 1+x

log2(x) Computes value of log a with base 2

log10(x) Computes value of log a with base 10

pow(x, y) Compute value of x raised to the power y (x**y)

sqrt(x) Returns the square root of the number

acos(x) Returns the arc cosine of value passed as argument

asin(x) Returns the arc sine of value passed as argument

Page No:- 88
Function
Name Description

atan(x) Returns the arc tangent of value passed as argument

atan2(y,
Returns atan(y / x)
x)

cos(x) Returns the cosine of value passed as argument

hypot(x,
Returns the hypotenuse of the values passed in arguments
y)

sin(x) Returns the sine of value passed as argument

tan(x) Returns the tangent of the value passed as argument

degrees(x
Convert argument value from radians to degrees
)

radians(x) Convert argument value from degrees to radians

Returns the inverse hyperbolic cosine of value passed as


acosh(x)
argument

asinh(x) Returns the inverse hyperbolic sine of value passed as argument

Returns the inverse hyperbolic tangent of value passed as


atanh(x)
argument

cosh(x) Returns the hyperbolic cosine of value passed as argument

sinh(x) Returns the hyperbolic sine of value passed as argument

tanh(x) Returns the hyperbolic tangent of value passed as argument

Page No:- 89
Function
Name Description

erf(x) Returns the error function at x

erfc(x) Returns the complementary error function at x

gamma(x) Return the gamma function of the argument

lgamma(x Return the natural log of the absolute value of the gamma
) function

Python Package?
Python Packages are a way to organize and structure your Python code into
reusable components. Think of it like a folder that contains related Python files
(modules) that work together to provide certain functionality. Packages help
keep your code organized, make it easier to manage and maintain, and allow
you to share your code with others. They’re like a toolbox where you can store
and organize your tools (functions and classes) for easy access and reuse in
different projects.

How to Create Package in Python?


Creating packages in Python allows you to organize your code into reusable
and manageable modules. Here’s a brief overview of how to create packages:
 Create a Directory: Start by creating a directory (folder) for your
package. This directory will serve as the root of your package structure.
 Add Modules: Within the package directory, you can add Python files
(modules) containing your code. Each module should represent a distinct
functionality or component of your package.
 Init File: Include an init .py file in the package directory. This file can
be empty or can contain an initialization code for your package. It
signals to Python that the directory should be treated as a package.
 Subpackages: You can create sub-packages within your package by
adding additional directories containing modules, along with their own
init .py files.

Page No:- 90
 Importing: To use modules from your package, import them into your
Python scripts using dot notation. For example, if you have a module
named [Link] inside a package named mypackage, you would
import its function like this: from mypackage.module1 import greet.
 Distribution: If you want to distribute your package for others to use,
you can create a [Link] file using Python’s setuptools library. This file
defines metadata about your package and specifies how it should be
installed.
Code Example
Here’s a basic code sample demonstrating how to create a simple Python
package:
1. Create a directory named mypackage.
2. Inside mypackage, create two Python files: [Link] and [Link].
3. Create an init .py file inside mypackage (it can be empty).
4. Add some code to the modules.
5. Finally, demonstrate how to import and use the modules from the
package.
mypackage/

├── init .py
├── [Link]
└── [Link]
Example:
# [Link]
def greet(name):
print(f"Hello, {name}!")
output:
Hello, Alice!
The result of addition is: 8
********************************
Python Exception Handling
An exception is a type of error that occurs when a syntactically correct Python
code raises an error.
Even if a statement or expression is syntactically correct, it may cause an error
when an attempt is made to execute it. Errors detected during execution are
called exceptions and are not unconditionally fatal.
Page No:- 91
Python Built-in Exceptions.
Python has a number of built-in exceptions, such as the well-known errors
SyntaxError, NameError, and TypeError. These Python Exceptions are thrown
by standard library routines or by the interpreter itself. They are built-in,
which implies they are present in the source code at all times.

Exception Name Description

BaseException The base class for all built-in exceptions.

Exception The base class for all non-exit exceptions.

Base class for all errors related to arithmetic


ArithmeticError operations.

Raised when a division or modulo operation is


ZeroDivisionError performed with zero as the divisor.

Raised when a numerical operation exceeds the


OverflowError maximum limit of a data type.

FloatingPointError Raised when a floating-point operation fails.

AssertionError Raised when an assert statement fails.

Raised when an attribute reference or


AttributeError assignment fails.

Raised when a sequence subscript is out of


IndexError range.

KeyError Raised when a dictionary key is not found.

Page No:- 92
Exception Name Description

MemoryError Raised when an operation runs out of memory.

Raised when a local or global name is not


NameError found.

Raised when a system-related operation (like


OSError file I/O) fails.

Raised when an operation or function is applied


TypeError to an object of inappropriate type.

Raised when a function receives an argument


ValueError of the right type but inappropriate value.

ImportError Raised when an import statement has issues.

ModuleNotFoundError Raised when a module cannot be found.

Raised when an I/O operation (like reading or


IOError writing to a file) fails.

Raised when a file or directory is requested but


FileNotFoundError cannot be found.

Raised when the next() function is called and


StopIteration there are no more items in an iterator.

Raised when the user presses Ctrl+C or


KeyboardInterrupt interrupts the program’s execution.

Raised when the [Link]() function is called to


SystemExit exit the program.

Raised when an abstract method that needs to


NotImplementedError be implemented is called.

Raised when a general error occurs in the


RuntimeError program.

Raised when the maximum recursion depth is


RecursionError exceeded.

Page No:- 93
Exception Name Description

Raised when there is an error in the syntax of


SyntaxError the code.

Raised when there is an indentation error in the


IndentationError code.

Raised when the indentation consists of


TabError inconsistent use of tabs and spaces.

Raised when a Unicode-related encoding or


UnicodeError decoding error occurs.

User-defined Exceptions
a user-defined exception is a custom error message that handles specific
errors in your code.
User-defined exceptions are custom error types that you create to handle
errors that are unique to your program. They allow you to define your own
error conditions and behaviors.

Some of the standard exceptions which are most frequent include


IndexError,
ImportError,
IOError,
ZeroDivisionError,
TypeError, and FileNotFoundError.

Advantages of Exception Handling:


 Improved program reliability: By handling exceptions properly, you can
prevent your program from crashing or producing incorrect results due to
unexpected errors or input.
 Simplified error handling: Exception handling allows you to separate
error handling code from the main program logic, making it easier to
read and maintain your code.
 Cleaner code: With exception handling, you can avoid using complex
conditional statements to check for errors, leading to cleaner and more
readable code.

Page No:- 94
 Easier debugging: When an exception is raised, the Python interpreter
prints a traceback that shows the exact location where the exception
occurred, making it easier to debug your code.
Disadvantages of Exception Handling:
 Performance overhead: Exception handling can be slower than using
conditional statements to check for errors, as the interpreter has to
perform additional work to catch and handle the exception.
 Increased code complexity: Exception handling can make your code
more complex, especially if you have to handle multiple types of
exceptions or implement complex error handling logic.
 Possible security risks: Improperly handled exceptions can potentially
reveal sensitive information or create security vulnerabilities in your
code, so it’s important to handle exceptions carefully and avoid exposing
too much information about your program.

 try Block: try block lets us test a block of code for errors. Python will
“try” to execute the code in this block. If an exception occurs, execution
will immediately jump to the except block.

 except Block: except block enables us to handle the error or exception. If


the code inside the try block throws an error, Python jumps to the except
block and executes it. We can handle specific exceptions or use a general
except to catch all exceptions.

 else Block: else block is optional and if included, must follow all except
blocks. The else block runs only if no exceptions are raised in the try
block. This is useful for code that should execute if the try block succeeds.

 finally Block: finally block always runs, regardless of whether an


exception occurred or not. It is typically used for cleanup operations
(closing files, releasing resources).

- Page No:- 95
Example
try:
numerator = 10
denominator = 0
result = numerator/denominator
print(result)
except:
print("Error: Denominator cannot be 0.")
# Output: Error: Denominator cannot be 0.
*****************
Example
try:
even_numbers = [2,4,6,8]
print(even_numbers[5])
except ZeroDivisionError:
print("Denominator cannot be 0.")
except IndexError:
print("Index Out of Bound.")
# Output: Index Out of Bound
***********************************************
UNIT-III

Python Lists

Python Lists are just like dynamically sized arrays, declared in other
languages (vector in C++ and Array List in Java). In simple language, a list
is a collection of things, enclosed in [ ] and separated by commas.

In Python, a list is a built-in dynamic sized array (automatically grows and


shrinks). We can store all types of items (including another list) in a list. A
list may contain mixed type of items, this is possible because a list mainly
stores references at contiguous locations and actual items maybe stored at
different locations.

- Page No:- 96
 List can contain duplicate items.
 List in Python are Mutable. Hence, we can modify, replace or delete the
items.
 List are ordered. It maintain the order of elements based on how they are
added.
 Accessing items in List can be done directly using their position (index),
starting from 0.

var=["mynu","sana","pooja"]
print(Var)

Output:

"mynu","sana","pooja"

Lists are the simplest containers that are an integral part of the Python
language. Lists need not be homogeneous always which makes it the most
powerful tool in Python. A single list may contain Data Types like Integers,
Strings, as well as Objects. Lists are mutable, and hence, they can be altered
even after their creation.
**********
Creating a List in Python

Lists in Python can be created by just placing the sequence inside the square
brackets[]. Unlike Sets, a list doesn’t need a built-in function for its creation
of a list.

# Creating a List
List=[]
print("Blank List: ")
print(List)

# Creating a List of numbers


List=[10,20,14]
print("\nList of numbers: ")
print(List)

# Creating a List of strings and accessing using index


List=["Geeks","For","Geeks"]
print("\nList Items: ")
print(List[0])
print(List[2])

Output
Blank List:
[]

- Page No:- 97
List of numbers:
[10, 20, 14]

List Items:
Geeks
Geeks
************
Accessing elements from the List

In order to access the list items refer to the index number. Use the index
operator [ ] to access an item in a list. The index must be an integer. Nested
lists are accessed using nested indexing.

# Creating a List with


# the use of multiple values
List=["Geeks","For","Geeks"]

# accessing a element from the


# list using index number
print("Accessing a element from the list")
print(List[0])
print(List[2])

Output

Accessing a element from the list


Geeks
Geeks
**************************
Taking Input of a Python List

We can take the input of a list of elements as string, integer, float, etc. But the
default one is a string.

Example 1:

Python
# input the list as string
string=input("Enter elements (Space-Separated): ")

# split the strings and store it to a list


lst=[Link]()
print('The list is:',lst)# printing the list
Output:
Enter elements: GEEKS FOR GEEKS
The list is: ['GEEKS', 'FOR', 'GEEKS']

**************************

- Page No:- 98
Python List Operations Types

There are many different types of operations that you can perform on Python
lists, including:

1. append()

The append() method adds elements at the end of the list. This method can
only add a single element at a time. You can use the append() method inside a
loop to add multiple elements.

Code:
myList =[1,2,3,'EduCBA','makes learning fun!']
[Link](4)
[Link](5)
[Link](6)
for i inrange(7,9):
[Link](i)
print(myList)

Output:

[1,2,3 ‘EduCBA’,’ makes learning fun!’,4,5,6,7,8


**********************

2. extend()

The extend() method adds more than one element at the end of the list.
Although it can add more than one element, unlike append(), it adds them at
the end of the list like append().

Code:
myList =[1,2,3,'EduCBA','makes learning fun!']
[Link]([4,5,6])
for i inrange(7,11):
[Link](i)
print(myList)

Output:

**********************

- Page No:- 99
3. insert()

The insert() method can add an element at a given position in the list. Thus,
unlike append(), it can add elements at any position, but like append(), it can
add only one element at a time. This method takes two arguments. The first
argument specifies the position, and the second argument specifies the
element to be inserted.

Code:
myList =[1,2,3,'EduCBA','makes learning fun!']
[Link](3,4)
[Link](4,5)
[Link](5,6)
print(myList)
Output:

**********************
4. remove()

The remove() method removes an element from the list. Only the first
occurrence of the same element is removed in the case of multiple
occurrences.
Code:
myList =[1,2,3,'EduCBA','makes learning fun!']
[Link]('makes learning fun!')
print(myList)
Output:

**********************
5. pop()

The method pop() can remove an element from any position in the list. The
parameter supplied to this method is the element index to be removed.

Code:
myList =[1,2,3,'EduCBA','makes learning fun!']
[Link](3)
print(myList)
Output:

**********************

- Page No:- 100


6. slice

The slice operation is used to print a section of the list. The slice operation
returns a specific range of elements. It does not modify the original list.

Code:
myList =[1,2,3,'EduCBA','makes learning fun!']
print(myList[:4])# prints from beginning to end index
print(myList[2:])# prints from start index to end of list
print(myList[2:4])# prints from start index to end index
print(myList[:])# prints from beginning to end of list
Output:

**********************
7. reverse()

You can use the reverse() operation to reverse the elements of a list. This
method modifies the original list. We use the slice operation with negative
indices to reverse a list without modifying the original. Specifying negative
indices iterates the list from the rear end to the front end of the list.

Code:
myList =[1,2,3,'EduCBA','makes learning fun!']
print(myList[::-1])# does not modify the original list
[Link]()# modifies the original list
print(myList)

Output:

**********************
8. len()

The len() method returns the length of the list, i.e., the number of elements in
the list.

Code:
myList =[1,2,3,'EduCBA','makes learning fun!']
print(len(myList))

Output: 5
**********************
- Page No:- 101
9. min() & max()

The min() method returns the minimum value in the list. The max() method
returns the maximum value in the list. Both methods accept only
homogeneous lists, i.e., lists with similar elements.

Code:
myList =[1,2,3,4,5,6,7]
print(min(myList))
print(max(myList))

Output:
1
7
**********************

10. count()

The function count() returns the number of occurrences of a given element in


the list.
Code:
myList =[1,2,3,4,3,7,3,8,3]
print([Link](3))
Output: 4

**********************

11. concatenate

The concatenate operation merges two lists and returns a single list. The
concatenation is performed using the + sign. It’s important to note that the
individual lists are not modified, and a new combined list is returned.

Code:
myList =[1,2,3,'EduCBA','makes learning fun!']
yourList =[4,5,'Python','is fun!']
print(myList+yourList)

Output:

**********************

- Page No:- 102


12. multiply

Python also allows multiplying the list n times. The resultant list is the original
list iterated n times.
Code:
myList =['EduCBA','makes learning fun!']
print(myList*2)
Output:

**********************

13. index()

The index() method returns the position of the first occurrence of the given
element. It takes two optional parameters – the beginning index and the end
index. These parameters define the start and end position of the search area
on the list. When you supply the begin and end indices, the element is
searched only within the sub-list specified by those indices. When not supplied,
the element is searched in the whole list.

Code:
myList =[1,2,3,'EduCBA','makes learning fun!']
print([Link]('EduCBA'))# searches in the whole list
print([Link]('EduCBA',0,2))# searches from 0th to 2nd position

Output:

**********************

14. sort()

The sort method sorts the list in ascending order. You can only perform this
operation on homogeneous lists, which means lists with similar elements.

yourList =[4,2,6,5,0,1]
[Link]()
print(yourList)
Output:

**********************

- Page No:- 103


15. clear()

This function erases all the elements from the list and empties them.
Code:
myList =[1,2,3,'EduCBA','makes learning fun!']
[Link]()

Output:
Here the output is empty because it clears all the data.
**********************

16. copy()

The copy method returns the shallow copy list. Now the created list points to a
different memory location than the original one. Hence any changes made to
the list don’t affect another one.

Syntax:

[Link]()
Code:
even_numbers =[2,4,6,8]
value = even_numbers.copy()
print('Copied List:', value)

Output:

**********************
TRAVERSING A LIST MEANING in python

Traversing a list in Python means accessing each element of the list one by
one. This can be done using a loop, such as a for loop, to iterate through each
element of the list.

Methods of Traversing Lists


Here are the methods which one can refer to for traversing lists in Python:

 Python range () method

Using For Loop and Range ()


If you wish to use the traditional for loop which iterates from number x to
number y.

# Python3 code to iterate over a list

- Page No:- 104


list = [2, 4, 6, 8, 10]

# getting length of list

length = len(list)

# Iterating the index same as 'for i in range(len(list))'

for i in range(length):

print(list[i])

Output:

10
******************************

 List Comprehension

This one is possibly the most concrete way.

# Python3 code to iterate over a list

list = [2, 4, 6, 8, 10]

# Using list comprehension

[print(i) for i in list]

OUTPUT

10
**************************

- Page No:- 105


 Python enumerate () method

If you wish to convert the list into an iterable list of tuples (or get
the index on the basis of a condition check, for instance, in linear
search, one might want to save the index of minimum element),
one can use the enumerate () function.

# Python3 code to iterate over a list

list = [1, 3, 5, 7, 9]

# Using enumerate()

for i, val in enumerate(list):

print (i, ",",val)

OUTPUT

0,1

1,3

2,5

3,7

4,9
***************
 Lambda function
Lambda functions in Python are essentially anonymous functions.
Syntax:
Lambda parameters: expression

 expression: The iterable which is to be evaluated.

The lambda function along with a Python map() function can come in use for
traversing lists easily.

Python map () method accepts a function as a parameter and returns a list.


The input function to the map () method gets called with every element of the
iterable and it returns a new list with all the elements returned from the
function, individually.

- Page No:- 106


Example:
lst = [20, 40, 85, 93, 99, 85, 31]
res = list(map(lambda x:x, lst))

print(res)

In the snippet of code mentioned above, you see how the lambda x:x
function is given as input to the map() function. Thus, the lambda x:x accepts
every element of the iterable and returns it.
The input_list (lst) is given as the second argument to the map() function.
Thus, the map() function will pass every element of lst to the lambda x:x
function and return the elements.

Output:
[20, 40, 85, 93, 99, 85, 31]
********************************

 Python NumPy module


For every large n-dimensional list (for instance an image array),
sometimes, it is better to make use of an external library like numpy.

# Python program for # iterating over array

import numpy as toppr

# creating an array using arrange method

a = [Link](9)

# shape array with 3 rows

# and 4 columns

a = [Link](3, 3)

# iterating an array

for x in [Link](a):

print(x)

OUTPUT

- Page No:- 107


3

8
***************************

 By using a for Loop

 By using a while Loop

# Python3 code to iterate over a list

list = [2, 4, 6, 8, 10]

# Getting length of list

length = len(list)

i=0

# Iterating using while loop

while i < length:

print(list[i])

i += 1
OUTPUT

10

*********************************

- Page No:- 108


Python List methods

Python list methods are built-in functions that allow us to perform various
operations on lists, such as adding, removing, or modifying elements. In
this article, we’ll explore all Python list methods with a simple example.

List Methods

Let’s look at different list methods in Python:


 append(): Adds an element to the end of the list.

 copy(): Returns a shallow copy of the list.


 clear(): Removes all elements from the list.
 count(): Returns the number of times a specified element appears in the
list.
 extend(): Adds elements from another list to the end of the current list.
 index(): Returns the index of the first occurrence of a specified element.
 insert(): Inserts an element at a specified position.
 pop(): Removes and returns the element at the specified position (or the
last element if no index is specified).
 remove(): Removes the first occurrence of a specified element.
 reverse(): Reverses the order of the elements in the list.
 sort(): Sorts the list in ascending order (by default).

append():

Syntax: list_name.append(element)
a = [1, 2, 3]

# Add 4 to the end of the list


[Link](4)
print(a)

Output
[1, 2, 3, 4]
****************

- Page No:- 109


copy():

Syntax: list_name.copy()
a = [1, 2, 3]

# Create a copy of the list


b = [Link]()
print(b)

Output
[1, 2, 3]
***************

clear():

Syntax: list_name.clear()
a = [1, 2, 3]

# Remove all elements from the list


[Link]()
print(a)

Output
[]
******************
Count():
Syntax: list_name.count(element)

a = [1, 2, 3, 2]

# Count occurrences of 2 in the list


print([Link](2))
Output
2
********************
extend():
Syntax: list_name.extend(iterable)
a = [1, 2]

# Extend list a by adding elements from list [3, 4]


[Link]([3, 4])
print(a)

Output
[1, 2, 3, 4]
*****************

- Page No:- 110


index():
Syntax: list_name.index(element)
a = [1, 2, 3]

# Find the index of 2 in the list


print([Link](2))
Output
1
***************************
insert():
Syntax: list_name.insert(index, element)
a = [1, 3]
# Insert 2 at index 1
[Link](1, 2)
print(a)

Output
[1, 2, 3]
*************************

pop():
Syntax: list_name.pop(index)
a = [1, 2, 3]

# Remove and return the last element in the list


[Link]()
print(a)
Output
[1, 2]
**********************
remove():
Syntax: list_name.remove(element)
a = [1, 2, 3]

# Remove the first occurrence of 2


[Link](2)
print(a)
Output
[1, 3]
*******************
reverse():
Syntax: list_name.reverse()
a = [1, 2, 3]

# Reverse the list order


[Link]()
print(a)
Output
[3, 2, 1]
*****************

- Page No:- 111


sort():
Syntax: list_name.sort(key=None, reverse=False)
a = [3, 1, 2]

# Sort the list in ascending order


[Link]()
print(a)
Output
[1, 2, 3]
******************
Python Built-in Functions List

Here is a comprehensive list of Python built-in functions:

Function
Name Description

Return the absolute value of a number


Python # An integer
abs() var = -94
Function print('Absolute value of integer is:', abs(var))
output: Absolute value of integer is: 94

Return true if all the elements of a given iterable( List, Dictionary,


Python
Tuple, set, etc) are True else it returns False
all()
print(all([True, True, False]))
Function
output: False

Returns true if any of the elements of a given iterable( List,


Dictionary, Tuple, set, etc) are True else it returns False
Python
# a List of boolean values
any()
l =[False, False, True, False, False]
Function
print(any(l))
output: True

Python
used for getting the next item from an asynchronous iterator
anext()
Function

Returns a string containing a printable representation of an


Python
object
ascii()
print(ascii("¥"))
Function
output: '\xa5'

Python Convert integer to a binary string

Page No:- 112


Function
Name Description

bin() x =bin(42)
Function print(x)
output: 0b101010

Return or convert a value to a Boolean value i.e., True or False


x =bool(1)
Python print(x)
bool() y =bool()
Function print(y)
output: True
False

Python
breakpoin It is used for dropping into the debugger at the call site during
t() runtime for debugging purposes
Function

Returns a byte array object which is an array of given bytes


str="Geeksforgeeks"

# encoding the string with unicode 8 and 16


Python array1 =bytearray(str, 'utf-8')
bytearray array2 =bytearray(str, 'utf-16')
()
Function print(array1)
print(array2)
output: bytearray(b'Geeksforgeeks')
bytearray(b'\xff\xfeG\x00e\x00e\x00k\x00s\x00f\x00o\x00r\x00
g\x00e\x00e\x00k\x00s\x00')

Converts an object to an immutable byte-represented object of a


given size and data
# python code demonstrating
Python # int to bytes
bytes() str="Welcome to Geeksforgeeks"
Function arr =bytes(str, 'utf-8')
print(arr)

output: b'Welcome to Geeksforgeeks'

Returns True if the object passed appears to be callable


Python
# Python program to illustrate
callable()
# callable() a test function
Function
defGeek():

Page No:- 113


Function
Name Description

return5

# an object is created of Geek()


let =Geek
print(callable(let))

# a test variable
num =5*5
print(callable(num))

Output
True
False

Returns a string representing a character whose Unicode code


point is an integer
Python
num =97
chr()
print("ASCII Value of 97 is: ", chr(num))
Function
Output
ASCII Value of 97 is: a

Returns a class method for a given function


class Geeks:
course = 'DSA'
list_of_instances = []

def init (self, name):


[Link] = name
Geeks.list_of_instances.append(self)

@classmethod
Python def get_course(cls):
classmeth return f"Course: {[Link]}"
od()
Function @classmethod
def get_instance_count(cls):
return f"Number of instances: {len(cls.list_of_instances)}"

@staticmethod
def welcome_message():
return "Welcome to Geeks for Geeks!"

# Creating instances
g1 = Geeks('Alice')
g2 = Geeks('Bob')

Page No:- 114


Function
Name Description

# Calling class methods


print(Geeks.get_course())
print(Geeks.get_instance_count())

# Calling static method


print(Geeks.welcome_message())
Output
Course: DSA
Number of instances: 2
Welcome to Geeks for Geeks!

Returns a Python code object


Python srcCode ='x = 10\ny = 20\nmul = x * y\nprint("mul =", mul)'
compile() execCode =compile(srcCode, 'mulstring', 'exec')
Function exec(execCode)
output: mul = 200

Python
Creates Complex Number
complex(
print(complex(1, 2))
)
Output:(1+2j)
Function

Delete the named attribute from the object

classEquation:
x =3
y =-8
z =5

l1 =Equation()

print("Value of x = ", l1.x)


print("Value of y = ", l1.y)
Python
print("Value of z = ", l1.z)
delattr()
Function
delattr(Equation,'z')
print("Value of x = ", l1.x)
print("Value of y = ", l1.z)

Output
Value of x = 3
Value of y = -8
Value of z = 5
Value of x = 3
ERROR!
Traceback (most recent call last):

Page No:- 115


Function
Name Description

File "<string>", line 14, in <module>


AttributeError: 'Equation' object has no attribute 'z'

Creates a Python Dictionary


Python
dict(One = "1", Two = "2")
dict()
Output:
Function
{'One': '1', 'Two': '2'}

Python
dir() Returns a list of the attributes and methods of any object
Function

Takes two numbers and returns a pair of numbers consisting of


their quotient and remainder
Python
Input : x = 9, y = 3
divmod()
Output :(3, 0)
Function
Input : x = 8, y = 3
Output :(2, 2)

Adds a counter to an iterable and returns it in a form of


enumerating object
l1 = ["eat", "sleep", "repeat"]
s1 = "geek"

# creating enumerate objects


obj1 = enumerate(l1)
Python obj2 = enumerate(s1)
enumerat
e() print ("Return type:", type(obj1))
Function print (list(enumerate(l1)))

# changing start index to 2 from 0


print (list(enumerate(s1, 2)))
Output:
Return type: <class 'enumerate'>
[(0, 'eat'), (1, 'sleep'), (2, 'repeat')]
[(2, 'g'), (3, 'e'), (4, 'e'), (5, 'k')]

Parses the expression passed to it and runs Python


expression(code) within the program
Python print(eval('1+2'))
eval() print(eval("sum([1, 2, 3, 4])"))
Function Output
3
10

Page No:- 116


Function
Name Description

Used for the dynamic execution of the program


Python
prog ='print("The sum of 5 and 10 is", (5+10))'
exec()
exec(prog)
Function
Output: The sum of 5 and 10 is 15

Filters the given sequence with the help of a function that tests
each element in the sequence to be true or not
# Function to check if a number is even
def even(n):
return n % 2 == 0
Python
filter()
a = [1, 2, 3, 4, 5, 6]
Function
b = filter(even, a)

# Convert filter object to a list


print(list(b))
Output : [2, 4, 6]

Return a floating-point number from a number or a string


Python # convert integer value to float
float() num =float(10)
Function print(num)
Output:10.0

Formats a specified value


name = "Ram"
age = 22
message = "My name is {0} and I am {1} years \
Python
old. {1} is my favorite \
format()
number.".format(name, age)
Function
print(message)
Output
My name is Ram and I am 22 years old. 22 is my favorite
number.

Python
frozenset
Returns immutable frozenset
()
Function

Access the attribute value of an object


Python
class Calculator:
getattr()
def add(self, a, b):
Function
return a + b

Page No:- 117


Function
Name Description

calc = Calculator()

# Accessing a method dynamically


operation = getattr(calc, "add")
result = operation(3, 5)
print(result)
Output :8

Returns the dictionary of the current global symbol table


Python3 program to demonstrate global() function
# global variable
a =5

deffunc():
c =10
Python d =c +a
globals()
Function # Calling globals()
globals()['a'] =d
print(a)

# Driver Code
func()

Output: 15

Check if an object has the given named attribute and return true
if present

# declaring class
classGfG:
name ="GeeksforGeeks"
age =24

Python
# initializing object
hasattr()
obj =GfG()
Function
# using hasattr() to check name
print("Does name exist ? "+str(hasattr(obj, 'name')))

# using hasattr() to check motto


print("Does motto exist ? "+str(hasattr(obj, 'motto')))

Output:
Does name exist ? True

Page No:- 118


Function
Name Description

Does motto exist ? False

Encode the data into an unrecognizable value


# initializing objects
int_val = 4
str_val = 'GeeksforGeeks'
flt_val = 24.56

# Printing the hash values.


Python
# Notice Integer value doesn't change
hash()
# You'll have answer later in article.
Function
print("The integer hash value is : " + str(hash(int_val)))
print("The string hash value is : " + str(hash(str_val)))
print("The float hash value is : " + str(hash(flt_val)))
Output
The integer hash value is : 4
The string hash value is : 4349415460800802357
The float hash value is : 1291272085159665688

Display the documentation of modules, functions, classes,


keywords, etc
Example: help()
Output
Welcome to Python 3.7's help utility!
Python
help()
If this is your first time using Python, you should definitely check
Function
out
the tutorial on the Internet at
[Link]

Enter the name ...

Convert an integer number into its corresponding hexadecimal


form

Python decimal_number =999


hex() hexadecimal_value =hex(decimal_number)
Function
print(hexadecimal_value)

Output: 0x3e7

Return the identity of an object


Python
id() x =42
Function y =x

Page No:- 119


Function
Name Description

z =42

print(id(x))
print(id(y)) # (same as x)
print(id(z)) # (same as x and y)

Output : 140642115230496
140642115230496
140642115230496

Take input from the user as a string

Python name =input("What is your name? ")


input() print("Hello, "+name +"!")
Function
Output : What is your name? GFG
Hello, GFG!

Converts a number in a given base to decimal


Python
age ="21"
int()
print("age =", int(age))
Function
Output:age = 21

Checks if the objects belong to a certain class or not

numbers =[1, 2, 3, 4, 2, 5]

# Check if 'numbers' is an instance of a list


Python
result =isinstance(numbers, list)
isinstance
()
ifresult:
Function
print("The variable 'numbers' is an instance of a list.")
else:
print("The variable 'numbers' is not an instance of a list.")

Output: The variable 'numbers' is an instance of a list.

Check if a class is a subclass of another class or not

print("Float is the subclass of str:", issubclass(float,str))


Python
print("Bool is the subclass of int:", issubclass(bool,int))
issubclass
print("int is the subclass of float:",issubclass(int,float))
()
importcollections
Function
print('[Link] is the subclass of dict: ',
issubclass([Link], dict))

Page No:- 120


Function
Name Description

Output: Float is the subclass of str: False


Bool is the subclass of int: True
int is the subclass of float: False
[Link] is the subclass of dict: True

Convert an iterable to an iterator


a = [10, 20, 30, 40]

# Convert the list into an iterator


Python iterator = iter(a)
iter()
Function # Access elements using next()
print(next(iterator))
print(next(iterator))
Output: 10
20

Returns the length of the object


s1 = "abcd"
print(len(s1))

s2 = ""
Python
print(len(s2))
len()
Function
s3 = "a"
print(len(s3))
Output: 4
0
1

Creates a list in Python


# initializing a string
string = "ABCDEF"
Python
# using list() function to create a list
list()
list1 = list(string)
Function
# printing list1
print(list1)
Output: ['A', 'B', 'C', 'D', 'E', 'F']

Returns the dictionary of the current local symbol table


Python # Python program to understand about locals
locals() # here no local variable is present
Function
def demo1():

Page No:- 121


Function
Name Description

print("Here no local variable is present : ", locals())

# here local variables are present


def demo2():
name = "Ankit"
print("Here local variables are present : ", locals())

# driver code
demo1()
demo2()
Output: Here no local variable is present : {}
Here local variables are present : {'name': 'Ankit'}

Returns a map object(which is an iterator) of the results after


applying the given function to each item of a given iterable
Python
s = ['1', '2', '3', '4']
map()
res = map(int, s)
Function
print(list(res))
Output: [1, 2, 3, 4]

Returns the largest item in an iterable or the largest of two or


more arguments

var1 =4
Python var2 =8
max() var3 =2
Function
max_val =max(var1, var2, var3)
print(max_val)

Output: 8

Returns memory view of an argument

byte_array =bytearray('XYZ', 'utf-8')


Python
mv =memoryview(byte_array)
memoryvi
ew()
print(mv[0])
Function
print(bytes(mv[0:1]))

Output: 88
b'X'

Python Returns the smallest item in an iterable or the smallest of two or


min() more arguments

Page No:- 122


Function
Name Description

Function numbers = [23,25,65,21,98]


print(min(numbers))
Output: 21

Receives the next item from the iterator

Python =[1, 2, 3]
next() l_iter =iter(l)
Function print(next(l_iter))

Output: 1

Returns a new object


# declaring the object of class object
obj =object()

Python # printing its type


object() print("The type of object class object is: ")
Function print(type(obj))

# printing its attributes


print("The attributes of its class are: ")
print(dir(obj))

returns an octal representation of an integer in a string format.


Python
oct() print(oct(10))
Function
Output: 0o12

Open a file and return its object

created_file =open("[Link]","x")
Python
open()
# Check the file
Function
print(open("[Link]","r").read() ==False)

Output:False

Returns the Unicode equivalence of the passed argument

print(ord('2'))
Python print(ord('g'))
ord() print(ord('&'))
Function
Output :50
103
38

Page No:- 123


Function
Name Description

Compute the power of a number


Python
pow() print(pow(3,2))
Function
Output:9

Print output to the console


name = "John"
age = 30
Python
print("Name:", name)
print()
print("Age:", age)
Function
Output
Name: John
Age: 30

Create a property of a class


# Python program to explain property() function
# Alphabet class

class Alphabet:
def init (self, value):
self._value = value

# getting the values


def getValue(self):
print('Getting value')
return self._value

Python # setting the values


property( def setValue(self, value):
) print('Setting value to ' + value)
Function self._value = value

# deleting the values


def delValue(self):
print('Deleting value')
del self._value

value = property(getValue, setValue,


delValue, )

# passing the value


x = Alphabet('GeeksforGeeks')
print([Link])

Page No:- 124


Function
Name Description

[Link] = 'GfG'

del [Link]

Output: Getting value


GeeksforGeeks
Setting value to GfG
Deleting value

Generate a sequence of numbers


Python for i in range(5):
range() print(i, end=" ")
Function print()
Output:0 1 2 3 4

Return the printable version of the object


s = 'Hello, Geeks.'
Python print (repr(s))
repr() print (repr(2.0/11.0))
Function Output :'Hello, Geeks.'
0.18181818181818182

Returns an iterator that accesses the given sequence in the


reverse order
# creating a list
Python
cars = ["nano", "swift", "bolero", "BMW"]
reversed(
# reversing the list
)
reversed_cars = list(reversed(cars))
Function
#printing the list
print(reversed_cars)
Output: ['BMW', 'bolero', 'swift', 'nano']

Rounds off to the given number of digits and returns the floating-
point number
Python
number = 111.23
round()
rounded_number = round(number)
Function
print(rounded_number)
Output :111

Python Convert any of the iterable to a sequence of iterable elements


set() with distinct elements
Function # we are creating an

Page No:- 125


Function
Name Description

#empty set by using set()

s = set()
print("Type of s is ",type(s))
Output: Type of s is <class 'set'>

Assign the object attribute its value

classPerson:
def init (self):
Python pass
setattr()
Function p =Person()
setattr(p, 'name', 'kiran')
print(f"name: {[Link]}")

Output :name: kiran

Returns a slice object

Python String ='Hello World'


slice() slice_obj =slice(5,11)
Function print(String[slice_obj])

Output: World

Returns a list with the elements in a sorted manner, without


modifying the original sequence
a = [4, 1, 3, 2]
Python
sorted()
#Using sorted function to modify list in-place
Function
b = sorted(a)
print(b)
Output: [1, 2, 3, 4]

Converts a message into the static message


class MathUtils:
@staticmethod
Python def add(a, b):
staticmet return a + b
hod()
Function result = [Link](9, 8)
print(result)
Output: 17

Page No:- 126


Function
Name Description

Returns the string version of the object


Python n = 123
str() s = str(n)
Function print(s)
Output: 123

Sums up the numbers in the list


Python
arr = [1, 5, 2]
sum()
print(sum(arr))
Function
Output: 8

Returns a temporary object of the superclass


class Emp():
def init (self, id, name, Add):
[Link] = id
[Link] = name
[Link] = Add

# Class freelancer inherits EMP


class Freelance(Emp):
def init (self, id, name, Add, Emails):
Python super(). init (id, name, Add)
super() [Link] = Emails
Function
Emp_1 = Freelance(103, "Suraj kr gupta", "Noida" ,
"KKK@gmails")
print('The ID is:', Emp_1.id)
print('The Name is:', Emp_1.name)
print('The Address is:', Emp_1.Add)
print('The Emails is:', Emp_1.Emails)
Output :The ID is: 103
The Name is: Suraj kr gupta
The Address is: Noida
The Emails is: KKK@gmails

Creates a tuple in Python


Python
l = [1,2,3]
tuple()
print(tuple(l))
Function
Output:(1, 2, 3)

Returns the type of the object


Python
x = 10
type()
print(type(x))
Function
Output: <class 'int'>

Page No:- 127


Function
Name Description

Returns the dict attribute for a module, class, instance, or


any other object

classGeeks:
def init (self, name1 ="Arun",
num2 =46, name3 ="Rishab"):
Python
self.name1 =name1
vars()
self.num2 =num2
Function
self.name3 =name3

GeeksforGeeks =Geeks()
print(vars(GeeksforGeeks))

Output: {'name1': 'Arun', 'num2': 46, 'name3': 'Rishab'}

Maps the similar index of multiple containers


names = ['John', 'Alice', 'Bob', 'Lucy']
Python scores = [85, 90, 78, 92]
zip()
Function res = zip(names, scores)
print(list(res))
Output: [('John', 85), ('Jane', 90), ('Tom', 78), ('Lucy', 92)]

Imports the module during runtime

# importing numpy module


# it is equivalent to "import numpy as np"
np = import ('numpy', globals(), locals(), [], 0)
Python
import
# array from numpy
()
a =[Link]([1, 2, 3])
Function
# prints the type
print(type(a))

Output:<class '[Link]'>

***********************************************************
Tuples in Python

Python Tuple is a collection of objects separated by commas. In some ways, a


tuple is similar to a Python list in terms of indexing, nested objects, and
repetition but the main difference between both is Python tuple is immutable,
unlike the Python list which is mutable.

Page No:- 128


# Note : In case of list, we use square brackets []. Here we use round
brackets ()
t = (10, 20, 30)

print(t)
print(type(t))
Output
(10, 20, 30)
<class 'tuple'>

****************

Creating Python Tuples


There are various ways by which you can create a tuple in Python. They are as
follows:
 Using round brackets
 With one item
 Tuple Constructor
Create Tuples using Round Brackets ()
To create a tuple we will use () operators.

var = ("Geeks", "for", "Geeks")


print(var)

Output:
('Geeks', 'for', 'Geeks')
******************

Create a Tuple With One Item

Python 3.11 provides us with another way to create a Tuple.

values : tuple[int | str, ...] = (1,2,4,"Geek")


print(values)

Output:
Here, in the above snippet we are considering a variable called values which
holds a tuple that consists of either int or str, the ‘…’ means that the tuple will
hold more than one int or str.
(1, 2, 4, 'Geek')
*****************************************

Tuple Constructor in Python

To create a tuple with a Tuple constructor, we will pass the elements as its
parameters.

Page No:- 129


 Python3

tuple_constructor = tuple(("dsa", "developement", "deep learning"))


print(tuple_constructor)

Output :
('dsa', 'developement', 'deep learning')
******************************************************
Accessing Values in Python Tuples
Tuples in Python provide two ways by which we can access the elements of a
tuple.
 Using a positive index
 Using a negative index
Python Access Tuple using a Positive Index
Using square brackets we can get the values from tuples in Python.
 Python3

var = ("Geeks", "for", "Geeks")

print("Value in Var[0] = ", var[0])


print("Value in Var[1] = ", var[1])
print("Value in Var[2] = ", var[2])

Output:
Value in Var[0] = Geeks
Value in Var[1] = for
Value in Var[2] = Geeks
*****************************

Access Tuple using Negative Index


In the above methods, we use the positive index to access the value in Python,
and here we will use the negative index within [].
 Python3

var = (1, 2, 3)

print("Value in Var[-1] = ", var[-1])


print("Value in Var[-2] = ", var[-2])
print("Value in Var[-3] = ", var[-3])

Output:
Value in Var[-1] = 3
Value in Var[-2] = 2
Value in Var[-3] = 1
*******************************************

Page No:- 130


Python Tuple Operations

Tuple Operations. In Python, the tuples can be defined as functions of


sequences that are invariable and feasible where several operations can be
done on it. These include concatenation, repetition, test for membership, and
slicing.

Tuples are immutable sequences in Python, meaning their elements cannot be


changed after creation. However, they support several operations that allow
you to work with them effectively.

Here, below are the Python tuple operations.

1. Accessing Elements:
* Indexing: You can access individual elements using their index (position),
which starts from 0.
my_tuple = (1, 2, 3, 'a', 'b')
print(my_tuple[0]) # Output: 1
print(my_tuple[2]) # Output: 3

* Slicing: You can extract a portion of a tuple using slicing.


print(my_tuple[1:3]) # Output: (2, 3)
print(my_tuple[:2]) # Output: (1, 2)
print(my_tuple[2:]) # Output: (3, 'a', 'b')

2. Concatenation:
* You can combine two or more tuples using the + operator.
tuple1 = (1, 2)
tuple2 = (3, 4)
new_tuple = tuple1 + tuple2
print(new_tuple) # Output: (1, 2, 3, 4)

3. Repetition:
* You can repeat a tuple using the * operator.
my_tuple = (1, 2)
repeated_tuple = my_tuple * 3
print(repeated_tuple) # Output: (1, 2, 1, 2, 1, 2)

4. Membership Testing:
* You can check if an element exists in a tuple using the in operator.
my_tuple = (1, 2, 3)
print(2 in my_tuple) # Output: True
print(4 in my_tuple) # Output: False

5. Length:
* You can find the number of elements in a tuple using the len() function.
my_tuple = (1, 2, 3, 'a', 'b')
print(len(my_tuple)) # Output: 5

Page No:- 131


6. Counting Elements:
* You can count the number of occurrences of a specific element using the
count() method.
my_tuple = (1, 2, 2, 3, 2)
print(my_tuple.count(2)) # Output: 3

7. Finding Index:
* You can find the index of the first occurrence of a specific element using the
index() method.
my_tuple = (1, 2, 3, 2)
print(my_tuple.index(2)) # Output: 1

8. Immutability:
* Tuples are immutable, meaning you cannot modify their elements after
creation.
my_tuple = (1, 2, 3)
my_tuple[0] = 5 # This will raise a TypeError

*******************************************************
Tuple Methods in Python

While tuples are immutable (meaning you can't change their elements after
creation), they have two built-in methods that can be very useful:
* count():
* Purpose: Returns the number of times a specified value appears in the
tuple.
* Syntax: tuple_name.count(value)
my_tuple = (1, 2, 2, 3, 2)

count_of_two = my_tuple.count(2)
print(count_of_two) # Output: 3

* index():
* Purpose: Returns the index of the first occurrence of a specified value.
* Syntax: tuple_name.index(value)
my_tuple = (1, 2, 3, 2)
index_of_two = my_tuple.index(2)
print(index_of_two) # Output: 1

Key Points:
* These methods provide valuable information about the elements within a
tuple without altering its contents.
* The index() method raises a ValueError if the specified value is not found in
the tuple.

***************************************************

Page No:- 132


Tuple Functions

There are some methods and functions which help us to perform different
tasks in a tuple. Therefore, we can call them tuple functions. Furthermore,
these tuple functions make our work easy and efficient. Besides, there are a
number of functions such as

cmp(),
len(),
max(),
min(),
tuple(),
index(),
count(),
sum(),
any(),
all(),
sorted(),
reversed().

The tuple() Function

We can use the tuple() constructor or function to create a tuple. It basically


performs two functions as follows:
 Creating an empty tuple if we give no arguments.
 Creating a tuple with elements if we pass the arguments.
For example,

>>>tup = tuple ((22, 45, 23, 78, 6.89))

>>>tup

(22, 45, 23, 78, 6.89)

>>> tup2 = tuple()

>>> tup2

()

The len() Function


This function returns the number of elements present in a tuple. Moreover, it is
necessary to provide a tuple to the len() function.
For example,

>>>tup = (22, 45, 23, 78, 6.89)


>>> len(tup)

Page No:- 133


The count() Function

This function will help us to fund the number of times an element is present in
the tuple. Furthermore, we have to mention the element whose count we need
to find, inside the count function.
For example,

Copy Code

>>>tup = (22, 45, 23, 78, 22, 22, 6.89)

>>> [Link](22)

>>> [Link](54)

**********************
The index() Function

The tuple index() method helps us to find the index or occurrence of an


element in a tuple. This function basically performs two functions:
 Giving the first occurrence of an element in the tuple.
 Raising an exception if the element mentioned is not found in the tuple.
For example,
Example 1: Finding the index of an element
Copy Code

>>> tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)

>>> print([Link](45))

>>> print([Link](890))

#prints the index of elements 45 and 890

The sorted() Function


This method takes a tuple as an input and returns a sorted list as an output.
Moreover, it does not make any changes to the original tuple.
For example,

>>> tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)

Page No:- 134


>>> sorted(tup)

[1, 2, 2.4, 3, 4, 22, 45, 56, 890]

**************
The min(), max(), and sum() Tuple Functions

min(): gives the smallest element in the tuple as an output. Hence, the name
is min().
For example,

max(): gives the largest element in the tuple as an output. Hence, the name is
max().
For example,
Copy Code

>>> tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)

>>> max(tup)

890

max(): gives the sum of the elements present in the tuple as an output.
For example,
Copy Code

>>> tup = (22, 3, 45, 4, 2, 56, 890, 1)

>>> sum(tup)

1023
********************************

Nested Tuples in Python

A nested tuple is a Python tuple that has been placed inside of another tuple.
Let's have a look at the following 8-element tuple.

1. tuple = (12, 23, 36, 20, 51, 40, (200, 240, 100))
This last element, which consists of three items enclosed in parenthesis, is
known as a nested tuple since it is contained inside another tuple. The name of
the main tuple with the index value, tuple[index], can be used to obtain the
nested tuple, and we can access each item of the nested tuple by using
tuple[index-1][index-2].

Example of a Nested Tuple

Page No:- 135


Code
# Python program to create a nested tuple

# Creating a nested tuple of one element only


employee = ((10, "Itika", 13000),)
print(employee)

# Creating a multiple-value nested tuple


employee = ((10, "Itika", 13000), (24, "Harry", 15294), (15, "Naill", 20001
), (40, "Peter", 16395))
print(employee)

Output:
((10, 'Itika', 13000),)
((10, 'Itika', 13000), (24, 'Harry', 15294), (15, 'Naill', 20001), (40, 'Peter',
16395))

***********************************************

Dictionaries in Python

A Python dictionary is a data structure that stores the value in key:


value pairs. Values in a dictionary can be of any data type and can be
duplicated, whereas keys can’t be repeated and must be immutable.

Example: Here, The data is stored in key:value pairs in dictionaries, which


makes it easier to find values.

Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}


print(Dict)

Output

{1: 'Geeks', 2: 'For', 3: 'Geeks'}


***********************************************************

How to Create a Dictionary

In Python, a dictionary can be created by placing a sequence of elements


within curly {} braces, separated by a ‘comma’. The dictionary holds pairs of
values, one being the Key and the other corresponding pair element being
its Key:value. Values in a dictionary can be of any data type and can be
duplicated, whereas keys can’t be repeated and must be immutable.

Note – Dictionary keys are case sensitive, the same name but different cases
of Key will be treated distinctly.

Page No:- 136


The code demonstrates creating dictionaries with different types of keys. The
first dictionary uses integer keys, and the second dictionary uses a mix of
string and integer keys with corresponding values. This showcases the
flexibility of Python dictionaries in handling various data types as keys.

Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}


print("\nDictionary with the use of Integer Keys: ")

print(Dict)

Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}


print("\nDictionary with the use of Mixed Keys: ")
print(Dict)

Output

Dictionary with the use of Integer Keys:


{1: 'Geeks', 2: 'For', 3: 'Geeks'}
********************************
Dictionaries are Mutable

Dictionaries themselves are mutable, so entries can be added, removed, and


changed at any time. Note, though, that because entries are accessed by their
key, we can't have two entries with the same key

Yes, dictionaries are mutable in Python, which means they can be changed
after they are created:
 Definition: A dictionary is a data structure that stores items in key-
value pairs.
 Mutability: Mutability refers to the ability to change a value in place
without creating a new storage location for the changed value.
 Changes: In a mutable dictionary, you can add, remove, or modify
key-value pairs.
 Keys: Keys are unique identifiers for items and must be
immutable. They can be either strings or numbers, but not mutable
data types like lists.
 Order: Dictionaries are unordered, meaning the items in a dictionary
are not stored in any particular order.
 Representation: Dictionaries are represented by a pair of curly
braces {} in which enclosed are the key: value pairs separated by a
comma.
 Examples: Dictionaries are similar in spirit to lists, sets, and tuples.
*************************************************************
Page No:- 137
Dictionary Operations in Python
Dictionaries in Python are unordered collections of key-value pairs. They are
mutable, meaning you can change their contents after creation. Here are some
common operations you can perform on dictionaries:
1. Creating a Dictionary:
* Using curly braces {}:
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}

* Using the dict() constructor:


my_dict = dict(name='Bob', age=25, city='London')

2. Accessing Values:
* Using the key:
value = my_dict['name'] # Accessing the value associated with the key
'name'
print(value) # Output: Alice
* Using the get() method (safer if the key might not exist):
value = my_dict.get('age')
print(value) # Output: 30
value = my_dict.get('country', 'Unknown') # Providing a default value if the
key doesn't exist
print(value) # Output: Unknown

3. Modifying Values:
* Assigning a new value to an existing key:
my_dict['city'] = 'Los Angeles'

4. Adding New Key-Value Pairs:


* Simply assign a value to a new key:
my_dict['state'] = 'California'

Page No:- 138


5. Removing Key-Value Pairs:
* Using the del keyword:
del my_dict['age']
* Using the pop() method:
removed_value = my_dict.pop('city')
print(removed_value) # Output: Los Angeles

6. Checking for Key Existence:


* Using the in operator:
if 'name' in my_dict:
print('Key "name" exists')

7. Other Useful Methods:


* keys(): Returns a view object containing all the keys in the dictionary.
* values(): Returns a view object containing all the values in the dictionary.
* items(): Returns a view object containing all the key-value pairs as tuples.
* clear(): Removes all items from the dictionary.
* copy(): Returns a shallow copy of the dictionary.
* update(): Updates the dictionary with the elements from another dictionary
or an iterable of key-value pairs.
Example:
my_dict = {'a': 1, 'b': 2, 'c': 3}print(my_dict.keys()) # Output: dict_keys(['a',
'b', 'c'])
print(my_dict.values()) # Output: dict_values([1, 2, 3])
print(my_dict.items()) # Output: dict_items([('a', 1), ('b', 2), ('c', 3)])
my_dict.update({'d': 4}) # Adding a new key-value pair
print(my_dict) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}

**********************************************

Page No:- 139


Traversing a Dictionary in Python
In Python, you can traverse a dictionary using various methods, depending on
whether you want to access keys, values, or key-value pairs. Here are the
common approaches:
1. Iterating Over Keys:
* Using keys() method:
my_dict = {'a': 1, 'b': 2, 'c': 3}
for key in my_dict.keys():
print(key) # Output: a, b, c
* Directly iterating over the dictionary:
for key in my_dict:
print(key) # Output: a, b, c
2. Iterating Over Values:
* Using values() method:
for value in my_dict.values():
print(value) # Output: 1, 2, 3
3. Iterating Over Key-Value Pairs:

* Using items() method:


for key, value in my_dict.items():
print(key, value) # Output: a 1, b 2, c 3
4. Using map() and [Link]():

keys = list(my_dict.keys())
values = list(map(my_dict.get, keys))
print(keys, values) # Output: ['a', 'b', 'c'] [1, 2, 3]
5. Using zip():
keys = list(my_dict.keys())
values = list(my_dict.values())
for key, value in zip(keys, values):
print(key, value) # Output: a 1, b 2, c 3

Page No:- 140


6. Unpacking a Dictionary:
for key, value in my_dict.items():
print(key, value) # Output: a 1, b 2, c 3

Choosing the Right Method:


* If you only need to access keys, directly iterating over the dictionary or
using keys() is efficient.
* If you only need to access values, use the values() method.
* If you need to access both keys and values, items() is the most concise and
efficient approach.
********************************************
Dictionary Methods in Python
Python dictionaries are versatile data structures that offer a rich set of
methods for efficient data manipulation. Here's a breakdown of some key
dictionary methods:
1. clear():
* Purpose: Removes all items from the dictionary.
* Syntax: dictionary_name.clear()
Example:
my_dict = {'a': 1, 'b': 2, 'c': 3}
my_dict.clear()
print(my_dict) # Output: {}
2. copy():
* Purpose: Creates a shallow copy of the dictionary. Changes to the original
dictionary will not affect the copy.
* Syntax: new_dict = dictionary_name.copy()
Example:
original_dict = {'x': 1, 'y': 2}
copied_dict = original_dict.copy()
copied_dict['z'] = 3
print(original_dict) # Output: {'x': 1, 'y': 2}

Page No:- 141


print(copied_dict) # Output: {'x': 1, 'y': 2, 'z': 3}

3. fromkeys():
* Purpose: Creates a new dictionary with specified keys and a default value.
* Syntax: new_dict = [Link](keys, value)
Example:
keys = ['a', 'b', 'c']
default_value = 0
new_dict = [Link](keys, default_value)
print(new_dict) # Output: {'a': 0, 'b': 0, 'c': 0}

4. get():
* Purpose: Returns the value associated with a key. If the key is not found, it
returns a default value (optional).
* Syntax: value = dictionary_name.get(key, default_value)
Example:
my_dict = {'a': 1, 'b': 2}

value = my_dict.get('a') # Output: 1


value = my_dict.get('c', 'Not Found') # Output: 'Not Found'

5. items():
* Purpose: Returns a view object containing all key-value pairs as tuples.
* Syntax: items_view = dictionary_name.items()
Example:
my_dict = {'a': 1, 'b': 2}
for key, value in my_dict.items():
print(key, value) # Output: a 1, b 2
6. keys():

* Purpose: Returns a view object containing all keys in the dictionary.


* Syntax: keys_view = dictionary_name.keys()

Page No:- 142


Example:
my_dict = {'a': 1, 'b': 2}
for key in my_dict.keys():
print(key) # Output: a, b

7. pop():
* Purpose: Removes and returns the value associated with a specified key. If
the key is not found, it raises a KeyError.
* Syntax: value = dictionary_name.pop(key, default_value)
Example:
my_dict = {'a': 1, 'b': 2}
value = my_dict.pop('a') # Output: 1
print(my_dict) # Output: {'b': 2}

8. popitem():
* Purpose: Removes and returns an arbitrary key-value pair as a tuple. If the
dictionary is empty, it raises a KeyError.
* Syntax: key_value_pair = dictionary_name.popitem()
Example:
my_dict = {'a': 1, 'b': 2}

removed_item = my_dict.popitem() # Output: ('b', 2)


print(my_dict) # Output: {'a': 1}

9. setdefault():
* Purpose: Returns the value associated with a key. If the key is not found, it
inserts the key with a specified default value and returns the default value.
* Syntax: value = dictionary_name.setdefault(key, default_value)
Example:
my_dict = {'a': 1}
value = my_dict.setdefault('b', 2) # Output: 2

Page No:- 143


print(my_dict) # Output: {'a': 1, 'b': 2}

10. update():
* Purpose: Updates the dictionary with key-value pairs from another
dictionary or an iterable.
* Syntax: dictionary_name.update(other)

Example:
my_dict = {'a': 1}
other_dict = {'b': 2, 'c': 3}
my_dict.update(other_dict)
print(my_dict) # Output: {'a': 1, 'b': 2, 'c': 3}

11. values():
* Purpose: Returns a view object containing all values in the dictionary.
* Syntax: values_view = dictionary_name.values()
Example:
my_dict = {'a': 1, 'b': 2}
for value in my_dict.values():
print(value) # Output: 1, 2
*********************************************************

Dictionary built in Functions in Python?


Python provides several built-in functions for working with dictionaries.
Here are some dictionary functions in python :
 len(dict): Returns the length (i.e., the number of key-value pairs) of the
dictionary.
 dict[key]: Returns the value associated with the specified key. If the
key is not found, a KeyError is raised.
 [Link](key, default=None): Returns the value associated with the
specified key, or the default value if the key is not found. If the default
parameter is not specified, it defaults to None.
 [Link](): Returns a list of all the keys in the dictionary.

Page No:- 144






 [Link](): Returns a list of all the values in the dictionary.


 [Link](): Returns a list of all the key-value pairs in the dictionary,
as tuples.
 [Link](): Removes all key-value pairs from the dictionary.
 [Link](key, default=None): Removes the key-value pair with the
specified key from the dictionary and returns the value. If the key is not
found and the default is not specified, a KeyError is raised.
 [Link](): Removes and returns an arbitrary key-value pair from
the dictionary. If the dictionary is empty, a KeyError is raised.
 [Link](other_dict): Updates the dictionary with key-value pairs
from another dictionary. If a key exists in both dictionaries, the value in
the other dictionary overwrites the value in the original dictionary.
 [Link](seq, value=None): Creates a new dictionary with keys
from the specified sequence (e.g., a list, tuple, or set) and values set to
the specified value. If the value parameter is not specified, it defaults to
None.
*********************************************
UNIT-IV
Python Arrays
Array is a collection of items stored at contiguous memory locations.
The idea is to store multiple items of the same type together.
Unlike Python lists (can store elements of mixed types), arrays must have all
elements of same type. Having only homogeneous elements makes it memory-
efficient.

Python Array Example


import array as arr
# creating array of integers
a = [Link]('i', [1, 2, 3])
# accessing First Araay
print(a[0])
Page No:- 145
# Adding element to array
[Link](5)
print(a)
Output:
1
array('i', [1, 2, 3, 5])

Advantages and Disadvantages of Array in Python:-


Advantages of Array in Python
1. Efficient access and handling.

2. Versatility with different data types.


3. Built-in functions for manipulation.
4. Optimized memory usage.
5. Fast data retrieval.
6. Supports various data structures.
7. Simplified iteration.
8. Widely used and supported.
Disadvantages of Array in Python
1. Once created, you cannot easily change their size.
2. Adding or removing elements in the middle can be slow.
3. You can only store elements of the same type.
4. Finding something in an array can take time, especially in large arrays.
5. They don’t support key-value pairs like dictionaries do.
**************************
NumPy Array?
 NumPy array is a multi-dimensional data structure that is the core of
scientific computing in Python.
 All values in an array are homogenous (of the same data type).
 They offer automatic vectorization and broadcasting.
 They provide efficient memory management, ufuncs(universal
functions), support various data types, and are flexible with Indexing
and slicing.

Page No:- 146


Dimensions in Arrays
NumPy arrays can have multiple dimensions, allowing users to store data in
multilayered structures.
Dimensionalities of array:

Name Example

0D (zero-dimensional) Scalar – A single element

1D (one-dimensional) Vector- A list of integers.

2D (two-dimensional) Matrix- A spreadsheet of data

3D (three-dimensional) Tensor- Storing a color image

Create NumPy Array from a List


You can use the np alias to create ndarray of a list using the array() method.
li = [1,2,3,4]
numpyArr = [Link](li)
or
numpyArr = [Link]([1,2,3,4])
0-D Arrays
0-D arrays, or Scalars, are the elements in an array. Each value in an array is
a 0-D array.
import numpy as np
arr = [Link](42)
print(arr)
output: 42
**************
1-D Arrays
An array that has 0-D arrays as its elements is called uni-dimensional or 1-D
array.
These are the most common and basic arrays

Page No:- 147


import numpy as np
arr = [Link]([1, 2, 3, 4, 5])
print(arr)
output
[1, 2, 3, 4, 5]
*********************
2-D Arrays
An array that has 1-D arrays as its elements is called a 2-D array.
These are often used to represent matrix or 2nd order tensors.
NumPy has a whole sub module dedicated towards matrix operations
called [Link]
import numpy as np
arr = [Link]([[1, 2, 3], [4, 5, 6]])
print(arr)
output
[[1 2 3]
[4 5 6]]

******************
3-D arrays

An array that has 2-D arrays (matrices) as its elements is called 3-D array.
These are often used to represent a 3rd order tensor.
import numpy as np
arr = [Link]([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(arr)
output
[[[1 2 3]
[4 5 6]]

[[1 2 3]
[4 5 6]]]
****************

Page No:- 148


Indexing And Slicing In Python
indexing and slicing are fundamental concepts that allow users to access
specific elements in a sequence. Indexing is used to retrieve a single element
from a specific position in a sequence, while slicing is used to extract a range
of elements from a sequence.

indexing and slicing are techniques used to access specific characters or parts
of a string. Indexing means referring to an element of an iterable by its
position whereas slicing is a feature that enables accessing parts of the
sequence.
Indexing Strings in Python
String Indexing allows us to access individual characters in a string. Python
treats strings like lists where each character is assigned an index, starting
from 0. We can access characters in a String in Two ways :
1. Accessing Characters by Positive Index Number
2. Accessing Characters by Negative Index Number

Accessing by Positive Index Number


In this type of Indexing we pass a Positive index (which we want to access) in
square brackets. The index number starts from index number 0 (which
denotes the first character of a string).
s = "Geeks for Geeks !"
print(s[0])
# accessing the character of str at 6th index
print(s[6])

# accessing the character of str at 10th index


print(s[10])
Output
G
f
G
****************
Page No:- 149
Accessing by Negative Index Number
In this type of Indexing, we pass the Negative index(which we want to access)
in square brackets. Here the index number starts from index number -1 (which
denotes the last character of a string). Example 2 (Negative Indexing) :
# declaring the string
s = "Geeks for Geeks !"

# accessing the character of str at last index


print(s[-1])

# accessing the character of str at 5th index from the last


print(s[-5])

# accessing the character of str at 10th index from the last


print(s[-10])
Output
!
e
o
*********************************************
Slicing Strings in Python
String Slicing allows us to extract a part of the string. We can specify a start
index, end index, and step size. The general format for slicing is:

string[start : end : step]


start : We provide the starting index.
end : We provide the end index(this is not included in substring).

step : It is an optional argument that determines the increment between each


index for slicing.
# declaring the string
s ="Geeks for Geeks !"
# slicing using indexing sequence
print(s[: 3])
print(s[1 : 5 : 2])
print(s[-1 : -12 : -2])

Output
Gee
ek
!seGrf
*************************

Page No:- 150


Discuss about the Operations on NumPy Arrays with example.

Ans: NumPy arrays are powerful data structures that provide a wide range of
operations to manipulate numerical data efficiently. These operations range
from basic arithmetic to more complex matrix manipulations, reshaping, and d
statistical computations. NumPy's optimized C-based implementation makes it
much faster and more efficient than Python's built-in list for these operations,
especially when dealing with large datasets.

Operations on NumPy:

1. Basic Arithmetic Operations: NumPy allows for element-wise arithmetic


operations, such as addition, subtraction, multiplication, and division. These
operations are vectorized, meaning they operate directly on entire arrays
without the need for explicit loops.

Example:
import numpy as np
#Creating two NumPy arrays arr1 [Link]([1, 2, 3]) arr2= [Link]([4, 5, 6])
#Performing element-wise addition resultarrl + arr2
print(result)
#Output: [579]
In this example, the + operator adds corresponding elements from arr1 and
arr2. Similar operations can be done for subtraction, multiplication and
division.

2. Broadcasting: Broadcasting is one of NumPy's most powerful features,


allowing operations between arrays of different shapes. NumPy automatically
stretches the smaller array across the larger one to perform operations.
Example
ит пратау [1, 2, 3])
scalar-5
Broadcasting scalar across the array

Page No:- 151


result scalar
print(result)
#Output: [678]
Here, the scalar 5 is broadcasted across the entire array arr for element-wise
addition,
3. Reshaping Arrays: The reshape() method allows you to modify the shape
of an array without changing its data. This is useful when dealing with multi-
dimensional data or transforming data for different operations.

Example:

[Link]([1, 2, 3, 4, 5, 6])

Reshaping the array into 2 rows and 3 columns

reshaped_arr [Link](2, 3)

print(reshaped_arr)

Output:

#[123]

#[456]]
Reshaping is especially useful in machine learning, where data often needs to
be reshaped for model inputs.

4. Matrix Operations: NumPy supports matrix operations such as dot


product, transposition, and matrix multiplication, which are essential for linear
algebra.
Example:

mati [Link]([[1, 2], [3, 4])

[Link]([[5, 6], [7, 8]])

#Matrix multiplication using dot product

[Link](mat, mat2)

Page No:- 152


print(result)

#Output:

#[[1922]

# [43.50]]

Matrix multiplication, using [Link](), is a common operation in machine


learning and data science.

5. Aggregation Functions: NumPy provides functions like sum(), mean(),


max(), and min() to perform aggregation across array elements.
Example:

arr [Link]([1, 2, 3, 4, 5])

Sum of all elements

total [Link](arr)

print(total)#Output: 15

#Mean of the array

mean value [Link](arr)

print(mean value) #Output: 3.0

These functions are useful for statistical analysis and summarizing data.

6. Element-wise Comparison: NumPy allows for element-wise comparisons


that return Boolean arrays, where True indicates that the condition is met.
Example: [Link]([1, 2, 3, 4, 5])

#Check if elements are greater than 3

result = arr>3

print(result) #Output: [False False False True True)

Element-wise comparisons are useful for filtering data based on conditions.


*****************************
Page No:- 153
[Link]() in Python

The concatenate() function is a function from the NumPy package. This


function essentially combines NumPy arrays together. This function is basically
used for joining two or more arrays of the same shape along a specified axis.
There are the following things which are essential to keep in mind:
1. NumPy's concatenate() is not like a traditional database join. It is like
stacking NumPy arrays.
2. This function can operate both vertically and horizontally. This means we
can concatenate arrays together horizontally or vertically.

# Python program explaining


# [Link]() function

# importing numpy as geek


import numpy as geek

arr1 = [Link]([[2, 4], [6, 8]])


arr2 = [Link]([[3, 5], [7, 9]])

gfg = [Link]((arr1, arr2), axis = 0)

print (gfg)

Output :
[[2 4]
[6 8]
[3 5]
[7 9]]
**********************************
Reshape NumPy Array
Reshaping numpy array simply means changing the shape of the given array,
shape basically tells the number of elements and dimension of array, by
reshaping an array we can add or remove dimensions or change number of
elements in each dimension.
Page No:- 154
In order to reshape a numpy array we use reshape method with the given
array.

Syntax : [Link](shape)
Argument : It take tuple as argument, tuple is the new shape to be formed
Return : It returns [Link]

Reshaping : 1-D to 2D
In this example we will reshape the 1-D array of shape (1, n) to 2-D array of
shape (N, M) here M should be equal to the n/N there for N should be factor of
n.

# importing numpy
import numpy as np

# creating a numpy array


array = [Link]([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])

# printing array
print("Array : " + str(array))

# length of array
n = [Link]

# N-D array N dimension


N=4

# calculating M
M = n//N

# reshaping numpy array


# converting it to 2-D from 1-D array
reshaped1 = [Link]((N, M))

# printing reshaped array


print("First Reshaped Array : ")
print(reshaped1)

# creating another reshaped array


reshaped2 = [Link](array, (2, 8))

# printing reshaped array

Page No:- 155


print("Second Reshaped Array : ")
print(reshaped2)

Output :

Array : [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16]
First Reshaped Array :
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]
[13 14 15 16]]
Second Reshaped Array :
[[ 1 2 3 4 5 6 7 8]
[ 9 10 11 12 13 14 15 16]]
***********************************
NumPy Splitting Array
Array splitting in NumPy is like a slice of cake. Think of each element in a
NumPy array as a slice of cake. Splitting divides this “cake” into smaller
“slices” (sub-arrays), often along specific dimensions or based on certain
criteria. We can split horizontally, vertically, or even diagonally depending on
our needs.
The split(), hsplit(), vsplit(), and dsplit() functions are important tools for
dividing arrays along various axes and dimensions. These functions are
particularly useful when working with one-dimensional arrays, matrices, or
high-dimensional datasets. NumPy’s array-splitting capabilities are crucial for
enhancing the efficiency and flexibility of data processing workflows.
Key concepts and terminology
Here are some important terms to understand when splitting arrays:
 Axis: The dimension along which the array is split (e.g., rows, columns,
depth).
 Sub-arrays: The smaller arrays resulting from the split.
 Splitting methods: Different functions in NumPy for splitting arrays
(e.g., [Link](), [Link](), [Link](), etc.).
 Equal vs. Unequal splits: Whether the sub-arrays have the same size or
not.
 Python3

import numpy as np
Arr = [Link]([1, 2, 3, 4, 5, 6])
array = np.array_split(arr, 3)

Page No:- 156


print(array)

Output:
[array([1, 2]), array([3, 4]), array([5, 6])]
Splitting NumPy Arrays in Python
There are many methods to Split Numpy Array in Python using different
functions some of them are mentioned below:
 Split numpy array using [Link]()
 Split numpy array using numpy.array_split()
 Splitting NumPy 2D Arrays
 Split numpy array using [Link]()
 Split numpy array using numpyhsplit()
 Split numpy arrayusing [Link]()

1. [Link]() is a function that divides an array into equal parts along a


specified axis. The code imports NumPy creates an array of numbers (0-
5), and then splits it in half (horizontally) using [Link](). The output
shows the original array and the two resulting sub-arrays, each
containing 3 elements.

2. numpy.array_split() splitting into equal or nearly equal sub-arrays or is


similar to [Link](), but it allows for uneven splitting of arrays. This
is useful when the array cannot be evenly divided by the specified
number of splits. numpy.array_split(array, 4) splits the array into four
parts, accommodating the uneven division.

3. the application of [Link]() in dividing a 2D array into equal parts


along a specified axis. Similar concepts can be applied
to numpy.array_split for uneven splitting. [Link] ( array, 3, axis=1 )
splits the array into three equal parts along the second axis.

4. Vertical splitting (row-wise) with [Link]() divides an array along


the vertical axis (axis=0), creating subarrays. This is particularly useful
for matrices and multi-dimensional arrays. [Link]( matrix, 2) splits
the matrix into two equal parts along the vertical axis (axis=0).

Page No:- 157


5. Horizontal splitting (column-wise) with [Link]() divides an array
along the horizontal axis (axis=1), creating subarrays. This operation is
valuable in data processing tasks. [Link] ( array, 2) splits the
array into two equal parts along the horizontal axis (axis=1).

6. [Link]() is used for splitting arrays along the third axis (axis=2),
applicable to 3D arrays and beyond. [Link] (original_3d_array, 2)
splits the array into two equal parts along the third axis (axis=2).
*************************
Numpy - Mathematical and Statistical functions on NumPy Arrays
There are several mathematical and statistical functions available in NumPy
which can be very useful in manipulating the data of a matrix (dataset).

They are as below:

import numpy as np
mean()

Calculates mean of all the elements of the NumPy array, irrespective of the
shape of the array.

X = [Link]( [ [-2.5, 3.1, 7],


[10, 11, 12] ] )
print("mean = ", [Link]())

Output will be

6.766666666666667

var()

Calculates the variance of the elements of the NumPy array.

print("Variance = ", [Link]())


Output will be

25.855555555555554

std()

Calculates the standard deviation of the elements of the NumPy array.

print("Standard Deviation = ", [Link]())


Output will be

Page No:- 158


5.084835843520964

min()

Returns the minimum element in the NumPy array.

print("min = ", [Link]())


Output will be

-2.5

max()

Returns the maximum element in the NumPy array.

print("max = ", [Link]())


Output will be

12.0

sum()

Returns the sum of the elements of the NumPy array.

print("sum = ", [Link]())


Output will be

40.6

prod()

Returns product of the elements of the NumPy array.

print("product = ", [Link]())


Output will be

-71610.0

Common NumPy Statistical Functions


Here are some of the statistical functions provided by NumPy:

Functions Descriptions
median() return the median of an array
# Import statistics Library
import statistics
# Calculate middle values
print([Link]([1, 3, 5, 7, 9, 11, 13]))
print([Link]([1, 3, 5, 7, 9, 11]))
print([Link]([-11, 5.5, -3.4, 7.1, -9, 22]))
output

Page No:- 159


7
6.0
1.05
mean() return the mean of an array
# Import statistics Library
import statistics

# Calculate average values


print([Link]([1, 3, 5, 7, 9, 11, 13]))
print([Link]([1, 3, 5, 7, 9, 11]))
print([Link]([-11, 5.5, -3.4, 7.1, -9, 22]))
output
7
6
1.8666666666666667
std() return the standard deviation of an array
# Import statistics Library
import statistics
# Calculate the standard deviation from a sample of data
print([Link]([1, 3, 5, 7, 9, 11]))
print([Link]([2, 2.5, 1.25, 3.1, 1.75, 2.8]))
print([Link]([-11, 5.5, -3.4, 7.1]))
print([Link]([1, 30, 50, 100]))
output
3.7416573867739413
0.6925797186365384
8.414471660973929
41.67633221226008
percentile() return the nth percentile of elements in an array
import numpy as np

# 1D array
arr = [20, 2, 7, 1, 34]
print("arr : ", arr)
print("50th percentile of arr : ",
[Link](arr, 50))
print("25th percentile of arr : ",
[Link](arr, 25))
print("75th percentile of arr : ",
[Link](arr, 75))
output
Output:
arr : [20, 2, 7, 1, 34]
50th percentile of arr : 7.0
25th percentile of arr : 2.0
75th percentile of arr : 20.0

Page No:- 160


min() return the minimum element of an array
#initialize the set my_set = {5, 2, 8, 1, 9, 2, 18} # Convert set
to a list my_list = list(my_set) # Find the maximum and
minimum values maximum = max(my_list) minimum =
min(my_list) # Display maximum and minimum value
print("Maximum:", maximum) print("Minimum:", minimum)
Output
Maximum: 18
Minimum: 1
max() return the maximum element of an array

**************************************
Libraries in Python

Normally, a library is a collection of books or is a room or place where many


books are stored to be used later.
Similarly, in the programming world, a library is a collection of precompiled
codes that can be used later on in a program for some specific well-defined
operations. Other than pre-compiled codes, a library may contain
documentation, configuration data, message templates, classes, and values,
etc.
A Python library is a collection of related modules. It contains bundles of code
that can be used repeatedly in different programs. It makes Python
Programming simpler and convenient for the programmer. As we don’t need to
write the same code again and again for different programs. Python libraries
play a very vital role in fields of Machine Learning, Data Science, Data
Visualization, etc.

Working of Python Library

As is stated above, a Python library is simply a collection of codes or modules


of codes that we can use in a program for specific operations. We use libraries
so that we don’t need to write the code again in our program that is already
available. But how it works. Actually, in the MS Windows environment, the
library files have a DLL extension (Dynamic Load Libraries). When we link a
library with our program and run that program, the linker automatically
searches for that library. It extracts the functionalities of that library and
interprets the program accordingly. That’s how we use the methods of a library
in our program.

Python standard library

The Python Standard Library contains the exact syntax, semantics, and tokens
of Python. It contains built-in modules that provide access to basic system
functionality like I/O and some other core modules. Most of the Python
Libraries are written in the C programming language. The Python standard
library consists of more than 200 core modules. All these work together to
make Python a high-level programming language. Python Standard Library
Page No:- 161
plays a very important role. Without it, the programmers can’t have access to
the functionalities of Python. But other than this, there are several other
libraries in Python that make a programmer’s life easier.

some of the commonly used libraries:

TensorFlow: This library was developed by Google in collaboration with the


Brain Team. It is an open-source library used for high-level computations. It is
also used in machine learning and deep learning algorithms. It contains a large
number of tensor operations. Researchers also use this Python library to solve
complex computations in Mathematics and Physics.

Matplotlib: This library is responsible for plotting numerical data. And that’s
why it is used in data analysis. It is also an open-source library and plots high-
defined figures like pie charts, histograms, scatterplots, graphs, etc.

Pandas: Pandas are an important library for data scientists. It is an open-


source machine learning library that provides flexible high-level data structures
and a variety of analysis tools. It eases data analysis, data manipulation, and
cleaning of data. Pandas support operations like Sorting, Re-indexing,
Iteration, Concatenation, Conversion of data, Visualizations, Aggregations, etc.

Numpy: The name “Numpy” stands for “Numerical Python”. It is the commonly
used library. It is a popular machine learning library that supports large
matrices and multi-dimensional data. It consists of in-built mathematical
functions for easy computations. Even libraries like TensorFlow use Numpy
internally to perform several operations on tensors. Array Interface is one of
the key features of this library.

SciPy: The name “SciPy” stands for “Scientific Python”. It is an open-source


library used for high-level scientific computations. This library is built over an
extension of Numpy. It works with Numpy to handle complex computations.
While Numpy allows sorting and indexing of array data, the numerical data
code is stored in SciPy. It is also widely used by application developers and
engineers.

Scrapy: It is an open-source library that is used for extracting data from


websites. It provides very fast web crawling and high-level screen scraping. It
can also be used for data mining and automated testing of data.

Scikit-learn: It is a famous Python library to work with complex data. Scikit-


learn is an open-source library that supports machine learning. It supports
variously supervised and unsupervised algorithms like linear regression,
classification, clustering, etc. This library works in association with Numpy and
SciPy.

Page No:- 162


PyGame: This library provides an easy interface to the Standard Directmedia
Library (SDL) platform-independent graphics, audio, and input libraries. It is
used for developing video games using computer graphics and audio libraries
along with Python programming language.

PyTorch: PyTorch is the largest machine learning library that optimizes tensor
computations. It has rich APIs to perform tensor computations with strong GPU
acceleration. It also helps to solve application issues related to neural
networks.

PyBrain: The name “PyBrain” stands for Python Based Reinforcement


Learning, Artificial Intelligence, and Neural Networks library. It is an open-
source library built for beginners in the field of Machine Learning. It provides
fast and easy-to-use algorithms for machine learning tasks. It is so flexible
and easily understandable and that’s why is really helpful for developers that
are new in research fields.

Use of Libraries in Python Program

As we write large-size programs in Python, we want to maintain the code’s


modularity. For the easy maintenance of the code, we split the code into
different parts and we can use that code later ever we need it. In
Python, modules play that part. Instead of using the same code in different
programs and making the code complex, we define mostly used functions in
modules and we can just simply import them in a program wherever there is a
requirement.

Example
# Importing math library
import math

A = 16
print([Link](A))

output
Output
4.0

Importing specific items from a library module

As in the above code, we imported a complete library to use one of its


methods. But we could have just imported “sqrt” from the math library. Python
allows us to import specific items from a library.
Let’s look at an exemplar code :

# Importing specific items


from math import sqrt, sin

Page No:- 163


A = 16
B = 3.14
print(sqrt(A))
print(sin(B))

Output
4.0
0.0015926529164868282
********************************************

Python Pandas Series

Pandas Series is a one-dimensional labeled array capable of holding data of


any type (integer, string, float, python objects, etc.).

Pandas Series Examples


# import pandas as pd
import pandas as pd

# simple array
data = [1, 2, 3, 4]

ser = [Link](data)
print(ser)

Output
0 1
1 2
2 3
3 4
dtype: int64
************************************
Creating a Pandas Series

In the real world, a Pandas Series will be created by loading the datasets from
existing storage, storage can be SQL Database, CSV file, and Excel file. Pandas
Series can be created from the lists, dictionary, and from a scalar value etc.
Series can be created in different ways, here are some ways by which we
create a series:

Creating a series from array: In order to create a series from array, we have to
import a numpy module and have to use array() function.

# import pandas as pd
import pandas as pd

# import numpy as np
import numpy as np

Page No:- 164


# simple array
data = [Link](['g','e','e','k','s'])

ser = [Link](data)
print(ser)

Output
0 g
1 e
2 e
3 k
4 s
dtype: object
***********************

Accessing element of Series

There are two ways through which we can access element of series, they are :
Accessing Element from Series with Position
Accessing Element Using Label (index)
Accessing Element from Series with Position : In order to access the series
element refers to the index number. Use the index operator [ ] to access an
element in a series. The index must be an integer. In order to access multiple
elements from a series, we use Slice operation.

Accessing first 5 elements of Series.

# import pandas and numpy


import pandas as pd
import numpy as np
# creating simple array
data = [Link](['g','e','e','k','s','f', 'o','r','g','e','e','k','s'])
ser = [Link](data)
#retrieve the first element
print(ser[:5])

Output

0 g
1 e
2 e
3 k
4 s
dtype: object
******************************

Page No:- 165


Accessing Element Using Label (index) :

In order to access an element from series, we have to set values by index


label. A Series is like a fixed-size dictionary in that you can get and set values
by index label.
Accessing a single element using index label.

# import pandas and numpy


import pandas as pd
import numpy as np
# creating simple array
data = [Link](['g','e','e','k','s','f', 'o','r','g','e','e','k','s'])
ser = [Link](data,index=[10,11,12,13,14,15,16,17,18,19,20,21,22])
# accessing a element using index element
print(ser[16])

Output
o
****************
Indexing and Selecting Data in Series
Indexing in pandas means simply selecting particular data from a Series.
Indexing could mean selecting all the data, some of the data from particular
columns. Indexing can also be known as Subset Selection.

Indexing a Series using indexing operator [] :


Indexing operator is used to refer to the square brackets following an object.
The .loc and .iloc indexers also use the indexing operator to make selections.
In this indexing operator to refer to df[ ].

# importing pandas module


import pandas as pd
# making data frame

df = pd.read_csv("[Link]")
ser = [Link](df['Name'])
data = [Link](10)
data

Page No:- 166


Now we access the element of series using index operator [ ].

# using indexing operator


data[3:6]

Indexing a Series using .loc[ ] :


This function selects data by refering the explicit index . The [Link] indexer
selects data in a different way than just the indexing operator. It can select
subsets of data.

# importing pandas module

import pandas as pd

# making data frame


df = pd.read_csv("[Link]")
ser = [Link](df['Name'])
data = [Link](10)

data

Now we access the element of series using .loc[] function.

Page No:- 167


# using .loc[] function
[Link][3:6]

Output :

Indexing a Series using .iloc[ ] :

This function allows us to retrieve data by position. In order to do that, we’ll


need to specify the positions of the data that we want. The [Link] indexer is
very similar to [Link] but only uses integer locations to make its selections.

# importing pandas module


import pandas as pd
# making data frame
df = pd.read_csv("[Link]")
ser = [Link](df['Name'])
data = [Link](10)
data

Output:

Now we access the element of Series using .iloc[] function.

# using .iloc[] function

[Link][3:6]

Output :

*************************************************

Page No:- 168


Pandas DataFrame
Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous
tabular data structure with labeled axes (rows and columns). A Data frame is a
two-dimensional data structure, i.e., data is aligned in a tabular fashion in
rows and columns. Pandas DataFrame consists of three principal components,
the data, rows, and columns.

Creating a Pandas DataFrame


Pandas DataFrame will be created by loading the datasets from existing
storage, storage can be SQL Database, CSV file, and Excel file. Pandas
DataFrame can be created from the lists, dictionary, and from a list of
dictionary etc.
Here are some ways by which we create a dataframe:
Creating a dataframe using List: DataFrame can be created using a single list
or a list of lists.
import pandas as pd
# list of strings
lst = ['Geeks', 'For', 'Geeks', 'is',
'portal', 'for', 'Geeks']
# Calling DataFrame constructor on list
df = [Link](lst)
9

print(df)
Output:

Page No:- 169


Output
Creating DataFrame from dict of ndarray/lists: To create DataFrame from dict
of narray/list, all the narray must be of same length. If index is passed then
the length index should be equal to the length of arrays. If no index is passed,
then by default, index will be range(n) where n is the array length.
# Python code demonstrate creating
# DataFrame from dict narray / lists
# By default addresses.
import pandas as pd

# intialise data of lists.


data = {'Name':['Tom', 'nick', 'krish', 'jack'],
'Age':[20, 21, 19, 18]}
# Create DataFrame
df = [Link](data)
# Print the output.
print(df)

Output:

Page No:- 170


Dealing with Rows and Columns in Pandas DataFrame
A Data frame is a two-dimensional data structure, i.e., data is aligned in a
tabular fashion in rows and columns. We can perform basic operations on
rows/columns like selecting, deleting, adding, and renaming.

Column Selection: In Order to select a column in Pandas DataFrame, we can


either access the columns by calling them by their columns name.

# Import pandas package


import pandas as pd
# Define a dictionary containing employee data
data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'],
'Age':[27, 24, 22, 32],
'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'],
'Qualification':['Msc', 'MA', 'MCA', 'Phd']}
# Convert the dictionary into DataFrame
df = [Link](data)
# select two columns
print(df[['Name', 'Qualification']])

Output:

Row Selection: Pandas provide a unique method to retrieve rows from a Data
frame. [Link][] method is used to retrieve rows from Pandas
DataFrame. Rows can also be selected by passing integer location to
an iloc[] function.

Page No:- 171


Note: We’ll be using [Link] file in below examples.
# importing pandas package
import pandas as pd
# making data frame from csv file
data = pd.read_csv("[Link]", index_col ="Name")

# retrieving row by loc method


first = [Link]["Avery Bradley"]
second = [Link]["R.J. Hunter"]
print(first, "\n\n\n", second)

Output:
As shown in the output image, two series were returned since there was only
one parameter both of the times.

For more Details refer to Dealing with Rows and Columns


Indexing and Selecting Data in Pandas
Indexing in pandas means simply selecting particular rows and columns of
data from a DataFrame. Indexing could mean selecting all the rows and some
of the columns, some of the rows and all of the columns, or some of each of
the rows and columns. Indexing can also be known as Subset Selection.

Page No:- 172


Indexing a Dataframe using indexing operator []
Indexing operator is used to refer to the square brackets following an object.
The .loc and .iloc indexers also use the indexing operator to make selections.
In this indexing operator to refer to df[].
In order to select a single column, we simply put the name of the column in-
between the brackets
# importing pandas package
import pandas as pd
# making data frame from csv file
data = pd.read_csv("[Link]", index_col ="Name")
# retrieving columns by indexing operator
first = data["Age"]
print(first)

Output:

Page No:- 173


Indexing a DataFrame using .loc[ ]
This function selects data by the label of the rows and columns.
The [Link] indexer selects data in a different way than just the indexing
operator. It can select subsets of rows or columns. It can also simultaneously
select subsets of rows and columns.
In order to select a single row using .loc[], we put a single row label in
a .loc function.
# importing pandas package
import pandas as pd
# making data frame from csv file
data = pd.read_csv("[Link]", index_col ="Name")
# retrieving row by loc method
first = [Link]["Avery Bradley"]
second = [Link]["R.J. Hunter"]
print(first, "\n\n\n", second)

Output:
As shown in the output image, two series were returned since there was only
one parameter both of the times.

Indexing a DataFrame using .iloc[ ]


This function allows us to retrieve rows and columns by position. In order to do
that, we’ll need to specify the positions of the rows that we want, and the
positions of the columns that we want as well. The [Link] indexer is very
similar to [Link] but only uses integer locations to make its selections.

Page No:- 174


In order to select a single row using .iloc[], we can pass a single integer
to .iloc[] function.

import pandas as pd
# making data frame from csv file
data = pd.read_csv("[Link]", index_col ="Name")
# retrieving rows by iloc method
row2 = [Link][3]
print(row2)
Output:

************************************************
import csv file in Pandas
CSV files are the “comma separated values”, these values are separated by
commas, this file can be viewed as an Excel file. In Python, Pandas is the most
important library coming to data science. We need to deal with huge datasets
while analyzing the data, which usually can be in CSV file format. Let’s see the
different ways to import csv files in Pandas.
Ways to Import CSV File in Pandas
There are various ways to import CSV files in Pandas, here we are discussing
some generally used methods for importing CSV files in pandas.
 Using read_csv() Method
 Using csv Module.
 Using numpy Module

Page No:- 175


Import a CSV File into Python using Pandas
In this method the below code uses the panda’s library to read an NBA-
related CSV file from a given URL, creating a DataFrame named `df`. It then
prints the first 10 rows of the DataFrame to provide a brief overview of the
dataset.
 Python

# importing pandas module


import pandas as pd

# making data frame


df = pd.read_csv("[Link]
content/uploads/[Link]")

[Link](10)

Output:

Providing file_path
In this example the below code uses the pandas library to read a CSV file
(“C:\Gfg\datasets\[Link]”) into a DataFrame and then prints the first five
rows of the DataFrame.

Page No:- 176


 Python3

# import pandas as pd
import pandas as pd

# Takes the file's folder


filepath = r"C:\Gfg\datasets\[Link]";

# read the CSV file


df = pd.read_csv(filepath)

# print the first five rows


print([Link]())

Output:

Import CSV file in Pandas using csv module.


One can directly import the csv files using csv module. In this code example
the below code reads a CSV file (“[Link]”) into a Pandas DataFrame using
Python’s `csv` and `pandas` modules. It then prints the values in the first
column of the DataFrame. A correction is needed in the DataFrame creation
line for accurate functionality.

Page No:- 177


 Python

# import the module csv


import csv
import pandas as pd

# open the csv file


with open(r"C:\Users\Admin\Downloads\[Link]") as csv_file:

# read the csv file


csv_reader = [Link](csv_file, delimiter=',')

# now we can use this csv files into the pandas


df = [Link]([csv_reader], index=None)
[Link]()

# iterating values of first column


for val in list(df[1]):
print(val)

Output:

Loading CSV Data into a NumPy Array


Way to import a CSV file in Python is by using the numpy library.
The numpy library provides the genfromtxt() function, which can be used to
read data from a CSV file and create a NumPy array.
Example : Replace 'path/to/your/[Link]' with the actual path to your CSV file.
The delimiter=',' parameter indicates that the values in the CSV file are
separated by commas. This method is useful when you want to work with
numerical data and leverage the capabilities of the NumPy library.

Page No:- 178


 Python3

import numpy as np

# Specify the path to the CSV file


csv_file_path = 'path/to/your/[Link]'

# Use genfromtxt to read the CSV file into a NumPy array


data_array = [Link](csv_file_path, delimiter=',')

# Now, data_array contains the data from the CSV file


print(data_array)

Output :
[[1. 2. 3.]
[4. 5. 6.]
[7. 8. 9.]]
***********************************************
Export Pandas dataframe to a CSV file
Suppose you are working on a Data Science project and you tackle one of the
most important tasks, i.e, Data Cleaning. After data cleaning, you don’t want
to lose your cleaned data frame, so you want to save your cleaned data frame
as a CSV. Let us see how to export a Pandas DataFrame to a CSV file.
Pandas enable us to do so with its inbuilt to_csv() function.
First, let’s create a sample data frame

# importing the module


import pandas as pd
# making the data
scores = {'Name': ['a', 'b', 'c', 'd'],
'Score': [90, 80, 95, 20]}
# creating the DataFrame
df = [Link](scores)

Page No:- 179


# displaying the DataFrame
print(df)

Output :

Now let us export this DataFrame as a CSV file named your_name.csv :

 Python3

# converting to CSV file


df.to_csv("your_name.csv")

Output

File Successfully saved

In case you get a UnicodeEncodeError, just pass the encoding parameter with
‘utf-8’ value.

 Python3

# converting to CSV file


df.to_csv("your_name.csv", encoding = 'utf-8')

Page No:- 180


Possible Customizations
1. Include index number
You can choose if you want to add automatic index. The default value is True.
To set it to False.

 Python3

# converting to CSV file


df.to_csv('your_name.csv', index = False)

Output :

2. Export only selected columns


If you want to export only a few selected columns, you may pass it in to_csv()
as ‘columns = [“col1”, “col2”]

Python3

# converting to CSV file


df.to_csv("your_name.csv", columns = ['Name'])

Output :

3. Export header
You can choose if you want your column names to be exported or not by
setting the header parameter to True or False. The default value is True.
Python3

Page No:- 181


# converting to CSV file
df.to_csv('your_name.csv', header = False)

Output :

4. Handle NaN
In case your data frame has NaN values, you can choose it to replace by some
other string. The default value is ”.

Python3

# converting to CSV file


df.to_csv("your_name.csv", na_rep = 'nothing')

5. Separate with something else

If instead of separating the values with a ‘comma’, we can separate it using


custom values.

Python3

# converting to CSV file


# separated with tabs
df.to_csv("your_name.csv", sep ='\t')

Output :

*********************************************
UNIT-V
plotting data using matplotlib

Matplotlib is a powerful and versatile open-source plotting library for Python,


designed to help users visualize data in a variety of formats. Developed by
John D. Hunter in 2003, it enables users to graphically represent data,
facilitating easier analysis and understanding. If you want to convert your
boring data into interactive plots and graphs, Matplotlib is the tool for you.

Page No:- 182


Key Features of Matplotlib

Versatile Plotting: Create a wide variety of visualizations, including line plots,


scatter plots, bar charts, and histograms.

Extensive Customization: Control every aspect of your plots, from colors and
markers to labels and annotations.
Seamless Integration with NumPy: Effortlessly plot data arrays directly,
enhancing data manipulation capabilities.
High-Quality Graphics: Generate publication-ready plots with precise control
over aesthetics.
Cross-Platform Compatibility: Use Matplotlib on Windows, macOS, and Linux
without issues.
Interactive Visualizations: Engage with your data dynamically through
interactive plotting features.
Example of a Plot in Matplotlib : Let’s create a simple line plot using
Matplotlib, showcasing the ease with which you can visualize data.
Python
1
import [Link] as plt
2

3
x = [0, 1, 2, 3, 4]
4
y = [0, 1, 4, 9, 16]
5

6
[Link](x, y)
7
[Link]()
Output:

Page No:- 183


Simplest plot in Matplotlib

Basic Components or Parts of Matplotlib Figure

Anatomy of a Matplotlib Plot: This section dives into the key components of a
Matplotlib plot, including figures, axes, titles, and legends, essential for
effective data visualization.

The parts of a Matplotlib figure include (as shown in the figure above):

Figure: The overarching container that holds all plot elements, acting as the
canvas for visualizations.

Axes: The areas within the figure where data is plotted; each figure can
contain multiple axes.

Axis: Represents the x-axis and y-axis, defining limits, tick locations, and
labels for data interpretation.

Lines and Markers: Lines connect data points to show trends, while markers
denote individual data points in plots like scatter plots.

Title and Labels: The title provides context for the plot, while axis labels
describe what data is being represented on each axis.

Different Types of Plots in Matplotlib

Matplotlib offers a wide range of plot types to suit various data visualization
needs. Here are some of the most commonly used types of plots in Matplotlib:
1. Line Graph
2. Bar Chart
3. Histogram
4. Scatter Plot
5. Pie Chart
6. 3D Plot

*********************************************

Page No:- 184


Line chart in Matplotlib – Python
Matplotlib is a data visualization library in Python. The pyplot, a sublibrary of
Matplotlib, is a collection of functions that helps in creating a variety of
charts. Line charts are used to represent the relation between two data X and
Y on a different axis. In this article, we will learn about line charts and
matplotlib simple line plots in Python.

Python Line chart in Matplotlib

Here, we will see some of the examples of a line chart in Python


using Matplotlib:

Matplotlib Simple Line Plot

In this example, a simple line chart is generated using NumPy to define data
values. The x-values are evenly spaced points, and the y-values are calculated
as twice the corresponding x-values.

# importing the required libraries


import [Link] as plt
import numpy as np
# define data values
x = [Link]([1, 2, 3, 4]) # X-axis points
y = x*2 # Y-axis points
[Link](x, y) # Plot the chart
[Link]() # display

Output:

Simple line plot between X and Y data

We can see in the above output image that there is no label on the x-axis and
y-axis. Since labeling is necessary for understanding the chart dimensions. In
the following example, we will see how to add labels, Ident in the charts.

import [Link] as plt


import numpy as np
# Define X and Y variable data
x = [Link]([1, 2, 3, 4])
y = x*2

Page No:- 185


[Link](x, y)
[Link]("X-axis") # add X-axis label
[Link]("Y-axis") # add Y-axis label
[Link]("Any suitable title") # add title
[Link]()

Output:

Simple line plot with labels and title

Line Chart with Annotations

In this example, a line chart is created using sample data points. Annotations
displaying the x and y coordinates are added to each data point on the line
chart for enhanced clarity.

import [Link] as plt

# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
# Create a line chart
[Link](figsize=(8, 6))
[Link](x, y, marker='o', linestyle='-')
# Add annotations
for i, (xi, yi) in enumerate(zip(x, y)):
[Link](f'({xi}, {yi})', (xi, yi), textcoords="offset points", xytext=(0,
10), ha='center')

# Add title and labels


[Link]('Line Chart with Annotations')
[Link]('X-axis Label')
[Link]('Y-axis Label')
# Display grid
[Link](True)
# Show the plot
[Link]()

Output:

Page No:- 186


Multiple Line Charts Using Matplotlib

We can display more than one chart in the same container by


using [Link]() function. This will help us in comparing the different
charts and also control the look and feel of charts.

import [Link] as plt


import numpy as np
x = [Link]([1, 2, 3, 4])
y = x*2
[Link](x, y)
[Link]("X-axis")
[Link]("Y-axis")
[Link]("Any suitable title")

[Link]() # show first chart


# The figure() function helps in creating a
# new figure that can hold a new chart in it.
[Link]()
x1 = [2, 4, 6, 8]
y1 = [3, 5, 7, 9]
[Link](x1, y1, '-.')
# Show another chart with '-' dotted line
[Link]()

Output:

Page No:- 187


Multiple Plots on the Same Axis

Here, we will see how to add 2 plots within the same axis.

import [Link] as plt


import numpy as np
x = [Link]([1, 2, 3, 4])
y = x*2
# first plot with X and Y data
[Link](x, y)
x1 = [2, 4, 6, 8]
y1 = [3, 5, 7, 9]
# second plot with x1 and y1 data
[Link](x1, y1, '-.')
[Link]("X-axis data")
[Link]("Y-axis data")
[Link]('multiple plots')
[Link]()

Output:

Fill the Area Between Two Lines

Using the pyplot.fill_between() function we can fill in the region between


two line plots in the same graph. This will help us in understanding the margin
of data between two line plots based on certain conditions.

import [Link] as plt


import numpy as np
x = [Link]([1, 2, 3, 4])
y = x*2
[Link](x, y)
x1 = [2, 4, 6, 8]
y1 = [3, 5, 7, 9]
[Link](x, y1, '-.')
[Link]("X-axis data")
[Link]("Y-axis data")
[Link]('multiple plots')
plt.fill_between(x, y, y1, color='green', alpha=0.5)
[Link]()

Page No:- 188


Output:

Fill the area between Y and Y1 data corresponding to X-axis data


**************************************
Bar Plot in Matplotlib

A bar plot uses rectangular bars to represent data categories, with bar length
or height proportional to their values. It compares discrete categories, with
one axis for categories and the other for values.
Consider a simple example where we visualize the sales of different fruits:

import [Link] as plt


import numpy as np
fruits = ['Apples', 'Bananas', 'Cherries', 'Dates']
sales = [400, 350, 300, 450]
[Link](fruits, sales)
[Link]('Fruit Sales')
[Link]('Fruits')
[Link]('Sales')
[Link]()

Output:

Simple bar plot for fruits sales

Page No:- 189


What is a Bar Plot?

A bar plot (or bar chart) is a graphical representation that uses rectangular
bars to compare different categories. The height or length of each bar
corresponds to the value it represents. The x-axis typically shows the
categories being compared, while the y-axis shows the values associated with
those categories. This visual format makes it easy to compare quantities
across different groups.

This function takes several parameters:

x: The categories (e.g., fruits).


height: The corresponding values (e.g., sales).
width: The width of the bars (default is 0.8).
bottom: The baseline for the bars (default is 0).
align: How to align bars (‘center’ or ‘edge’)

Why Use Bar Plots?

Bar plots are significant because they provide a clear and intuitive way to
visualize categorical data. They allow viewers to quickly grasp differences in
size or quantity among categories, making them ideal for presenting survey
results, sales data, or any discrete variable comparisons.

Syntax: [Link](x, height, width, bottom, align)


Customizing Bar Colors

You can customize the color of the bars by using the color parameter in
the bar() function:

import [Link] as plt


import numpy as np
fruits = ['Apples', 'Bananas', 'Cherries', 'Dates']
sales = [400, 350, 300, 450]
[Link](fruits, sales, color='violet')
[Link]('Fruit Sales')
[Link]('Fruits')
[Link]('Sales')
[Link]()

Output:

Page No:- 190


Changed color to Violet

Creating Horizontal Bar Plots

For horizontal bar plots, you can use the barh() function. This function works
similarly to bar(), but it displays bars horizontally:

import [Link] as plt


import numpy as np
fruits = ['Apples', 'Bananas', 'Cherries', 'Dates']
sales = [400, 350, 300, 450]
[Link](fruits, sales)
[Link]('Fruit Sales')
[Link]('Fruits')
[Link]('Sales')
[Link]()

Output:

Horizontal Plots

Page No:- 191


Adjusting Bar Width

You can control the width of the bars using the width parameter:

import [Link] as plt


import numpy as np
fruits = ['Apples', 'Bananas', 'Cherries', 'Dates']
sales = [400, 350, 300, 450]
[Link](fruits, sales, width=0.3)
[Link]('Fruit Sales')
[Link]('Fruits')
[Link]('Sales')
[Link]()

Output:

bar plot with low width()

Multiple bar plots

Multiple bar plots are used when comparison among the data set is to be done
when one variable is changing. We can easily convert it as a stacked area bar
chart, where each subgroup is displayed by one on top of the others. It can be
plotted by varying the thickness and position of the bars. Following bar plot
shows the number of students passed in the engineering branch:

import numpy as np
import [Link] as plt
barWidth = 0.25
fig = [Link](figsize =(12, 8))
IT = [12, 30, 1, 8, 22]
ECE = [28, 6, 16, 5, 10]
CSE = [29, 3, 24, 25, 17]
br1 = [Link](len(IT))
br2 = [x + barWidth for x in br1]
br3 = [x + barWidth for x in br2]
[Link](br1, IT, color ='r', width = barWidth,
Page No:- 192
edgecolor ='grey', label ='IT')

[Link](br2, ECE, color ='g', width = barWidth,


edgecolor ='grey', label ='ECE')
[Link](br3, CSE, color ='b', width = barWidth,
edgecolor ='grey', label ='CSE')
[Link]('Branch', fontweight ='bold', fontsize = 15)
[Link]('Students passed', fontweight ='bold', fontsize = 15)

[Link]([r + barWidth for r in range(len(IT))],


['2015', '2016', '2017', '2018', '2019'])
[Link]()
[Link]()

Output:

Stacked bar plot

Stacked bar plots represent different groups on top of one another. The height
of the bar depends on the resulting height of the combination of the results of
the groups. It goes from the bottom to the value instead of going from zero to
value. The following bar plot represents the contribution of boys and girls in
the team.

import numpy as np
import [Link] as plt
N=5
boys = (20, 35, 30, 35, 27)
girls = (25, 32, 34, 20, 25)
boyStd = (2, 3, 4, 1, 2)
girlStd = (3, 5, 2, 3, 3)
ind = [Link](N)
width = 0.35
Page No:- 193
fig = [Link](figsize =(10, 7))
p1 = [Link](ind, boys, width, yerr = boyStd)

p2 = [Link](ind, girls, width,

bottom = boys, yerr = girlStd)


[Link]('Contribution')
[Link]('Contribution by the teams')
[Link](ind, ('T1', 'T2', 'T3', 'T4', 'T5'))
[Link]([Link](0, 81, 10))
[Link]((p1[0], p2[0]), ('boys', 'girls'))
[Link]()

Output:

**********************************************

Plotting Histogram in Python using Matplotlib

A Histogram represents data provided in the form of some groups. It is an


accurate method for the graphical representation of numerical data
distribution. It is a type of bar plot where the X-axis represents the bin ranges
while the Y-axis gives information about frequency.

Creating a Matplotlib Histogram

To create a Matplotlib histogram the first step is to create a bin of the ranges,
then distribute the whole range of the values into a series of intervals, and
count the values that fall into each of the intervals. Bins are identified as
consecutive, non-overlapping intervals of
[Link] [Link]() function is used to compute and
create a histogram of x.

Page No:- 194


The following table shows the parameters accepted by [Link]()
function :

Attribute Parameter

x array or sequence of array

bins optional parameter contains integer or sequence or strings

density Optional parameter contains boolean values

range Optional parameter represents upper and lower range of bins

optional parameter used to create type of histogram [bar,


histtype
barstacked, step, stepfilled], default is “bar”

optional parameter controls the plotting of histogram [left,


align
right, mid]

optional parameter contains array of weights having same


weights
dimensions as x

bottom location of the baseline of each bin

optional parameter which is relative width of the bars with


rwidth
respect to bin width

color optional parameter used to set color or sequence of color specs

optional parameter string or sequence of string to match with


label
multiple datasets

log optional parameter used to set histogram axis on log scale

Plotting Histogram in Python using Matplotlib


Here we will see different methods of Plotting Histogram in Matplotlib
in Python:

Basic Histogram

Customized Histogram with Density Plot


Customized Histogram with Watermark
Multiple Histograms with Subplots
Stacked Histogram
Page No:- 195
2D Histogram (Hexbin Plot)
Create a Basic Histogram in Matplotlib

Let’s create a basic histogram in Matplotlib using Python of some random


values.

Python3

import [Link] as plt


import numpy as np

# Generate random data for the histogram


data = [Link](1000)

# Plotting a basic histogram


[Link](data, bins=30, color='skyblue', edgecolor='black')

# Adding labels and title


[Link]('Values')
[Link]('Frequency')
[Link]('Basic Histogram')

# Display the plot


[Link]()

Output:

Customized Histogram in Matplotlib with Density Plot

Let’s create a customized histogram with a density plot using Matplotlib and
Seaborn in Python. The resulting plot visualizes the distribution of random data
with a smooth density estimate.
Python3

Page No:- 196


import [Link] as plt
import seaborn as sns
import numpy as np

# Generate random data for the histogram


data = [Link](1000)

# Creating a customized histogram with a density plot


[Link](data, bins=30, kde=True, color='lightgreen', edgecolor='red')

# Adding labels and title


[Link]('Values')
[Link]('Density')
[Link]('Customized Histogram with Density Plot')

# Display the plot


[Link]()

Output:

Customized Histogram with Watermark


Create a customized histogram using Matplotlib in Python with specific
features. It includes additional styling elements, such as removing axis ticks,
adding padding, and setting a color gradient for better visualization.

Python3

import [Link] as plt


import numpy as np
from matplotlib import colors
from [Link] import PercentFormatter

# Creating dataset
[Link](23685752)
N_points = 10000
n_bins = 20

Page No:- 197


# Creating distribution
x = [Link](N_points)

y = .8 ** x + [Link](10000) + 25
legend = ['distribution']

# Creating histogram
fig, axs = [Link](1, 1,
figsize =(10, 7),
tight_layout = True)

# Remove axes splines


for s in ['top', 'bottom', 'left', 'right']:
[Link][s].set_visible(False)

# Remove x, y ticks
[Link].set_ticks_position('none')
[Link].set_ticks_position('none')

# Add padding between axes and labels


[Link].set_tick_params(pad = 5)
[Link].set_tick_params(pad = 10)

# Add x, y gridlines
[Link](b = True, color ='grey',
linestyle ='-.', linewidth = 0.5,
alpha = 0.6)

# Add Text watermark


[Link](0.9, 0.15, 'Jeeteshgavande30',
fontsize = 12,
color ='red',
ha ='right',
va ='bottom',
alpha = 0.7)

# Creating histogram
N, bins, patches = [Link](x, bins = n_bins)

# Setting color
fracs = ((N**(1 / 5)) / [Link]())
norm = [Link]([Link](), [Link]())

for thisfrac, thispatch in zip(fracs, patches):


color = [Link](norm(thisfrac))
thispatch.set_facecolor(color)

Page No:- 198


# Adding extra features
[Link]("X-axis")
[Link]("y-axis")
[Link](legend)

[Link]('Customized histogram')

# Show plot
[Link]()

Output :

Multiple Histograms with Subplots

Let’s generates two histograms side by side using Matplotlib in Python, each
with its own set of random data and provides a visual comparison of the
distributions of data1 and data2 using histograms.
Python3

import [Link] as plt


import numpy as np

# Generate random data for multiple histograms


data1 = [Link](1000)
data2 = [Link](loc=3, scale=1, size=1000)

# Creating subplots with multiple histograms


fig, axes = [Link](nrows=1, ncols=2, figsize=(12, 4))

axes[0].hist(data1, bins=30, color='Yellow', edgecolor='black')


axes[0].set_title('Histogram 1')

axes[1].hist(data2, bins=30, color='Pink', edgecolor='black')


axes[1].set_title('Histogram 2')

Page No:- 199


# Adding labels and title
for ax in axes:
ax.set_xlabel('Values')
ax.set_ylabel('Frequency')

# Adjusting layout for better spacing


plt.tight_layout()

# Display the figure


[Link]()

Output:

Stacked Histogram using Matplotlib

Let’s generates a stacked histogram using Matplotlib in Python, representing


two datasets with different random data distributions. The stacked histogram
provides insights into the combined frequency distribution of the two datasets.
Python3

import [Link] as plt


import numpy as np

# Generate random data for stacked histograms


data1 = [Link](1000)
data2 = [Link](loc=3, scale=1, size=1000)

# Creating a stacked histogram


[Link]([data1, data2], bins=30, stacked=True, color=['cyan', 'Purple'],
edgecolor='black')

# Adding labels and title


[Link]('Values')
[Link]('Frequency')
[Link]('Stacked Histogram')

# Adding legend
[Link](['Dataset 1', 'Dataset 2'])

Page No:- 200


# Display the plot
[Link]()

Output:

Plot 2D Histogram (Hexbin Plot) using Matplotlib

Let’s generates a 2D hexbin plot using Matplotlib in Python, provides a visual


representation of the 2D data distribution, where hexagons convey the density
of data points. The colorbar helps interpret the density of points in different
regions of the plot.
Python3

import [Link] as plt


import numpy as np

# Generate random 2D data for hexbin plot


x = [Link](1000)
y = 2 * x + [Link](size=1000)

# Creating a 2D histogram (hexbin plot)


[Link](x, y, gridsize=30, cmap='Blues')

# Adding labels and title


[Link]('X values')
[Link]('Y values')
[Link]('2D Histogram (Hexbin Plot)')

# Adding colorbar
[Link]()

# Display the plot

Page No:- 201


[Link]()

Output:

***********************
Matplotlib Scatter

[Link]() is used to create scatter plots, which are essential


for visualizing relationships between numerical variables. Scatter plots help
illustrate how changes in one variable can influence another, making them
invaluable for data analysis.
A basic scatter plot can be created using [Link]() by plotting
two sets of data points on the x and y axes:

import [Link] as plt


import numpy as np

4
x = [Link]([12, 45, 7, 32, 89, 54, 23, 67, 14, 91])
5
y = [Link]([99, 31, 72, 56, 19, 88, 43, 61, 35, 77])
6

7
[Link](x, y)
8
[Link]()

Output:

Page No:- 202


There are various ways of creating plots using [Link]() in
Python,

Scatter Plot with Multiple Datasets


In this example there seems to be a relationship between the height and
weight data of two distinct groups (Group 1 and Group 2) by plotting them on
a scatter plot, using different colors to differentiate between the groups.

Customizing Scatter Plots: Color and Size

Matplotlib allows full customization of scatter plots, including selecting the


color and size of data points.
Bubble Plots in Matplotlib
Bubble charts add a dimension of data by using the size of the data points to
represent additional information.

Advanced Customization in Scatter Plot: Size, Color, and Transparency


Matplotlib offers even more flexibility by allowing you to customize scatter
plots using random data, color maps, and alpha (transparency) for more
complex visualizations.
*************************
Pie Chart in Python

A Pie Chart is a circular statistical plot that can display only one series of data.
The area of the chart is the total percentage of the given data. Pie charts in
Python are widely used in business presentations, reports, and dashboards due
to their simplicity and effectiveness in displaying data distributions. In this
article, we will explore how to create a pie chart in Python using
the Matplotlib library, one of the most widely used libraries for data
visualization in Python.

Why Use Pie Charts?

Pie charts provide a visual representation of data that makes it easy to


compare parts of a whole. They are particularly useful when:
Displaying relative proportions or percentages.
Summarizing categorical data.
Highlighting significant differences between categories.

Basic Structure of a Pie Chart

A pie chart consists of slices that represent different categories. The size of
each slice is proportional to the quantity it represents. The following
components are essential when creating a pie chart in Matplotlib:

Data: The values or counts for each category.


Labels: The names of each category, which will be displayed alongside the
slices.

Page No:- 203


Colors: Optional, but colors can be used to differentiate between slices
effectively.
Plotting a Pie Chart in Matplotlib

# Import libraries
from matplotlib import pyplot as plt
import numpy as np

# Creating dataset
cars = ['AUDI', 'BMW', 'FORD',
'TESLA', 'JAGUAR', 'MERCEDES']

data = [23, 17, 35, 29, 12, 41]

# Creating plot
fig = [Link](figsize=(10, 7))
[Link](data, labels=cars)

# show plot
[Link]()

Output:

Customizing Pie Charts

Once you are familiar with the basics of pie charts in Matplotlib, you can start
customizing them to fit your needs. A pie chart can be customized on the basis
several aspects:

startangle: This attribute allows you to rotate the pie chart in


Python counterclockwise around the x-axis by the specified degrees.. By
adjusting this angle, you can change the starting position of the first wedge,
which can improve the overall presentation of the chart.

Page No:- 204


shadow: This boolean attribute adds a shadow effect below the rim of the pie.
Setting this to True can make your chart stand out and give it a more three-
dimensional appearance, enhancing the overall look of your pie chart in
Matplotlib.

wedgeprops: This parameter accepts a Python dictionary to customize the


properties of each wedge in the pie chart. You can specify various attributes
such as linewidth, edgecolor, and facecolor. This level of customization allows
you to enhance the visual distinction between wedges, making your matplotlib
pie chart more informative.

frame: When set to True, this attribute draws a frame around the pie chart.
This can help emphasize the chart’s boundaries and improve its visibility,
making it clearer when presenting data.

autopct: This attribute controls how the percentages are displayed on the
wedges. You can customize the format string to define the appearance of the
percentage labels on each slice.

Creating a Nested Pie Chart in Python


A nested pie chart is an effective way to represent hierarchical data, allowing
you to visualize multiple categories and subcategories in a single view.
In Matplotlib, you can create a nested pie chart by overlaying multiple pie
charts with different radii. Below, we’ll explore how to create this type of chart
in Python.

Page No:- 205


The outer pie chart represents the main categories, while the inner pie chart
represents subcategories related to one of those main categories. This
structure is particularly useful for showing proportions within proportions,
helping viewers quickly grasp the relationships within the data.

Center Circle: The centre_circle is added to create the donut effect, providing a
clean visual separation between the outer and inner pie charts.

Creating 3D Pie Charts

To create a proper 3D pie chart in Matplotlib, you can use the following code
snippet. Note that Matplotlib does not have a direct function for 3D pie
charts, but we can simulate it with a 3D surface plot or use a workaround
with 2D pie charts:

****************************************
Connect Python with SQL Database

Python is a high-level, general-purpose, and very popular programming


language. Basically, it was designed with an emphasis on code readability, and
programmers can express their concepts in fewer lines of code. We can also
use Python with SQL. we will learn how to connect SQL with Python using the
‘MySQL Connector Python module. The diagram given below illustrates how a

Page No:- 206


connection request is sent to MySQL connector Python, how it gets accepted
from the database and how the cursor is executed with result data.

*******************************************
How do you import MySQL, in Python for database connectivity?

Database connectivity is a crucial aspect of modern applications, allowing them


to interact with databases for storing, retrieving, and manipulating data. In
Python, one of the most popular databases is MySQL, and various libraries
facilitate connecting Python applications to MySQL databases. The two most
commonly used libraries for MySQL database connectivity in Python are mysql-
connector-python and PyMySQL

installing MySQL Connector:

Before you can use MySQL in Python, you need to install the appropriate
MySQL connector library. This can be done easily via pip, Python's package
manager. Below are the steps to install and use the MySQL connector.

1. Install the MySQL. Connector: Open your terminal or command prompt and
run one of the following commands:

For mysql-connector-python:

pip install mysql-connector-python

For PyMySQL:

pip install pymysql

These commands will install the necessary libraries that allow you to connect
to and interact with a MySQL database from your Python scripts.

*************************

Page No:- 207


Importing the MySQL Connector:

1. After successfully installing the library, you can import it into your Python
script to establish a connection to a MySQL database.

2. Using mysql-connector-python: Here's how to import and use the


mysql- connector-python library:

import [Link]

3. Connecting to the Database: Next, create a connection to the MySQL


database by specifying the connection parameters, such as host, user,
password, and database name.

connection [Link](
host 'localhost', or your database server
user your username',
password your password",
database your database')

If the connection is successful, the connection object will be created without


throwing an error

4. Creating a Curser Object: Once connected, you need a cursor object to


execute SQL queries. The cursor allows you to interact with the database.

cursor [Link]()

5. Executing Queries: You can now execute SQL queries using the cursor. For
example, to retrieve data from a table:
[Link]("SELECT FROM your_table")

results [Link]()
# Fetch all results
for row in results:

print(row)

6. Cloning the Connections After completing your operations, it's essential to


close the cursor and the connection to free up resources.

[Link]()

[Link]()
***************************************************************

Page No:- 208


Complete Example Code:

Here's a complete example demonstrating how to connect to a MySQL


database using

mysql-connector-python:

import [Link]

#Establish a connection to the database

connection [Link](

host-localhost,
user=your_username',

password='your_password",

database 'your database'

#Create a cursor object cursor [Link]()

#Execute a query

[Link]("SELECT FROM your_table")

results [Link]()

# Display the results for row in results:

print(row)

Close the cursor and connection

[Link]()

[Link]()

*****************************
Connect MySQL database using MySQL-Connector Python

While working with Python we need to work with databases, they may be of
different types like MySQL, SQLite, NoSQL, etc. In this article, we will be
looking forward to how to connect MySQL databases using MySQL
Connector/Python.

Page No:- 209


MySQL Connector module of Python is used to connect MySQL databases with
the Python programs, it does that using the Python Database API Specification
v2.0 (PEP 249). It uses the Python standard library and has no dependencies.

Connecting to the Database


The [Link] provides the connect() method used to create a
connection between the MySQL database and the Python application. The
syntax is given below.
Syntax:
Conn_obj= [Link](host = <hostname>, user =
<username>, passwd = <password>)

The connect() function accepts the following arguments.


Hostname – It represents the server name or IP address on which MySQL is
running.
Username – It represents the name of the user that we use to work with the
MySQL server. By default, the username for the MySQL database is root.
Password – The password is provided at the time of installing the MySQL
database. We don’t need to pass a password if we are using the root.
Database – It specifies the database name which we want to connect. This
argument is used when we have multiple databases.

In the following example we will be connecting to MySQL database using


connect()
Example:
# Python program to connect
# to mysql database

import [Link]

# Connecting from the server


conn = [Link](user = 'username',
host = 'localhost',
database = 'database_name')

print(conn)

# Disconnecting from the server


[Link]()

Page No:- 210


Output:

Another way is to pass the dictionary in the connect() function using ‘**’
operator:
Example:
# Python program to connect
# to mysql database

from [Link] import connection

dict = {
'user': 'root',
'host': 'localhost',
'database': 'College'
}

# Connecting to the server


conn = [Link](**dict)

print(conn)

# Disconnecting from the server


[Link]()

# importing required libraries


import [Link]

dataBase = [Link](
host ="localhost",
user ="user",
passwd ="gfg"
)
# preparing a cursor object
cursorObject = [Link]()
# creating database
[Link]("CREATE DATABASE geeks4geeks")

Page No:- 211


********************************
Common MySQL Queries

MySQL server is a open-source relational database management system which


is a major support for web based applications. Databases and related tables
are the main component of many websites and applications as the data is
stored and exchanged over the web. Even all social networking websites
mainly Facebook, Twitter, and Google depends on MySQL data which are
designed and optimized for such purpose. For all these reasons, MySQL server
becomes the default choice for web applications.
MySQL server is used for data operations like querying, sorting, filtering,
grouping, modifying and joining the tables. Before learning the commonly used
queries, let us look into some of the advantages of MySQL.

Advantages of MySQL :

Fast and high Performance database.


Easy to use, maintain and administer.
Easily available and maintain integrity of database.
Provides scalability, usability and reliability.
Low cost hardware.
MySQL can read simple and complex queries and write operations.
InnoDB is default and widely used storage engine.
Provides strong indexing support.
Provides SSL support for secured connections.
Provides powerful data encryption and accuracy.
Provides Cross-platform compatibility.
Provides minimized code repetition.

Queries can be understood as the commands which interacts with database


tables to work around with data.

Some of the commonly used MySQL queries, operators, and functions are as
follows :

Page No:- 212


1. SHOW DATABASES
This displays information of all the existing databases in the server.
Output:

2. USE database_name
database_name : name of the database
This sets the database as the current database in the MySQL server.
To display the current database name which is set, use syntax
SELECT DATABASE();

3. DESCRIBE table_name

table_name : name of the table


This describes the columns of the table_name with respect to Field, Type, Null,
Key, Default, Extra.

4. SHOW TABLES
This shows all the tables in the selected database as a information.

5. SHOW CREATE TABLE table_name


table_name : name of the table
This shows the complete CREATE TABLE statement used by MySQL for creating
the table.

6. SELECT NOW()
MySQL queries mostly starts with SELECT statement.
This query shows the current date and time.

Output :
2019-09-24 07:08:30

7. SELECT 2 + 4;
Output :
6

This executes SELECT statement without any table.


SELECT can be used for executing an expression or evaluating an in-built
function.
SELECT can also be used for more than one or many columns.

Page No:- 213


Example :

SELECT 2+4, CURDATE();


Output :

8. Comments
Comments are of two types. Multi-line comments or single-line or end-of-line
comment.
/* These are multi-line comments. */
# This is single-line comment.
-- This is also single-line comment.

9. CREATE DATABASE database_name


database_name : name of the database
This statement creates a new database.

10. DROP DATABASE database_name


database_name : name of the database
This statement deletes the database.
Note : User has to be very careful before deleting a database as it will lose all
the crucial information stored in the database.
11. CREATE TABLE table_name(column1, column2, column3..)
table_name : name of the table
column1 : name of first column
column2 : name of second column
column3 : name of third column
When the developer start building an application, he needs to create database
tables.
This statement creates a new table with the given columns.
Example :
CREATE TABLE employee('id' INTEGER NOT NULL AUTO_INCREMENT,'name'
VARCHAR(30) NOT NULL,'profile' VARCHAR(40) DEFAULT 'engineer',
PRIMARY KEY ('id')ENGINE = InnoDB;
Note : You have ‘id’ column as AUTO_INCREMENT with a primary key
constraint which ensures that each id is incremented value, avoiding
duplication. Storage engine selected is ‘InnoDB’ allowing foreign key constraint
and related transactions.

Page No:- 214


12. AUTO_INCREMENT
It is used to generate a unique identification field for new row.

13. DROP TABLE table_name


table_name : name of the table
This statement deletes the mentioned table.

14. RENAME TABLE old_table_name TO new_table_name


old_table_name : name of the previous table.
new_table_name : name of the new table.
This statement renames the table to a new name.

15. ALTER TABLE table_name ADD(column1, column2, column3..)


table_name : name of the existing table.
column1 : name of first column.
column2 : name of second column.
column3 : name of third column.
This statement adds columns to the existing table.

16. ALTER TABLE table_name DROP(column1)


table_name : name of the existing table.
column1 : name of first column.
This statement deletes specified columns from the existing table.

17. INSERT INTO table_name (column1, column2, column3 . . )


VALUES(value1, value2, value3 . . )
table_name : name of the existing table.
column1 : name of first column.
column2 : name of second column.
column3 : name of third column.
value1 : value for first column.
value2 : value for second column.
value3 : value for third column.
This statement inserts a new record into a table with specified values.

18. UPDATE table_name SET column1 = value1, column2 = value2,


column3 = value3.. WHERE condition
table_name : name of the table.
column1 : name of first column.
column2 : name of second column.
column3 : name of third column.
value1 : value for first column.

Page No:- 215


value2 : value for second column.
value3 : value for third column.

condition : the condition statement.


This statement update records in the table with the new given values for the
columns.
Note : WHERE clause in MySQL queries is used to filter rows for a specific
condition.

19. DELETE FROM table_name WHERE condition


table_name : name of the table.
condition : the condition statement.
This statement deletes records from the table.

20. SELECT column1, column2, column3.. FROM table_name WHERE


condition
table_name : name of the table.
column1 : name of first column.
column2 : name of second column.
column3 : name of third column.
condition : the condition statement.
This statement executes and gives records from specific columns from the
table which matches the condition after WHERE clause.

21. SELECT * FROM table_name


table_name: name of the table.
Instead of specifying one column or many columns, you can use an asterisk
(*) which represents all columns of table. This query retrieves all records from
the table.

22. COUNT
The COUNT function is used to return total number of records matching a
condition from any table.
It is one of the known AGGREGATE function.
Example :
SELECT COUNT(*) from student;
Note: AGGREGATE functions allow you to run calculations on data and provide
information by using
a SELECT query.

23. MAX
It is used to get the maximum numeric value of a particular column of table.
Example :
SELECT MAX(marks) FROM student_report;

Page No:- 216


Note: The MIN and MAX functions work correctly on numeric as well as
alphabetic values.

24. MIN
It is used to get the minimum numeric value of a particular column of table.
Example :
SELECT MIN(marks) FROM student_report;
Note : The above given example queries can also be nested with each other
depending on the requirementExample :
SELECT MIN(marks)
FROM student_report
WHERE marks > ( SELECT MIN(marks) from student_report);

25. LIMIT
It is used to set the limit of number of records in result set.
Example :
SELECT *
FROM student limit 4, 10;
This gives 10 records starting from the 5th record.

26. BETWEEN
It is used to get records from the specified lower limit to upper limit.
This verifies if a value lies within that given range.
Example :
SELECT * FROM employee
WHERE age BETWEEN 25 to 45.

27. DISTINCT
This is used to fetch all distinct records avoiding all duplicate ones.
Example :
SELECT DISTINCT profile
FROM employee;

28. IN clause
This verifies if a row is contained in a set of given values.
It is used instead of using so many OR clause in a query.
Example :
SELECT *
FROM employee
WHERE age IN(40, 50, 55);

29. AND
This condition in MySQL queries are used to filter the result data based on AND
conditions.
Example :

Page No:- 217


SELECT NAME, AGE
FROM student
WHERE marks > 95 AND grade = 7;

30. OR
This condition in MySQL queries are used to filter the result data based on OR
conditions.
Example :
SELECT *
FROM student
WHERE address = 'Hyderabad' OR address = 'Bangalore';

31. IS NULL
This keyword is used for boolean comparison or to check if the data value of a
column is null.
Example :
SELECT * FROM employee WHERE contact_number IS NULL;

32. FOREIGN KEY


It is used for pointing a PRIMARY KEY of another table.
Example :
CREATE TABLE Customers
(
id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(30) NOT NULL,
)

CREATE TABLE Orders


(
order_id INT AUTO_INCREMENT PRIMARY KEY, FOREIGN KEY (id)
REFERENCES Customers(id)
);
Note: This is not used in the MYISAM storage engine of MySQL server.
InnoDB storage engines supports foreign key constraints.

33. LIKE
This is used to fetch records matching for specified string pattern.
Example :
SELECT * FROM employee WHERE name LIKE 'Sh%';

SELECT * FROM employee WHERE name LIKE '%Sh%';


Note: Percentage signs (%) in the query represent zero or more characters.

34. JOINS
Joins are the joining of two or more database tables to fetch data based on a
common field.
There are various types of joins with different names in different databases.
Commonly known joins are self join, outer join, inner join and many more.

Page No:- 218


Regular Join :
It is the join which gets all the records from both the tables which exactly
match the given condition.

Example :
SELECT [Link], [Link]
FROM student JOIN department ON [Link] = [Link]
Left Join :
It is the join which gets all the records that match the given condition, and
also fetch all the records from
the left table.

Example :
SELECT [Link], [Link]
FROM student LEFT JOIN department ON [Link] =
[Link]
Right Join :
It is the join which gets all the records that match the given condition, and
also fetch all the records from the right table.

Example :
SELECT [Link], [Link]
FROM student RIGHT JOIN department on [Link] =
[Link]

35. ADD or DROP a column


A new column can be added on a database table, if required later on.
Example :
ALTER TABLE employee ADD COLUMN salary VARCHAR(25);
Similarly, any column can be deleted from a database table.
Example :
ALTER TABLE employee DROP COLUMN salary;

************************************************

passing a query to mysql in python

Interacting with a MySQL database from Python involves passing SQL queries
to the database and retrieving the results. Python's mysql-connector-python
library makes it easy to establish a connection to a MySQL database, execute
queries, and fetch results. This process typically includes creating a
connection, creating a cursor to execute SQL commands, fetching the results,

and finally closing the connection. Below is a step-by-step guide on how to


pass an SQL query to MySQL and fetch the results using Python.
Steps to Execute an SQL. Query and Fetch Results:

Page No:- 219


1. Install the MySQL. Connector: Before you start, ensure that the mysql-
connector- python library is installed. If it is not installed, you can use pip to
install it:

pip install mysql-connector-python

2. Importing the Connector: After installation, import the MySQL connector


into your Python script:

import [Link]

3 Establishing a Connection: Create a connection to your MySQL database


by specifying the necessary connection parameters such as host, user,
password, and database name.

connection [Link](

host-localhost', #Database server address

user your_username', # Your MySQL username

password='your_password", # Your MySQL password

database your_database # The database you want to use)

4. Creating a Cursor: A cursor is required to execute SQL queries. Create a


cursor object using the connection you established.

cursor [Link]()

5. Writing an SQL Query: Write the SQL query you want to execute. For
example, if you want to retrieve all records from a table named employees,
your SQL query would look like this: sql query "SELECT FROM employees;"

6. Executing the Query: Use the cursor to execute the SQL query. The
execute() method runs the SQL command you defined.

[Link](sql_query)

7. Fetching the Results: After executing the query, you can fetch the results
using one of the following methods:

fetchall(): Fetches all rows returned by the query.

fetchone(): Fetches the next row from the result set.

fetchmany(size): Fetches the specified number of rows.

Page No:- 220


For example, to fetch all results:

results [Link]()

8. Processing the Results: You can loop through the fetched results and
print them or perform further processing as needed.

for row in results:

print(row)

9. Closing the Cursor and Connection: After completing your database


operations, it is essential to close both the cursor and the connection to free
up resources. [Link]()

[Link]()
************************************************************

Page No:- 221

You might also like