Python Programming
Python Programming
UNIT I
UNIT IV
UNIT V
Page No:- 1
Introduction To Python
****************
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.
Output:
Page No:- 4
Note: To exit from this mode, press ‘Ctrl+Z’ and then press ‘Enter’ or type
‘exit()’ and then press Enter.
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.
***************************************
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)
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()
*********************************************
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
*****************************************************
Page No:- 10
Example:
def change():
# 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:
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
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.
Example: The code is an example of how to create sets using different types
of values, such as strings , lists , and mixed values
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.
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.
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.
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.
and Logical AND: True if both the operands are true x and y
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.
| Bitwise OR x|y
~ Bitwise NOT ~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.
Page No:- 21
Operator Description Syntax
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
********************************************
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
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.
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
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
print("Hello, World!")
Output
Hello, World!
name = "Mynu"
age = 30
print("Name:", name, "Age:", age)
output:
Name: Mynu Age: 30
***************
Output Formatting
Page No:- 26
Example 1: Using Format()
amount = 150.75
print("Amount: ${:.2f}".format(amount))
Output
Amount: $150.75
*******************
# 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
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
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
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.
***************************
Python - Control Flow
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
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)
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'))
Vowel alphabet
Simple alphabet
Vowel alphabet
Page No:- 32
Loops or Iteration Statements
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 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)
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
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
Page No:- 34
# continue when letter is 'h'
if letter == "h":
continue
print("Current Letter :", letter)
if 10 > 5:
print("This is true!")
print("I am tab 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:
Output
10 greater than 5
Program ended
******************************************************
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:
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")
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:
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
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"
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
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
!
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():
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
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
Output
POOJA
string ="MYNUDDINS-S"
casefold()
print("lowercase string: ", [Link]())
Output:
lowercase string: mynuddin-s
string ="Mynuddin-s"
new_string =[Link](24)
center()
print("After padding String is: ", new_string)
Output:
After padding String is: mynuddin-s
my_string = "Apple"
count() char_count =
my_string.count('A')
print(char_count)
Output
Page No:- 48
Function
Name Description
Output:
Center
Output:
Page No:- 49
Function
Name Description
string = 'random'
index()
print("index of 'and' in string:", [Link]('and'))
Output
Index of 'and' in string: 1
string ="abc123"
isalnum()
print([Link]())
Output:
True
string ="geeks"
isalpha() print([Link]())
Output: True
print("100".isdecimal())
isdecimal()
Output
True
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
print("geeks".islower())
islower()
Output:
True
string ="123456789"
isnumeric() result =[Link]()
print(result)
Output:
True
Output:
True
False
True
Output:
Page No:- 51
Function
Name Description
True
string ="Geeks"
istitle() print([Link]())
Output:
True
print(("GEEKS").isupper())
isupper()
Output:
True
string ='geeks'
length =8
fillchar ='*'
ljust()
print([Link](length, fillchar))
Output:
***geeks
Output
convert all to lowercase
Page No:- 52
Function
Name Description
Output:
geeksforgeeks
maketrans(
Returns a translation table.
)
Output:
('I love Geeks ', 'for', ' geeks')
Output
Good Bye World
string ="GeeksForGeeks"
rfind() print([Link]("Geeks"))
Output:
8
rindex() Returns the highest index of the substring inside the string
rsplit() Split the string from the right by the specified separator
Page No:- 53
Function
Name Description
startswith(
Returns “True” if a string starts with the given prefix
)
strip() Returns the string with both leading and trailing characters
Output
LIST UPPER
************************
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.
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.
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.
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.
Page No:- 56
Function Name Description
Python
Returns a class method for a given function
classmethod()
Page No:- 57
Function Name Description
string
Python
Returns immutable frozenset
frozenset()
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()
Page No:- 58
Function Name Description
Python
Returns memory view of an argument
memoryview()
Page No:- 59
Function Name Description
Python
Converts a message into the static message
staticmethod()
Python
Imports the module during runtime
import ()
Page No:- 60
Working of all() with Lists
# All elements of list are true
l = [4, 5, 1]
print(all(l))
Output
True
False
***************
Python any() Function Example
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
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
*************
# sequence
sequence = ['g', 'e', 'e', 'j', 'k', 's', 'p', 'r']
input() Function
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
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.
def f():
# local variable
s = "I love Geeksforgeeks"
print(s)
# Driver code
f()
Output
I love Geeksforgeeks
************************
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:
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.
# 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):
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.
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.
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.
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.
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.
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.
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.
**************
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
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 *
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]()
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
Page No:- 82
Function Name Description
Page No:- 83
Function Name Description
object
Page No:- 84
Function Name Description
*********************************************
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
import math
x = 33.7
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
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
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
Page No:- 87
Function
Name Description
Page No:- 88
Function
Name Description
atan2(y,
Returns atan(y / x)
x)
hypot(x,
Returns the hypotenuse of the values passed in arguments
y)
degrees(x
Convert argument value from radians to degrees
)
Page No:- 89
Function
Name Description
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.
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.
Page No:- 92
Exception Name Description
Page No:- 93
Exception Name Description
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.
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.
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.
- 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.
- 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)
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.
Output
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): ")
**************************
- 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:
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:
**********************
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()
**********************
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:
**********************
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:
**********************
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.
length = len(list)
for i in range(length):
print(list[i])
Output:
10
******************************
List Comprehension
OUTPUT
10
**************************
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.
list = [1, 3, 5, 7, 9]
# Using enumerate()
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
The lambda function along with a Python map() function can come in use for
traversing lists easily.
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]
********************************
a = [Link](9)
# and 4 columns
a = [Link](3, 3)
# iterating an array
for x in [Link](a):
print(x)
OUTPUT
8
***************************
length = len(list)
i=0
print(list[i])
i += 1
OUTPUT
10
*********************************
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
append():
Syntax: list_name.append(element)
a = [1, 2, 3]
Output
[1, 2, 3, 4]
****************
Syntax: list_name.copy()
a = [1, 2, 3]
Output
[1, 2, 3]
***************
clear():
Syntax: list_name.clear()
a = [1, 2, 3]
Output
[]
******************
Count():
Syntax: list_name.count(element)
a = [1, 2, 3, 2]
Output
[1, 2, 3, 4]
*****************
Output
[1, 2, 3]
*************************
pop():
Syntax: list_name.pop(index)
a = [1, 2, 3]
Function
Name Description
Python
used for getting the next item from an asynchronous iterator
anext()
Function
bin() x =bin(42)
Function print(x)
output: 0b101010
Python
breakpoin It is used for dropping into the debugger at the call site during
t() runtime for debugging purposes
Function
return5
# a test variable
num =5*5
print(callable(num))
Output
True
False
@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')
Python
Creates Complex Number
complex(
print(complex(1, 2))
)
Output:(1+2j)
Function
classEquation:
x =3
y =-8
z =5
l1 =Equation()
Output
Value of x = 3
Value of y = -8
Value of z = 5
Value of x = 3
ERROR!
Traceback (most recent call last):
Python
dir() Returns a list of the attributes and methods of any object
Function
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)
Python
frozenset
Returns immutable frozenset
()
Function
calc = Calculator()
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')))
Output:
Does name exist ? True
Output: 0x3e7
z =42
print(id(x))
print(id(y)) # (same as x)
print(id(z)) # (same as x and y)
Output : 140642115230496
140642115230496
140642115230496
numbers =[1, 2, 3, 4, 2, 5]
s2 = ""
Python
print(len(s2))
len()
Function
s3 = "a"
print(len(s3))
Output: 4
0
1
# driver code
demo1()
demo2()
Output: Here no local variable is present : {}
Here local variables are present : {'name': 'Ankit'}
var1 =4
Python var2 =8
max() var3 =2
Function
max_val =max(var1, var2, var3)
print(max_val)
Output: 8
Output: 88
b'X'
Python =[1, 2, 3]
next() l_iter =iter(l)
Function print(next(l_iter))
Output: 1
created_file =open("[Link]","x")
Python
open()
# Check the file
Function
print(open("[Link]","r").read() ==False)
Output:False
print(ord('2'))
Python print(ord('g'))
ord() print(ord('&'))
Function
Output :50
103
38
class Alphabet:
def init (self, value):
self._value = value
[Link] = 'GfG'
del [Link]
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
s = set()
print("Type of s is ",type(s))
Output: Type of s is <class 'set'>
classPerson:
def init (self):
Python pass
setattr()
Function p =Person()
setattr(p, 'name', 'kiran')
print(f"name: {[Link]}")
Output: World
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:<class '[Link]'>
***********************************************************
Tuples in Python
print(t)
print(type(t))
Output
(10, 20, 30)
<class 'tuple'>
****************
Output:
('Geeks', 'for', 'Geeks')
******************
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')
*****************************************
To create a tuple with a Tuple constructor, we will pass the elements as its
parameters.
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
Output:
Value in Var[0] = Geeks
Value in Var[1] = for
Value in Var[2] = Geeks
*****************************
var = (1, 2, 3)
Output:
Value in Var[-1] = 3
Value in Var[-2] = 2
Value in Var[-3] = 1
*******************************************
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
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
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.
***************************************************
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().
>>>tup
>>> tup2
()
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
>>> [Link](22)
>>> [Link](54)
**********************
The index() Function
>>> print([Link](45))
>>> print([Link](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
>>> max(tup)
890
max(): gives the sum of the elements present in the tuple as an output.
For example,
Copy Code
>>> sum(tup)
1023
********************************
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].
Output:
((10, 'Itika', 13000),)
((10, 'Itika', 13000), (24, 'Harry', 15294), (15, 'Naill', 20001), (40, 'Peter',
16395))
***********************************************
Dictionaries in Python
Output
Note – Dictionary keys are case sensitive, the same name but different cases
of Key will be treated distinctly.
print(Dict)
Output
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'}
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'
**********************************************
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
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}
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():
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}
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
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
*********************************************************
Name Example
******************
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]]]
****************
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
Output
Gee
ek
!seGrf
*************************
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:
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.
Example:
[Link]([1, 2, 3, 4, 5, 6])
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.
[Link](mat, mat2)
#Output:
#[[1922]
# [43.50]]
total [Link](arr)
print(total)#Output: 15
These functions are useful for statistical analysis and summarizing data.
result = arr>3
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
# printing array
print("Array : " + str(array))
# length of array
n = [Link]
# calculating M
M = n//N
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)
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]()
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).
import numpy as np
mean()
Calculates mean of all the elements of the NumPy array, irrespective of the
shape of the array.
Output will be
6.766666666666667
var()
25.855555555555554
std()
min()
-2.5
max()
12.0
sum()
40.6
prod()
-71610.0
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
# 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
**************************************
Libraries in Python
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.
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.
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.
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.
Example
# Importing math library
import math
A = 16
print([Link](A))
output
Output
4.0
Output
4.0
0.0015926529164868282
********************************************
# 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
ser = [Link](data)
print(ser)
Output
0 g
1 e
2 e
3 k
4 s
dtype: object
***********************
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.
Output
0 g
1 e
2 e
3 k
4 s
dtype: object
******************************
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.
df = pd.read_csv("[Link]")
ser = [Link](df['Name'])
data = [Link](10)
data
import pandas as pd
data
Output :
Output:
[Link][3:6]
Output :
*************************************************
print(df)
Output:
Output:
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.
Output:
As shown in the output image, two series were returned since there was only
one parameter both of the times.
Output:
Output:
As shown in the output image, two series were returned since there was only
one parameter both of the times.
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
[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.
# import pandas as pd
import pandas as pd
Output:
Output:
import numpy as np
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
Output :
Python3
Output
In case you get a UnicodeEncodeError, just pass the encoding parameter with
‘utf-8’ value.
Python3
Python3
Output :
Python3
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
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
Python3
Output :
*********************************************
UNIT-V
plotting data using matplotlib
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:
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.
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
*********************************************
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.
Output:
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.
Output:
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.
# 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')
Output:
Output:
Here, we will see how to add 2 plots within the same axis.
Output:
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:
Output:
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.
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.
You can customize the color of the bars by using the color parameter in
the bar() function:
Output:
For horizontal bar plots, you can use the barh() function. This function works
similarly to bar(), but it displays bars horizontally:
Output:
Horizontal Plots
You can control the width of the bars using the width parameter:
Output:
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')
Output:
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)
Output:
**********************************************
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.
Attribute Parameter
Basic Histogram
Python3
Output:
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
Output:
Python3
# Creating dataset
[Link](23685752)
N_points = 10000
n_bins = 20
y = .8 ** x + [Link](10000) + 25
legend = ['distribution']
# Creating histogram
fig, axs = [Link](1, 1,
figsize =(10, 7),
tight_layout = True)
# Remove x, y ticks
[Link].set_ticks_position('none')
[Link].set_ticks_position('none')
# Add x, y gridlines
[Link](b = True, color ='grey',
linestyle ='-.', linewidth = 0.5,
alpha = 0.6)
# Creating histogram
N, bins, patches = [Link](x, bins = n_bins)
# Setting color
fracs = ((N**(1 / 5)) / [Link]())
norm = [Link]([Link](), [Link]())
[Link]('Customized histogram')
# Show plot
[Link]()
Output :
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
Output:
# Adding legend
[Link](['Dataset 1', 'Dataset 2'])
Output:
# Adding colorbar
[Link]()
Output:
***********************
Matplotlib Scatter
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:
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.
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:
# Import libraries
from matplotlib import pyplot as plt
import numpy as np
# Creating dataset
cars = ['AUDI', 'BMW', 'FORD',
'TESLA', 'JAGUAR', 'MERCEDES']
# Creating plot
fig = [Link](figsize=(10, 7))
[Link](data, labels=cars)
# show plot
[Link]()
Output:
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:
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.
Center Circle: The centre_circle is added to create the donut effect, providing a
clean visual separation between the outer and inner 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
*******************************************
How do you import MySQL, in Python for database connectivity?
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:
For PyMySQL:
These commands will install the necessary libraries that allow you to connect
to and interact with a MySQL database from your Python scripts.
*************************
1. After successfully installing the library, you can import it into your Python
script to establish a connection to a MySQL database.
import [Link]
connection [Link](
host 'localhost', or your database server
user your username',
password your password",
database your 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)
[Link]()
[Link]()
***************************************************************
mysql-connector-python:
import [Link]
connection [Link](
host-localhost,
user=your_username',
password='your_password",
#Execute a query
results [Link]()
print(row)
[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.
import [Link]
print(conn)
Another way is to pass the dictionary in the connect() function using ‘**’
operator:
Example:
# Python program to connect
# to mysql database
dict = {
'user': 'root',
'host': 'localhost',
'database': 'College'
}
print(conn)
dataBase = [Link](
host ="localhost",
user ="user",
passwd ="gfg"
)
# preparing a cursor object
cursorObject = [Link]()
# creating database
[Link]("CREATE DATABASE geeks4geeks")
Advantages of MySQL :
Some of the commonly used MySQL queries, operators, and functions are as
follows :
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
4. SHOW TABLES
This shows all the tables in the selected database as a information.
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
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.
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;
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 :
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;
33. LIKE
This is used to fetch records matching for specified string pattern.
Example :
SELECT * FROM employee WHERE name LIKE 'Sh%';
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.
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]
************************************************
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,
import [Link]
connection [Link](
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:
results [Link]()
8. Processing the Results: You can loop through the fetched results and
print them or perform further processing as needed.
print(row)
[Link]()
************************************************************