0% found this document useful (0 votes)
0 views92 pages

— Python Programming——

Python is a simple, open-source, and platform-independent programming language with extensive library support. It is widely used for data visualization, analytics, AI, web applications, and database management. Key concepts include variables, data types, typecasting, strings, conditional statements, and loops.

Uploaded by

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

— Python Programming——

Python is a simple, open-source, and platform-independent programming language with extensive library support. It is widely used for data visualization, analytics, AI, web applications, and database management. Key concepts include variables, data types, typecasting, strings, conditional statements, and loops.

Uploaded by

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

<<<—-Python

Programming⸺>>>

Features of Python
● Python is simple and easy to understand.
● It is Interpreted and platform-independent which makes debugging very
easy.
● Python is an open-source programming language.
● Python provides very big library support. Some of the popular libraries
include NumPy, Tensor flow, Selenium, OpenCV, etc.
● It is possible to integrate other programming languages within python.

_____________________________________________________________________
___________________________________

What is Python used for


● Python is used in Data Visualisation to create plots and graphical
representations.
● Python helps in Data Analytics to analyse and understand raw data for
insights and trends.
● It is used in AI and Machine Learning to simulate human behaviour and to
learn from past data without hard coding.
● It is used to create web applications.
● It can be used to handle databases.
● It is used in business and accounting to perform complex mathematical
operations along with quantitative and qualitative analysis.

_____________________________________________________________________
___________________________________

What is a variable?
Variable is like a container that holds data. Very similar to how our containers in
kitchen holds sugar, salt etc Creating a variable is like creating a placeholder in
memory and assigning it some value. In Python its as easy as writing:
a=1
b = True
c = "Harry"
d = None
_____________________________________________________________________
___________________________________

What is a Data Type?


Data type specifies the type of value a variable holds. This is required in
programming to do various operations without causing an error.

Example->
a=1
print(type(a))
b = "1"
print(type(b))

Type—>>

1. Numeric data: int, float, complex


● int: 3, -8, 0
● float: 7.349, -9.0, 0.0000001
● complex: 6 + 2i

2. Text data: str


str: "Hello World!!!", "Python Programming"

3. Boolean data:
Boolean data consists of values True or False.

4. Sequenced data: list, tuple


list: A list is an ordered collection of data with elements separated by a comma
and enclosed within square brackets. Lists are mutable and can be modified
after creation.
Example:
list1 = [8, 2.3, [-4, 5], ["apple", "banana"]]
print(list1)

Output:
[8, 2.3, [-4, 5], ['apple', 'banana']]

Tuple: A tuple is an ordered collection of data with elements separated by a


comma and enclosed within parentheses. Tuples are immutable and can not be
modified after creation.
Example:
tuple1 = (("parrot", "sparrow"), ("Lion", "Tiger"))
print(tuple1)

Output:
(('parrot', 'sparrow'), ('Lion', 'Tiger'))

5. Mapped data: dict


dict: A dictionary is an unordered collection of data containing a key:value pair.
The key:value pairs are enclosed within curly brackets.

Example:
dict1 = {"name":"Sakshi", "age":20, "canVote":True}
print(dict1)

Output:
{'name': 'Sakshi', 'age': 20, 'canVote': True}

_____________________________________________________________________
___________________________________

Two Types of Typecasting:


. Explicit Conversion (Explicit type casting in python)
. Implicit Conversion (Implicit type casting in python).

Explicit typecasting:
The conversion of one data type into another data type, done via developer or
programmer's intervention or manually as per the requirement, is known as
explicit type conversion.
It can be achieved with the help of Python’s built-in type conversion functions
such as int(), float(), hex(), oct(), str(), etc .

Example of Explicit Typecasting ⸺>>>>>


string = "15"
number = 7
string_number = int(string) #throws an error if the string is not a valid integer
sum= number + string_number
print("The Sum of both the numbers is: ", sum)

The Sum of both the numbers is 22

Implicit type casting:


Data types in Python do not have the same level i.e. ordering of data types is
not the same in Python. Some of the data types have higher-order, and some
have lower order. While performing any operations on variables with different
data types in Python, one of the variable's data types will be changed to the
higher data type. According to the level, one data type is converted into other
by the Python interpreter itself (automatically). This is called, implicit
typecasting in python.
Python converts a smaller data type to a higher data type to prevent data loss.

Example of Implicit Typecasting ⸺>>>>>


# Python automatically converts
# a to int
a=7
print(type(a))

# Python automatically converts b to float


b = 3.0
print(type(b))

# Python automatically converts c to float as it is a float addition


c=a+b
print(c)
print(type(c))

Ouput:
<class 'int'>
<class 'float'>
10.0
<class 'float'>

_____________________________________________________________________
___________________________________

What are strings?


In python, anything that you enclose between single or double quotation marks
is considered a string. A string is essentially a sequence or array of textual
data. Strings are used when working with Unicode characters.

Accessing Characters of a String—>>>


In Python, string is like an array of characters. We can access parts of string by
using its index which starts from 0.
Square brackets can be used to access elements of the string.
print(name[0])
print(name[1])

Looping through the string—>>>


We can loop through strings using a for loop like this:
for character in name:
print(character)

_____________________________________________________________________
___________________________________

String Slicing & Operations on String⸻>>>>>>

Length of a String⸺>>>>>
We can find the length of a string using len() function.
Example:
fruit = "Mango"
len1 = len(fruit)
print("Mango is a", len1, "letter word.")
Output:
Mango is a 5 letter word.

String as an array⸺>>>
A string is essentially a sequence of characters also called an array. Thus we
can access the elements of this array.
Example:
pie = "ApplePie"
print(pie[:5])
print(pie[6]) #returns character at specified index

Output:
Apple
i

Note: This method of specifying the start and end index to specify a part
of a string is called slicing.

Slicing Example:
pie = "ApplePie"
print(pie[:5]) #Slicing from Start
print(pie[5:]) #Slicing till End
print(pie[2:6]) #Slicing in between
print(pie[-8:]) #Slicing using negative index

Output:
Apple
Pie
pleP
ApplePie

Loop through a String:


Strings are arrays and arrays are iterable. Thus we can loop through strings.
Example:
alphabets = "ABCDE"
for i in alphabets:
print(i)

Output:
A
B
C
D
E
_____________________________________________________________________
___________________________________
String methods—>>
Python provides a set of built-in methods that we can use to alter and modify
the strings.
upper() :
The upper() method converts a string to upper case.
Example:
str1 = "AbcDEfghIJ"
print(str1.upper())

Output:
ABCDEFGHIJ

round() :
lower()
The lower() method converts a string to lower case.
Example:
str1 = "AbcDEfghIJ"
print(str1.lower())

Output:
abcdefghij

strip() :
The strip() method removes any white spaces before and after the string.
Example:
str2 = " Silver Spoon "
print(str2.strip)

Output:
Silver Spoon

rstrip() :
the rstrip() removes any trailing characters. Example:
str3 = "Hello !!!"
print(str3.rstrip("!"))

Output:
Hello

replace() :
The replace() method replaces all occurences of a string with another string.
Example:
str2 = "Silver Spoon"
print(str2.replace("Sp", "M"))

Output:
Silver Moon

split() :
The split() method splits the given string at the specified instance and returns
the separated strings as list items.
Example:
str2 = "Silver Spoon"
print(str2.split(" ")) #Splits the string at the whitespace " ".

Output:
['Silver', 'Spoon']
There are various other string methods that we can use to modify our strings.

capitalize() :
The capitalize() method turns only the first character of the string to uppercase
and the rest other characters of the string are turned to lowercase. The string
has no effect if the first character is already uppercase.
Example:
str1 = "hello"
capStr1 = str1.capitalize()
print(capStr1)
str2 = "hello WorlD"
capStr2 = str2.capitalize()
print(capStr2)

Output:
Hello
Hello world

center() :
The center() method aligns the string to the center as per the parameters given
by the user.
Example:
str1 = "Welcome to the Console!!!"
print(str1.center(50))

Output:
Welcome to the Console!!!

We can also provide padding character. It will fill the rest of the fill characters
provided by the user.
Example:
str1 = "Welcome to the Console!!!"
print(str1.center(50, "."))

Output:
............Welcome to the Console!!!.............

count() :
The count() method returns the number of times the given value has occurred
within the given string.
Example:
str2 = "Abracadabra"
countStr = str2.count("a")
print(countStr)

Output:
4

endswith() :
The endswith() method checks if the string ends with a given value. If yes then
return True, else return False.
Example :
str1 = "Welcome to the Console !!!"
print(str1.endswith("!!!"))

Output:
True

We can even also check for a value in-between the string by providing start and
end index positions.
Example:
str1 = "Welcome to the Console !!!"
print(str1.endswith("to", 4, 10))

Output:
True

find() :
The find() method searches for the first occurrence of the given value and
returns the index where it is present. If given value is absent from the string
then return -1.
Example:
str1 = "He's name is Dan. He is an honest man."
print(str1.find("is"))

Output:
10

As we can see, this method is somewhat similar to the index() method. The
major difference being that index() raises an exception if value is absent
whereas find() does not.
Example:
str1 = "He's name is Dan. He is an honest man."
print(str1.find("Daniel"))

Output:
-1

index() :
The index() method searches for the first occurrence of the given value and
returns the index where it is present. If given value is absent from the string
then raise an exception.
Example:
str1 = "He's name is Dan. Dan is an honest man."
print(str1.index("Dan"))

Output:
13

As we can see, this method is somewhat similar to the find() method. The major
difference being that index() raises an exception if value is absent whereas
find() does not.
Example:
str1 = "He's name is Dan. Dan is an honest man."
print(str1.index("Daniel"))

Output:
ValueError: substring not found

isalnum() :
The isalnum() method returns True only if the entire string only consists of A-Z,
a-z, 0-9. If any other characters or punctuations are present, then it returns
False.
Example 1:
str1 = "WelcomeToTheConsole"
print(str1.isalnum())
Output:
True

isalpha() :
The isalnum() method returns True only if the entire string only consists of A-Z,
a-z. If any other characters or punctuations or numbers(0-9) are present, then
it returns False.
Example :
str1 = "Welcome"
print(str1.isalpha())

Output:
True

islower() :
The islower() method returns True if all the characters in the string are lower
case, else it returns False.
Example:
str1 = "hello world"
print(str1.islower())

Output:
True

isprintable() :
The isprintable() method returns True if all the values within the given string are
printable, if not, then return False.
Example :
str1 = "We wish you a Merry Christmas"
print(str1.isprintable())

Output:
True

isspace() :
The isspace() method returns True only and only if the string contains white
spaces, else returns False.
Example:
str1 = " " #using Spacebar
print(str1.isspace())
str2 = " " #using Tab
print(str2.isspace())

Output:
True
True
istitle() :
The istitile() returns True only if the first letter of each word of the string is
capitalized, else it returns False.
Example:
str1 = "World Health Organization"
print(str1.istitle())

Output:
True

Example:
str2 = "To kill a Mocking bird"
print(str2.istitle())

Output:
False

isupper() :
The isupper() method returns True if all the characters in the string are upper
case, else it returns False.
Example :
str1 = "WORLD HEALTH ORGANIZATION"
print(str1.isupper())

Output:
True

startswith() :
The endswith() method checks if the string starts with a given value. If yes then
return True, else return False.
Example :
str1 = "Python is a Interpreted Language"
print(str1.startswith("Python"))

Output:
True

swapcase() :
The swapcase() method changes the character casing of the string. Upper case
are converted to lower case and lower case to upper case.
Example:
str1 = "Python is a Interpreted Language"
print(str1.swapcase())

Output:
pYTHON IS A iNTERPRETED lANGUAGE
title() :
The title() method capitalizes each letter of the word within the string.
Example:
str1 = "He's name is Dan. Dan is an honest man."
print(str1.title())

Output:
He'S Name Is Dan. Dan Is An Honest Man.

_____________________________________________________________________
___________________________________

if-else Statements—>>>
Sometimes the programmer needs to check the evaluation of certain
expression(s), whether the expression(s) evaluate to True or False. If the
expression evaluates to False, then the program execution follows a different
path than it would have if the expression had evaluated to True.
Based on this, the conditional statements are further classified into following
types:
● if
● if-else
● if-else-elif
● nested if-else-elif.

An if……else statement evaluates like this:


if the expression evaluates True:
Execute the block of code inside if statement. After execution return to the
code out of the if……else block.\

if the expression evaluates False:


Execute the block of code inside else statement. After execution return to the
code out of the if……else block.

Example:
applePrice = 210
budget = 200
if (applePrice <= budget):
print("Alexa, add 1 kg Apples to the cart.")
else:
print("Alexa, do not add Apples to the cart.")

An if…elif…else statement evaluates like this:


Example:
num = 0
if (num < 0):
print("Number is negative.")
elif (num == 0):
print("Number is Zero.")
else:
print("Number is positive.")

Nested if statements⸺>>>

Example:
num = 18
if (num < 0):
print("Number is negative.")
elif (num > 0):
if (num <= 10):
print("Number is between 1-10")
elif (num > 10 and num <= 20):
print("Number is between 11-20")
else:
print("Number is greater than 20")
else:
print("Number is zero")

_____________________________________________________________________
___________________________________

Match case ⸺>>>

x=4
# x is the variable to match
match x:
# if x is 0
case 0:
print("x is zero")
# case with if-condition
case 4 if x % 2 == 0:
print("x % 2 == 0 and case is 4")
# Empty case with if-condition
case _ if x < 10:
print("x is < 10")
# default case(will only be matched if the above cases were not matched)
# so it is basically just an else:
case _:
print(x)

_____________________________________________________________________
___________________________________

Introduction to Loops—>>>
Sometimes a programmer wants to execute a group of statements a certain
number of times. This can be done using loops. Based on this loops are further
classified into following main types;
● for loop
● while loop

The for Loop—>>


for loops can iterate over a sequence of iterable objects in python. Iterating
over a sequence is nothing but iterating over strings, lists, tuples, sets and
dictionaries.

Example: iterating over a string:


name = 'Abhishek'
for i in name:
print(i, end=", ")

Output:
A, b, h, i, s, h, e, k,

Example: iterating over a list:


colors = ["Red", "Green", "Blue", "Yellow"]
for x in colors:
print(x)
Output:
Red
Green
Blue
Yellow
Similarly, we can use loops for lists, sets and dictionaries.

range():
What if we do not want to iterate over a sequence? What if we want to use for
loop for a specific number of times?
Here, we can use the range() function.
Example:
for k in range(5):
print(k)
Output:
0
1
2
3
4

Here, we can see that the loop starts from 0 by default and increments at each
iteration.
But we can also loop over a specific range.

Example:
for k in range(4,9):
print(k)
Output:
4
5
6
7
8

_____________________________________________________________________
___________________________________

while Loop
As the name suggests, while loops execute statements while the condition is
True. As soon as the condition becomes False, the interpreter comes out of the
while loop.

Example:
count = 5
while (count > 0):
print(count)
count = count - 1
Output:
5
4
3
2
1

Here, the count variable is set to 5 which decrements after each iteration.
Depending upon the while loop condition, we need to either increment or
decrement the counter variable (the variable count, in our case) or the loop will
continue forever.
Else with While Loop
We can even use the else statement with the while loop. Essentially what the
else statement does is that as soon as the while loop condition becomes False,
the interpreter comes out of the while loop and the else statement is executed.

Example:
x=5
while (x > 0):
print(x)
x=x-1
else:
print('counter is 0')
Output:
5
4
3
2
1
counter is 0

_____________________________________________________________________
___________________________________

break statement—>>

The break statement enables a program to skip over a part of the code. A break
statement terminates the very loop it lies within.

Example
for i in range(1,101,1):
print(i ,end=" ")
if(i==50):
break
else:
print("Mississippi")
print("Thank you")
Output
1 Mississippi
2 Mississippi
3 Mississippi
4 Mississippi
5 Mississippi
.
.
.
50 Mississippi
Continue Statement⸺>>>
The continue statement skips the rest of the loop statements and causes the
next iteration to occur.

Example
for i in [2,3,4,6,8,0]:
if (i%2!=0):
continue
print(i)
Output
2
4
6
8
0
_____________________________________________________________________
___________________________________

Python Functions
A function is a block of code that performs a specific task whenever it is called.
In bigger programs, where we have large amounts of code, it is advisable to
create or use existing functions that make the program flow organized and
neat.

There are two types of functions:


. Built-in functions
. User-defined functions

Built-in functions:
These functions are defined and pre-coded in python. Some examples of built-
in functions are as follows:
min(), max(), len(), sum(), type(), range(), dict(), list(), tuple(), set(), print(), etc.

User-defined functions:
We can create functions to perform specific tasks as per our needs. Such
functions are called user-defined functions.

Syntax:
def function_name(parameters):
pass
# Code and Statements

● Create a function using the def keyword, followed by a function name,


followed by a paranthesis (()) and a colon(:).
● Any parameters and arguments should be placed within the parentheses.
● Rules to naming function are similar to that of naming variables.
● Any statements and other code within the function should be indented.
Calling a function:
We call a function by giving the function name, followed by parameters (if any)
in the parenthesis.
Example:
def name(fname, lname):
print("Hello,", fname, lname)

name("Sam", "Wilson")

Output:
Hello, Sam Wilson

_____________________________________________________________________
___________________________________

Default arguments:
We can provide a default value while creating a function. This way the function
assumes a default value even if a value is not provided in the function call for
that argument.

Example:
def name(fname, mname = "Jhon", lname = "Whatson"):
print("Hello,", fname, mname, lname)
name("Amy")

Output:
Hello, Amy Jhon Whatson

Keyword arguments:
We can provide arguments with key = value, this way the interpreter recognizes
the arguments by the parameter name. Hence, the the order in which the
arguments are passed does not matter.

Example:
def name(fname, mname, lname):
print("Hello,", fname, mname, lname)
name(mname = "Peter", lname = "Wesker", fname = "Jade")

Output:
Hello, Jade Peter Wesker

Required arguments:
In case we don’t pass the arguments with a key = value syntax, then it is
necessary to pass the arguments in the correct positional order and the
number of arguments passed should match with actual function definition.

Example 1: when number of arguments passed does not match to the actual
function definition.
def name(fname, mname, lname):
print("Hello,", fname, mname, lname)
name("Peter", "Quill")

Output:
name("Peter", "Quill")\
TypeError: name() missing 1 required positional argument: 'lname'

Example 2: when number of arguments passed matches to the actual function


definition.
def name(fname, mname, lname):
print("Hello,", fname, mname, lname)
name("Peter", "Ego", "Quill")

Output:
Hello, Peter Ego Quill

Variable-length arguments:
Sometimes we may need to pass more arguments than those defined in the
actual function. This can be done using variable-length arguments.
There are two ways to achieve this:

Arbitrary Arguments:
While creating a function, pass a * before the parameter name while defining
the function. The function accesses the arguments by processing them in the
form of tuple.

Example:
def name(*name):
print("Hello,", name[0], name[1], name[2])
name("James", "Buchanan", "Barnes")

Output:
Hello, James Buchanan Barnes

Keyword Arbitrary Arguments:


While creating a function, pass a * before the parameter name while defining
the function. The function accesses the arguments by processing them in the
form of dictionary.

Example1:
Example1:

return Statement
The return statement is used to return the value of the expression back to the
calling function.
Example:

def name(fname, mname, lname):


return "Hello, " + fname + " " + mname + " " + lname
print(name("James", "Buchanan", "Barnes"))

Output:
Hello, James Buchanan Barnes

_____________________________________________________________________
_______________________________

Python Lists
● Lists are ordered collection of data items.
● They store multiple items in a single variable.
● List items are separated by commas and enclosed within square brackets
[].
● Lists are changeable meaning we can alter them after creation.

Example 1:
lst1 = [1,2,2,3,5,4,6]
lst2 = ["Red", "Green", "Blue"]
print(lst1)
print(lst2)
Output:
[1, 2, 2, 3, 5, 4, 6]
['Red', 'Green', 'Blue']

Example 2:
details = ["Abhijeet", 18, "FYBScIT", 9.8]
print(details)
Output:
['Abhijeet', 18, 'FYBScIT', 9.8]

As we can see, a single list can contain items of different data types.

_____________________________________________________________________
_______________________________

List Index
Each item/element in a list has its own unique index. This index can be used to
access any particular item from the list. The first item has index [0], second
item has index [1], third item has index [2] and so on.
Example:
colors = ["Red", "Green", "Blue", "Yellow", "Green"]
# [0] [1] [2] [3] [4]

Accessing list items


We can access list items by using its index with the square bracket syntax [].
For example colors[0] will give "Red", colors[1] will give "Green" and so on...
Positive Indexing:
As we have seen that list items have index, as such we can access items using
these indexes.
Example:
colors = ["Red", "Green", "Blue", "Yellow", "Green"]
# [0] [1] [2] [3] [4]
print(colors[2])
print(colors[4])
print(colors[0])

Output:
Blue
Green
Red

Negative Indexing:
Similar to positive indexing, negative indexing is also used to access items, but
from the end of the list. The last item has index [-1], second last item has index
[-2], third last item has index [-3] and so on.
Example:
colors = ["Red", "Green", "Blue", "Yellow", "Green"]
# [-5] [-4] [-3] [-2] [-1]
print(colors[-1])
print(colors[-3])
print(colors[-5])

Output:
Green
Blue
Red

Check whether an item in present in the list?


We can check if a given item is present in the list. This is done using
the in keyword.

colors = ["Red", "Green", "Blue", "Yellow", "Green"]


if "Yellow" in colors:
print("Yellow is present.")
else:
print("Yellow is absent.")

Output:
Yellow is present.

colors = ["Red", "Green", "Blue", "Yellow", "Green"]


if "Orange" in colors:
print("Orange is present.")
else:
print("Orange is absent.")

Output:
Orange is absent.

Range of Index:
You can print a range of list items by specifying where you want to start, where
do you want to end and if you want to skip elements in between the range.
Syntax:
listName[start : end : jumpIndex]
Note: jump Index is optional. We will see this in later examples.
Example: printing elements within a particular range:

animals = ["cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow"]
print(animals[3:7]) #using positive indexes
print(animals[-7:-2]) #using negative indexes'
Output:
['mouse', 'pig', 'horse', 'donkey']
['bat', 'mouse', 'pig', 'horse', 'donkey']

Here, we provide index of the element from where we want to start and the
index of the element till which we want to print the values.
Note: The element of the end index provided will not be included.
Example: printing all element from a given index till the end

animals = ["cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow"]
print(animals[4:]) #using positive indexes
print(animals[-4:]) #using negative indexes
Output:
['pig', 'horse', 'donkey', 'goat', 'cow']
['horse', 'donkey', 'goat', 'cow']

When no end index is provided, the interpreter prints all the values till the end.

Example: printing all elements from start to a given index


animals = ["cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow"]
print(animals[:6]) #using positive indexes
print(animals[:-3]) #using negative indexes

Output:
['cat', 'dog', 'bat', 'mouse', 'pig', 'horse']
['cat', 'dog', 'bat', 'mouse', 'pig', 'horse']

When no start index is provided, the interpreter prints all the values from start
up to the end index provided.
Example: Printing alternate values

animals = ["cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow"]
print(animals[::2]) #using positive indexes
print(animals[-8:-1:2]) #using negative indexes

Output:
['cat', 'bat', 'pig', 'donkey', 'cow']
['dog', 'mouse', 'horse', 'goat']

Here, we have not provided start and index, which means all the values will be
considered. But as we have provided a jump index of 2 only alternate values will
be printed.

Example: printing every 3rd consecutive value withing a given range


animals = ["cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow"]
print(animals[1:8:3])

Output:
['dog', 'pig', 'goat’]

Here, jump index is 3. Hence it prints every 3rd element within given index.

_____________________________________________________________________
_______________________________

Introduction to Lists in Python :


In Python, a list is a versatile data structure used to store collections of items. It
is an ordered sequence of elements, where each element can be of any data
type - integers, floats, strings, or even other lists. Lists are mutable, meaning
their elements can be changed after the list is created. Lists are defined using
square brackets [ ] and can be accessed by indexing and slicing.
Key Features of Lists:

● Ordered Collection: Lists maintain the order of elements as they are


inserted.
● Mutable: Elements in a list can be modified, added, or removed.
● Heterogeneous: Lists can contain elements of different data types.
● Dynamic: Lists can grow or shrink dynamically as elements are added or
removed.
● Accessing Elements: Elements in a list can be accessed using indexing
and slicing.
● Iterability: Lists can be iterated over using loops like for loop.
● Versatility: Lists are versatile and can be used for various purposes like
storing data, implementing stacks, queues, etc.

Traversal of Lists in Python:


Traversal refers to the process of accessing each element in a list, usually for
the purpose of performing some operation on each element. Python offers
several methods for traversing lists, including iteration with loops and built-in
functions.
1. Using a for Loop:
The most common method for traversing a list is by using a for loop. In Python,
you can iterate over the elements of a list directly using a for loop:
python
my_list = [1, 2, 3, 4, 5]
for item in my_list:
print(item)
Output:
12345

2. Using a while Loop:


You can also traverse a list using a while loop along with an index variable:

index = 0
while index < len(my_list):
print(my_list[index])
index += 1
Output:
12345

4. Using the map() Function:


The map() function can also be used for traversing a list and applying a
function to each element:

def square(x):
return x ** 2

squared_list = list(map(square, my_list))


print(squared_list)
Output:
[1, 4, 9, 16, 25]

5. Using enumerate():
enumerate() can be used to iterate over both the elements and their indices:
python

for index, item in enumerate(my_list):


print(f"Index {index}: {item}")

Output:
Index 0: 1
Index 1: 2
Index 2: 3
Index 3: 4
Index 4: 5

Traversal is a fundamental operation when working with lists in Python. It allows


you to access and process each element of the list efficiently, enabling various
operations and manipulations on the data stored in the list.
Slicing Lists in Python:
Slicing allows you to extract a portion of a list by specifying a start index, stop
index, and an optional step size. It provides a convenient way to work with
subsets of lists without modifying the original list.
Basic Syntax:
The basic syntax for slicing a list in Python is list[start:stop:step], where:
● start: The index where the slice begins (inclusive).
● stop: The index where the slice ends (exclusive).
● step (optional): The increment between elements in the slice.

Examples:
● Slice with Positive Indices:
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Extract elements from index 2 to index 5 (exclusive)


slice1 = my_list[2:5]
print(slice1) # Output: [3, 4, 5]

# Extract elements from index 0 to index 7 (exclusive) with step 2


slice2 = my_list[0:7:2]
print(slice2) # Output: [1, 3, 5, 7]

● Slice with Negative Indices:


# Extract elements from the third element from the end to the end
slice3 = my_list[-3:]
print(slice3) # Output: [8, 9, 10]

# Extract elements from index 2 to the fourth element from the end with step -1
slice4 = my_list[2:-4:-1]
print(slice4) # Output: [3, 2, 1]

● Omitting Indices:
If you omit start, it defaults to the beginning of the list. If you omit stop, it
defaults to the end of the list.
# Extract elements from the beginning to index 5 (exclusive)
slice5 = my_list[:5]
print(slice5) # Output: [1, 2, 3, 4, 5]

# Extract elements from index 2 to the end


slice6 = my_list[2:]
print(slice6) # Output: [3, 4, 5, 6, 7, 8, 9, 10]

● Reverse LIst:
# Reverse the entire list
reversed_list = my_list[::-1]
print(reversed_list) # Output: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

Delete List Element in Python:

1. Using del statement:


The del statement removes an element from a list at a specified
index.

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

# Delete element at index 2 (value: 3)


del my_list[2]
print(my_list) # Output: [1, 2, 4, 5]

2. Using remove() method:


The remove() method removes the first occurrence of a specified
value from the list.

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

# Remove value 3 from the list


my_list.remove(3)
print(my_list) # Output: [1, 2, 4, 3, 5]

Note:
● If you use del, you need to know the index of the element you want to
delete.
● If you use remove(), you need to know the value of the element you want to
delete. If the value appears multiple times, only the first occurrence will be
removed.
● Attempting to delete an element that doesn't exist in the list will raise an
error. You can use error handling mechanisms like try and except to handle
such situations if necessary.

List Methods

list.sort()
This method sorts the list in ascending order. The original list is updated
Example 1:
colors = ["voilet", "indigo", "blue", "green"]
colors.sort()
print(colors)

num = [4,2,5,3,6,1,2,1,2,8,9,7]
num.sort()
print(num)

Output:
['blue', 'green', 'indigo', 'voilet']\
[1, 1, 2, 2, 2, 3, 4, 5, 6, 7, 8, 9]

What if you want to print the list in descending order?


We must give reverse=True as a parameter in the sort method.
Example:
colors = ["voilet", "indigo", "blue", "green"]
colors.sort(reverse=True)
print(colors)

num = [4,2,5,3,6,1,2,1,2,8,9,7]
num.sort(reverse=True)
print(num)

Output:
['voilet', 'indigo', 'green', 'blue']
[9, 8, 7, 6, 5, 4, 3, 2, 2, 2, 1, 1]

The reverse parameter is set to False by default.


Note: Do not mistake the reverse parameter with the reverse method.

reverse()
This method reverses the order of the list.

Example:
colors = ["voilet", "indigo", "blue", "green"]
colors.reverse()
print(colors)

num = [4,2,5,3,6,1,2,1,2,8,9,7]
num.reverse()
print(num)

Output:
['green', 'blue', 'indigo', 'voilet']
[7, 9, 8, 2, 1, 2, 1, 6, 3, 5, 2, 4]

index()
This method returns the index of the first occurrence of the list item.
Example:
colors = ["voilet", "green", "indigo", "blue", "green"]
print(colors.index("green"))

num = [4,2,5,3,6,1,2,1,3,2,8,9,7]
print(num.index(3))

Output:
1
3

count()
Returns the count of the number of items with the given value.

Example:
colors = ["voilet", "green", "indigo", "blue", "green"]
print(colors.count("green"))

num = [4,2,5,3,6,1,2,1,3,2,8,9,7]

Output:
2
3

copy()
Returns copy of the list. This can be done to perform operations on the list
without modifying the original list.

Example:
colors = ["voilet", "green", "indigo", "blue"]
newlist = colors.copy()
print(colors)
print(newlist)

Output:
['voilet', 'green', 'indigo', 'blue']
['voilet', 'green', 'indigo', 'blue']

append():
This method appends items to the end of the existing list.

Example:
colors = ["voilet", "indigo", "blue"]
colors.append("green")
print(colors)
Output:
['voilet', 'indigo', 'blue', 'green']

insert():
This method inserts an item at the given index. User has to specify index and
the item to be inserted within the insert() method.

Example:
colors = ["voilet", "indigo", "blue"]
# [0] [1] [2]

colors.insert(1, "green") #inserts item at index 1


# updated list: colors = ["voilet", "green", "indigo", "blue"]
# indexs [0] [1] [2] [3]

print(colors)

Output:
['voilet', 'green', 'indigo', 'blue']

extend():
This method adds an entire list or any other collection datatype (set, tuple,
dictionary) to the existing list.

Example 1:
#add a list to a list
colors = ["voilet", "indigo", "blue"]
rainbow = ["green", "yellow", "orange", "red"]
colors.extend(rainbow)
print(colors)

Output:
['voilet', 'indigo', 'blue', 'green', 'yellow', 'orange', 'red']

Concatenating two lists:


You can simply concatenate two lists to join two lists.

Example:
colors = ["voilet", "indigo", "blue", "green"]
colors2 = ["yellow", "orange", "red"]
print(colors + colors2)

Output:
['voilet', 'indigo', 'blue', 'green', 'yellow', 'orange', 'red']

_____________________________________________________________________
_______________________________

Python Tuples
Tuples are ordered collection of data items. They store multiple items in a
single variable. Tuple items are separated by commas and enclosed within
round brackets (). Tuples are unchangeable meaning we can not alter them
after creation.
Example 1:
tuple1 = (1,2,2,3,5,4,6)
tuple2 = ("Red", "Green", "Blue")
print(tuple1)
print(tuple2)

Output:
(1, 2, 2, 3, 5, 4, 6)
('Red', 'Green', 'Blue')

Example 2:
details = ("Abhijeet", 18, "FYBScIT", 9.8)
print(details)

Output:
('Abhijeet', 18, 'FYBScIT', 9.8)

The tuple() Constructor


It is also possible to use the tuple() constructor to make a tuple.
Example
Using the tuple() method to make a tuple:
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-
brackets
print(thistuple)

_____________________________________________________________________
_______________________________

Tuple Indexes
Each item/element in a tuple has its own unique index. This index can be used
to access any particular item from the tuple. The first item has index [0],
second item has index [1], third item has index [2] and so on.
Example:
country = ("Spain", "Italy", "India",)
# [0] [1] [2]

Accessing tuple items:


I. Positive Indexing:
As we have seen that tuple items have index, as such we can access items
using these indexes.
Example:
country = ("Spain", "Italy", "India",)
# [0] [1] [2]
print(country[0])
print(country[1])
print(country[2])

Output:
Spain
Italy
India

II. Negative Indexing:


Similar to positive indexing, negative indexing is also used to access items, but
from the end of the tuple. The last item has index [-1], second last item has
index [-2], third last item has index [-3] and so on.
Example:
country = ("Spain", "Italy", "India", "England", "Germany")
# [0] [1] [2] [3] [4]
print(country[-1]) # Similar to print(country[len(country) - 1])
print(country[-3])
print(country[-4])

Output:
Germany
India
Italy

III. Check for item:


We can check if a given item is present in the tuple. This is done using
the in keyword.
Example 1:
country = ("Spain", "Italy", "India", "England", "Germany")
if "Germany" in country:
print("Germany is present.")
else:
print("Germany is absent.")

Output:
Germany is present.

Example 2:
country = ("Spain", "Italy", "India", "England", "Germany")
if "Russia" in country:
print("Russia is present.")
else:
print("Russia is absent.")

Output:
Russia is absent.

IV. Range of Index:


You can print a range of tuple items by specifying where do you want to start,
where do you want to end and if you want to skip elements in between the
range.
Syntax:
Tuple[start : end : jumpIndex]

Note: jump Index is optional. We will see this in given examples.


Example: Printing elements within a particular range:
animals = ("cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow")
print(animals[3:7]) #using positive indexes
print(animals[-7:-2]) #using negative indexes

Output:
('mouse', 'pig', 'horse', 'donkey')
('bat', 'mouse', 'pig', 'horse', 'donkey')

Here, we provide index of the element from where we want to start and the
index of the element till which we want to print the values. Note: The element of
the end index provided will not be included.
Example: Printing all element from a given index till the end
animals = ("cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow")
print(animals[4:]) #using positive indexes
print(animals[-4:]) #using negative indexes

Output:
('pig', 'horse', 'donkey', 'goat', 'cow')
('horse', 'donkey', 'goat', 'cow')

When no end index is provided, the interpreter prints all the values till the end.
Example: printing all elements from start to a given index
animals = ("cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow")
print(animals[:6]) #using positive indexes
print(animals[:-3]) #using negative indexes

Output:
('cat', 'dog', 'bat', 'mouse', 'pig', 'horse')
('cat', 'dog', 'bat', 'mouse', 'pig', 'horse')

When no start index is provided, the interpreter prints all the values from start
up to the end index provided.
Example: Print alternate values
animals = ("cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow")
print(animals[::2]) #using positive indexes
print(animals[-8:-1:2]) #using negative indexes

Output:
('cat', 'bat', 'pig', 'donkey', 'cow')
('dog', 'mouse', 'horse', 'goat')

Here, we have not provided start and end index, which means all the values will
be considered. But as we have provided a jump index of 2 only alternate values
will be printed.
Example: printing every 3rd consecutive withing given range
animals = ("cat", "dog", "bat", "mouse", "pig", "horse", "donkey", "goat", "cow")
print(animals[1:8:3])

Output:
('dog', 'pig', 'goat')

Here, jump index is 3. Hence it prints every 3rd element within given index.

_____________________________________________________________________
_______________________________

Manipulating Tuples
Tuples are immutable, hence if you want to add, remove or change tuple items,
then first you must convert the tuple to a list. Then perform operation on that
list and convert it back to tuple.
Example:
countries = ("Spain", "Italy", "India", "England", "Germany")
temp = list(countries)
temp.append("Russia") #add item
temp.pop(3) #remove item
temp[2] = "Finland" #change item
countries = tuple(temp)
print(countries)

Output:
('Spain', 'Italy', 'Finland', 'Germany', 'Russia')

Thus, we convert the tuple to a list, manipulate items of the list using list
methods, then convert list back to a tuple.
However, we can directly concatenate two tuples without converting them to
list.
Example:
countries = ("Pakistan", "Afghanistan", "Bangladesh", "ShriLanka")
countries2 = ("Vietnam", "India", "China")
southEastAsia = countries + countries2
print(southEastAsia)

Output:
('Pakistan', 'Afghanistan', 'Bangladesh', 'ShriLanka', 'Vietnam', 'India', 'China')

Unpacking a tuple:
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits

print(green)
print(yellow)
print(red)

Output: apple
banana
cherry

Using Asterisk*
If the number of variables is less than the number of values, you can add an * to
the variable name and the values will be assigned to the variable as a list:
Example
Assign the rest of the values as a list called "red":

fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")


(green, yellow, *red) = fruits

print(green)
print(yellow)
print(red)

Output:

_____________________________________________________________________
_______________________________

Tuple methods
As tuple is immutable type of collection of elements it have limited built in
methods.They are explained below
count() Method
The count() method of Tuple returns the number of times the given element
appears in the tuple.
Syntax:
tuple.count(element)

Example
Tuple1 = (0, 1, 2, 3, 2, 3, 1, 3, 2)
res = Tuple1.count(3)
print('Count of 3 in Tuple1 is:', res)

Output
3

index() method
The Index() method returns the first occurrence of the given element from the
tuple.
Syntax:
tuple.index(element, start, end)

Note: This method raises a ValueError if the element is not found in the tuple.
Example
Tuple = (0, 1, 2, 3, 2, 3, 1, 3, 2)
res = Tuple.index(3)
print('First occurrence of 3 is', res)

Output
3
_____________________________________________________________________
_______________________________

String formatting in python


String formatting can be done in python using the format method.
txt = "For only {price:.2f} dollars!"
print(txt.format(price = 49))

f-strings in python
It is a new string formatting mechanism introduced by the PEP 498. It is also
known as Literal String Interpolation or more commonly as F-strings (f
character preceding the string literal). The primary focus of this mechanism is
to make the interpolation easier.
When we prefix the string with the letter 'f', the string becomes the f-string
itself. The f-string can be formatted in much same as the str.format() method.
The f-string offers a convenient way to embed Python expression inside string
literals for formatting.

Example
val = 'Geeks'
print(f"{val}for{val} is a portal for {val}.")
name = 'Tushar'
age = 23
print(f"Hello, My name is {name} and I'm {age} years old.")

Output:
Hello, My name is Tushar and I'm 23 years old.

In the above code, we have used the f-string to format the string. It evaluates at
runtime; we can put all valid Python expressions in them.
We can use it in a single statement as well.
Example
print(f"{2 * 30})"

Output:
60

_____________________________________________________________________
_______________________________

Docstrings in python
Python docstrings are the string literals that appear right after the definition of
a function, method, class, or module.
Example
def square(n):
'''Takes in a number n, returns the square of n'''
print(n**2)
square(5)

Here,
'''Takes in a number n, returns the square of n''' is a docstring which will not
appear in output
Output:
25

Here is another example:


def add(num1, num2):
"""
Add up two integer numbers.

This function simply wraps the ``+`` operator, and does not
do anything interesting, except for illustrating what
the docstring of a very simple function looks like.

Parameters
----------
num1 : int
First number to add.
num2 : int
Second number to add.

Returns
-------
int
The sum of ``num1`` and ``num2``.

See Also
--------
subtract : Subtract one integer from another.

Examples
--------
>>> add(2, 2)
4
>>> add(25, 0)
25
>>> add(10, -10)
0
"""
return num1 + num2

Python Comments vs Docstrings


Python Comments
Comments are descriptions that help programmers better understand the intent
and functionality of the program. They are completely ignored by the Python
interpreter.
Python docstrings
As mentioned above, Python docstrings are strings used right after the
definition of a function, method, class, or module (like in Example 1). They are
used to document our code.
We can access these docstrings using the doc attribute.
Python doc attribute
Whenever string literals are present just after the definition of a function,
module, class or method, they are associated with the object as
their doc attribute. We can later use this attribute to retrieve this docstring.
Example
def square(n):
'''Takes in a number n, returns the square of n'''
return n**2

print(square.__doc__)
Output:
Takes in a number n, returns the square of n

_____________________________________________________________________
_______________________________

Recursion in python
Recursion is the process of defining something in terms of itself.

Python Recursive Function


In Python, we know that a function can call other functions. It is even possible
for the function to call itself. These types of construct are termed as recursive
functions.
Example:
def factorial(num):
if (num == 1 or num == 0):
return 1
else:
return (num * factorial(num - 1))

# Driver Code
num = 7;
print("Number: ",num)
print("Factorial: ",factorial(num))

Output:
number: 7
Factorial: 5040

_____________________________________________________________________
_______________________________

Python Sets
Sets are unordered collection of data items. They store multiple items in a
single variable. Set items are separated by commas and enclosed within curly
brackets {}. Sets are unchangeable, meaning you cannot change items of the
set once created. Sets do not contain duplicate items.
Example:
info = {"Carla", 19, False, 5.9, 19}
print(info)

Output:
{False, 19, 5.9, 'Carla'}

Here we see that the items of set occur in random order and hence they cannot
be accessed using index numbers. Also sets do not allow duplicate values.
Quick Quiz: Try to create an empty set. Check using the type() function
whether the type of your variable is a set
Accessing set items:

Using a For loop


You can access items of set using a for loop.
Example:
info = {"Carla", 19, False, 5.9}
for item in info:
print(item)

Output:
False
Carla
19
5.9

_____________________________________________________________________
_______________________________

Joining Sets
Sets in python more or less work in the same way as sets in mathematics. We
can perform operations like union and intersection on the sets just like in
mathematics.

I. union() and update():


The union() and update() methods prints all items that are present in the two
sets. The union() method returns a new set whereas update() method adds
item into the existing set from another set.

Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
cities3 = cities.union(cities2)
print(cities3)

Output:
{'Tokyo', 'Madrid', 'Kabul', 'Seoul', 'Berlin', 'Delhi'}

Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
cities.update(cities2)
print(cities)

Output:
{'Berlin', 'Madrid', 'Tokyo', 'Delhi', 'Kabul', 'Seoul'}

II. intersection and intersection_update():


The intersection() and intersection_update() methods prints only items that are
similar to both the sets. The intersection() method returns a new set whereas
intersection_update() method updates into the existing set from another set.

Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
cities3 = cities.intersection(cities2)
print(cities3)

Output:
{'Madrid', 'Tokyo'}

Example :
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
cities.intersection_update(cities2)
print(cities)

Output:
{'Tokyo', 'Madrid'}

III. symmetric_difference and symmetric_difference_update():


The symmetric_difference() and symmetric_difference_update() methods
prints only items that are not similar to both the sets. The
symmetric_difference() method returns a new set whereas
symmetric_difference_update() method updates into the existing set from
another set.

Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
cities3 = cities.symmetric_difference(cities2)
print(cities3)

Output:
{'Seoul', 'Kabul', 'Berlin', 'Delhi'}

Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
cities.symmetric_difference_update(cities2)
print(cities)
Output:
{'Kabul', 'Delhi', 'Berlin', 'Seoul'}

IV. difference() and difference_update():


The difference() and difference_update() methods prints only items that are
only present in the original set and not in both the sets. The difference()
method returns a new set whereas difference_update() method updates into
the existing set from another set.

Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Seoul", "Kabul", "Delhi"}
cities3 = cities.difference(cities2)
print(cities3)

Output:
{'Tokyo', 'Madrid', 'Berlin'}

Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Seoul", "Kabul", "Delhi"}
print(cities.difference(cities2))

Output:
{'Tokyo', 'Berlin', 'Madrid'}

_____________________________________________________________________
_______________________________

Set Methods
There are several in-built methods used for the manipulation of set.They are
explained below

isdisjoint():
The isdisjoint() method checks if items of given set are present in another set.
This method returns False if items are present, else it returns True.
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
print(cities.isdisjoint(cities2))

Output:
False

issuperset():
The issuperset() method checks if all the items of a particular set are present in
the original set. It returns True if all the items are present, else it returns False.

Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Seoul", "Kabul"}
print(cities.issuperset(cities2))
cities3 = {"Seoul", "Madrid","Kabul"}
print(cities.issuperset(cities3))
Output:
False
False

issubset():
The issubset() method checks if all the items of the original set are present in
the particular set. It returns True if all the items are present, else it returns
False.

Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Delhi", "Madrid"}
print(cities2.issubset(cities))
Output:
True

add()
If you want to add a single item to the set use the add() method.
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities.add("Helsinki")
print(cities)
Output:
{'Tokyo', 'Helsinki', 'Madrid', 'Berlin', 'Delhi'}

update()
If you want to add more than one item, simply create another set or any other
iterable object(list, tuple, dictionary), and use the update() method to add it
into the existing set.
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Helsinki", "Warsaw", "Seoul"}
cities.update(cities2)
print(cities)
Output:
{'Seoul', 'Berlin', 'Delhi', 'Tokyo', 'Warsaw', 'Helsinki', 'Madrid'}

remove()/discard()
We can use remove() and discard() methods to remove items form list.
Example :
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities.remove("Tokyo")
print(cities)
Output:
{'Delhi', 'Berlin', 'Madrid'}

The main difference between remove and discard is that, if we try to delete an
item which is not present in set, then remove() raises an error, whereas
discard() does not raise any error.
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities.remove("Seoul")
print(cities)

Output:
KeyError: 'Seoul'

pop()
This method removes the last item of the set but the catch is that we don’t
know which item gets popped as sets are unordered. However, you can access
the popped item if you assign the pop() method to a variable.
Example 1:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
item = cities.pop()
print(cities)
print(item)

Output:
{'Tokyo', 'Delhi', 'Berlin'}
del
del is not a method, rather it is a keyword which deletes the set entirely.
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
del cities
print(cities)
Output:
NameError: name 'cities' is not defined We get an error because our entire set
has been deleted and there is no variable called cities which contains a set.

Remove Dictionary Items del keyword


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)

What if we don’t want to delete the entire set, we just want to delete all
items within that set?
clear():
This method clears all items in the set and prints an empty set.
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities.clear()
print(cities)

set()
Check if item exists
You can also check if an item exists in the set or not.
Example
info = {"Carla", 19, False, 5.9}
if "Carla" in info:
print("Carla is present.")
else:
print("Carla is absent.")

Output:
Carla is present.
_____________________________________________________________________
_______________________________

What Is a Dictionary?
A dictionary is a kind of data structure that stores items in key-value pairs. A
key is a unique identifier for an item, and a value is the data associated with
that key. Dictionaries often store information such as words and definitions, but
they can be used for much more. Dictionaries are mutable in Python, which
means they can be changed after they are created. They are also unordered,
indicating the items in a dictionary are not stored in any particular order.

Creating a Dictionary
Dictionaries are created using curly braces {}. The key is on the left side of the
colon (:) and the value is on the right. A comma separates each key-value pair.
Creating a Python dictionary is straightforward. Remember to use curly braces
{} and separate each key-value pair with a comma.
You will use the built-in dictionary data type to create a Python dictionary. This
type stores all kinds of data, from integers to strings to lists. The dictionary
data type is similar to a list but uses keys instead of indexes to look up values.
You use the dict() function in Python to create a dictionary. This function takes
two arguments:
The first argument is a list of keys.
The second argument is a list of values.

Check out the example of how to create a dictionary using the dict() function:
# empty dictionary
my_dict = {}
# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}
# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
# from sequence having each item as a pair
my_dict = dict([(1,'apple'), (2,'ball')])

Complexities for Creating a Dictionary


The time complexity of a dictionary is O(len(dict)); because a dictionary must
be created, the hash function must calculate the hash values for each element.
O(N) is the space complexity required to create a dictionary.

Changing and Adding Elements to a Dictionary


In Python, dictionaries are mutable data structures that allow you to store key-
value pairs. Dictionary can be created using the dict() constructor or curly
braces' {}'. Once you have created a dictionary, you can add, remove, or update
elements using the methods dict.update(), dict.pop(), and dict.popitem().
The `dict.update()` method is used to change an element in a dictionary. This
method takes a key and a value as arguments and assigns the value to the key.
It will be added if the key does not exist in the dictionary.

You can use the `dict.pop()` method to remove an element from a dictionary.
This method takes a key value as an argument and removes the key-value pair
from the dictionary. In case when key does not exist in the dictionary,
`dict.pop()` will raise a `KeyError.`

The dict.popitem()` method is used to remove an arbitrary element from a


dictionary, . This method removes a random key-value pair from the dictionary
and returns it as a tuple. If the dictionary is empty, `dict.popitem()` will raise a
`KeyError`.

Accessing Elements of a Dictionary


In Python, dictionaries are accessed by key, not by index. This means you can't
access a dictionary element by using its position in the dictionary. Instead, you
must use the dictionary key.
There are two ways to access a dictionary element in Python. The first is by
using the get() method. This method takes two arguments: the dictionary key
and a default value. If the key is in the dictionary, the get() method will return
the value associated with that key. The get() method will return the default
value if the key is not in the dictionary.
The second way to access a dictionary element is using the [] operator. This
operator takes the dictionary key as an argument and returns the value
associated with the key value. If the key value is not in the dictionary, the []
operator will raise a KeyError.

# get vs [] for retrieving elements


my_dict = {'name': 'Jack', 'age': 26}

# Output: Jack
print(my_dict['name'])

# Output: 26
print(my_dict.get('age'))

# Trying to access keys that don't exist throws an error


# Output None
print(my_dict.get('address'))

# KeyError
print(my_dict['address'])

Methods
In Python, several built-in methods allow us to manipulate dictionaries. These
methods are useful for adding, removing, and changing the values of dictionary
keys. Dictionary methods are a powerful way to work with dictionaries. By
understanding how these methods work, we can more effectively use
dictionaries to store and manipulate data.

Method Description
clear() Removes all the
elements from the
dictionary
copy() Returns a copy of the
dictionary
get() Returns specified key
value
items() Returns an index
having a tuple for every
key-value pair
keys() Returns a list
get() Returns specified key
value
items() Returns an index
having a tuple for every
key-value pair
keys() Returns a list
containing the
dictionary's keys
pop() Removes the element
with the specified key
popitem() Remove last inserted
key-value pair
setdefault() Returns specified key
value. If a key value
does not exist: insert
the specified value of
key
fromkeys() Returns specified keys
and values in dictionary
update() Updates the specified
key-value pairs in
dictionary
values() Returns values lists in
the dictionary
List in a dictionary
dict_list = {1:["I","am"],2:["Sayan","Bhattacharjee"]}
print(dict_list[1])
print(dict_list[2])

Output
Dictionary in a list
list_dict = [{1:"Myself"},{2:"sayan"}]
# print(list_dict)
first_value = list_dict[0]
print(first_value[1])
second_value = list_dict[1]
print(second_value[2])

Output

Difference between List, Tuple, Set, and Dictionary


The following table shows the difference between various Python built-in data
structures.

List Tuple Set Dictionary


A list is a A Tuple is The set data A dictionary
non- also a non- structure is is also a non-
homogeneou homogeneou also a non- homogeneou
s data s data homogeneou s data
structure that structure that s data structure that
stores the stores structure but stores key-
elements in elements in stores the value pairs.
columns of a columns of a elements in a
single row or single row or single row.
multiple rows. multiple rows.
The list can Tuple can be The set can The
be represented be dictionary
represented by ( ) represented can be
by [ ] by { } represented
by { }
The list Tuple allows The Set will The
allows duplicate not allow dictionary
columns of a columns of a elements in a
single row or single row or single row.
multiple rows. multiple rows.
The list can Tuple can be The set can The
be represented be dictionary
represented by ( ) represented can be
by [ ] by { } represented
by { }
The list Tuple allows The Set will The
allows duplicate not allow dictionary
duplicate elements duplicate doesn’t allow
elements elements duplicate
keys.
The list can Tuple can use The set can The
use nested nested use nested dictionary
among all among all among all can use
nested
among all
Example: [1, Example: (1, Example: {1, Example: {1:
2, 3, 4, 5] 2, 3, 4, 5) 2, 3, 4, 5} “a”, 2: “b”, 3:
“c”, 4: “d”, 5:
“e”}
A list can be Tuple can be A set can be A dictionary
created using created using created using can be
the list() the tuple() the set() created using
function function. function the dict()
function.
A list is A tuple is A set is A dictionary
mutable i.e immutable i.e mutable i.e is mutable, its
we can make we can not we can make Keys are not
any changes make any any changes duplicated.
in the list. changes in in the set, its
the tuple. elements are
not
duplicated.
List is Tuple is Set is Dictionary is
ordered ordered unordered ordered
(Python 3.7
and above)
Creating an Creating an Creating a set Creating an
empty list empty Tuple a=set() empty
l=[] t=() b=set(a) dictionary
d={}
ordered ordered unordered ordered
(Python 3.7
and above)
Creating an Creating an Creating a set Creating an
empty list empty Tuple a=set() empty
l=[] t=() b=set(a) dictionary
d={}

Python Dictionaries
Dictionaries are ordered collection of data items. They store multiple items in a
single variable. Dictionary items are key-value pairs that are separated by
commas and enclosed within curly brackets {}.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info)
Output:
{'name': 'Karan', 'age': 19, 'eligible': True}

Accessing Dictionary items:


I. Accessing single values:
Values in a dictionary can be accessed using keys. We can access dictionary
values by mentioning keys either in square brackets or by using get method.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info['name'])
print(info.get('eligible'))
Output:
Karan
True

II. Accessing multiple values:


We can print all the values in the dictionary using values() method.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info.values())
Output:
dict_values(['Karan', 19, True])

III. Accessing keys:


We can print all the keys in the dictionary using keys() method.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info.keys())
Output:
dict_keys(['name', 'age', 'eligible'])

IV. Accessing key-value pairs:


We can print all the key-value pairs in the dictionary using items() method.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info.items())
Output:
dict_items([('name', 'Karan'), ('age', 19), ('eligible', True)])

Accessing Dictionary items in key-value pairs :

dict = {"Name":"Sayan Bhattacharjee" , "Address":"West Bengal" , "Age":24}

for key, value in dict.items():


print(f"{key} : {value}")

Output :

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]

x = thisdict.get("model") [Using get keyword]

x = thisdict.keys()
x = car.keys()
print(x) #before the change
car["color"] = "white"
print(x) #after the change

x = thisdict.values()

x = car.values()
print(x) #before the change
car["year"] = 2020
print(x) #after the change

Check if Key Exists


if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")

Change Dictionary Items


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018

thisdict.update({"year": 2020})

Loop Dictionaries
Print all key names in the dictionary, one by one:
for x in thisdict:
print(x)
for x in thisdict:
print(thisdict[x])

_____________________________________________________________________
_______________________________

Dictionary Methods
Dictionary uses several built-in methods for manipulation.They are listed below

update()
The update() method updates the value of the key provided to it if the item
already exists in the dictionary, else it creates a new key-value pair.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info)
info.update({'age':20})
info.update({'DOB':2001})
print(info)
Output:
{'name': 'Karan', 'age': 19, 'eligible': True}
{'name': 'Karan', 'age': 20, 'eligible': True, 'DOB': 2001}

Removing items from dictionary:


There are a few methods that we can use to remove items from dictionary.
clear():
The clear() method removes all the items from the list.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
info.clear()
print(info)
Output:
{}

pop():
The pop() method removes the key-value pair whose key is passed as a
parameter.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
info.pop('eligible')
print(info)
Output:
{'name': 'Karan', 'age': 19}

popitem():
The popitem() method removes the last key-value pair from the dictionary.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True, 'DOB':2003}
info.popitem()
print(info)
Output:
{'name': 'Karan', 'age': 19, 'eligible': True}

del:
we can also use the del keyword to remove a dictionary item.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True, 'DOB':2003}
del info['age']
print(info)
Output:
{'name': 'Karan', 'eligible': True, 'DOB': 2003}

If key is not provided, then the del keyword will delete the dictionary entirely.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True, 'DOB':2003}
del info
print(info)
Output:
NameError: name 'info' is not defined

Copy a Dictionary
Example-1
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)

Example-2
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)

Nested Dictionaries
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}

Access Items in Nested Dictionaries


print(myfamily["child2"]["name"])
_____________________________________________________________________
_______________________________

for-else in Loop
As you have learned before, the else clause is used along with the if statement.
Python allows the else keyword to be used with the for and while loops too. The
else block appears after the body of the loop. The statements in the else block
will be executed after all iterations are completed. The program exits the loop
only after the else block is executed.

Syntax
for counter in sequence:
#Statements inside for loop block
else:
#Statements inside else block

Example:
for x in range(5):
print ("iteration no {} in for loop".format(x+1))
else:
print ("else block in loop")
print ("Out of loop")

Output:
iteration no 1 in for loop
iteration no 2 in for loop
iteration no 3 in for loop
iteration no 4 in for loop
iteration no 5 in for loop
else block in loop
Out of loop

_____________________________________________________________________
_______________________________

Exception Handling
Exception handling is the process of responding to unwanted or unexpected
events when a computer program runs. Exception handling deals with these
events to avoid the program or system crashing, and without this process,
exceptions would disrupt the normal operation of a program.

Exceptions in Python
Python has many built-in exceptions that are raised when your program
encounters an error (something in the program goes wrong).
When these exceptions occur, the Python interpreter stops the current process
and passes it to the calling process until it is handled. If not handled, the
program will crash.

Python try...except
try….. except blocks are used in python to handle errors and exceptions. The
code in try block runs when there is no error. If the try block catches the error,
then the except block is executed.
Syntax:
try:
#statements which could generate
except:
#Soloution of generated exception

Example:
try:
num = int(input("Enter an integer: "))
except ValueError:
print("Number entered is not an integer.")

Output:
Enter an integer: 6.022
Number entered is not an integer.

_____________________________________________________________________
_______________________________

Finally Clause—>>
The finally code block is also a part of exception handling. When we handle
exception using the try and except block, we can include a finally block at the
end. The finally block is always executed, so it is generally used for doing the
concluding tasks like closing file resources or closing database connection or
may be ending the program execution with a delightful message.
Syntax:
try:
#statements which could generate
#exception
except:
#solution of generated exception
finally:
#block of code which is going to
#execute in any situation

Try-except and finally block


try:
num = int(input("Enter an integer: "))
except ValueError:
print("Number entered is not an integer.")
else:
print("Integer Accepted.")
finally:
print("This block is always executed.")

Output 1:
Enter an integer: 19
Integer Accepted.
This block is always executed.

Rather than using finally block we can use normal print function to print a
statement. But while we use a function we can’t execute statements after
producing an error. Control will go to main body where function is called. In the
function we have to use “finally” block if we want to execute our code.

def func1():
try:
l = [1, 5, 6, 7]
i = int(input("Enter the index: "))
print(l[i])
return 1
except:
print("Some error occurred")
return 0

finally:
print("I am always executed")
# print("I am always executed")
x = func1()
print(x)

_____________________________________________________________________
_______________________________

Raising Custom errors⸺>>>

Example 1 —>
salary = int(input("Enter salary amount: "))
if not 2000 < salary < 5000:
raise ValueError("Not a valid salary")

Example 2 —>
a = int(input("Enter any value between 5 and 9"))
if(a<5 or a>9):
raise ValueError("Value should be between 5 and 9")

_____________________________________________________________________
_______________________________

Function Composition in Python—>>>


Function composition is the way of combining two or more functions in such a
way that the output of one function becomes the input of the second function
and so on. For example, let there be two functions “F” and “G” and their
composition can be represented as F(G(x)) where “x” is the argument and
output of G(x) function will become the input of F() function.

Example 1 —>
def add(x):
return x + 2

def multiply(x):
return x * 2

print("Adding 2 to 5 and multiplying the result with 2: ",


multiply(add(5)))

OUTPUT:
Adding 2 to 5 and multiplying the result with 2: 14

_____________________________________________________________________
_______________________________

Variable Names—>>
A variable can have a short name (like x and y) or a more descriptive name
(age, carname, total_volume).
Rules for Python variables:
● A variable name must start with a letter or the underscore character
● A variable name cannot start with a number
● A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
● Variable names are case-sensitive (age, Age and AGE are three different
variables)

#Legal variable names:


myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"

#Illegal variable names:


2myvar = "John"
my-var = "John"
my var = "John"

_____________________________________________________________________
_______________________________

Parameter and Argument in python—>>>

In Python, parameters are the variables that are defined in the function
declaration. Arguments are the values that are passed to a function when it is
called. The terms parameter and argument are often used interchangeably, but
they have different meanings.

Here is an example to illustrate the difference between parameters and


arguments:

def add_numbers(a, b):


return a + b
print(add_numbers(1, 2))

In this example, the parameters are a and b. The arguments are 1 and 2. When
the function is called, the arguments are passed to the parameters. The
function then uses the values of the parameters to calculate the sum of the two
numbers.

_____________________________________________________________________
_______________________________
Logical Operators :
Operator Description Example Try it
and Returns True if x < 5 and x < 10 Try it »
both statements
are true
or Returns True if x < 5 or x < 4 Try it »
one of the
statements is
true
not Reverse the not(x < 5 and x
result, returns < 10)
False if the
result is true

_____________________________________________________________________
_______________________________

Declare an Empty List in Python—>>


Declaring an empty list can be achieved in two ways i.e. either by using square
brackets[] or using the list() constructor.
Create an Empty List in Python using Square Brackets [ ]

Example:
a = []
print("Values of a:", a)
print("Type of a:", type(a))
print("Size of a:", len(a))

Declare an Empty tuple in Python—>>>


There are two ways to initialize an empty tuple. You can initialize an empty tuple
by having () with no values in them.

# Way 1
emptyTuple = ()

You can also initialize an empty tuple by using the tuple function.
# Way 2
emptyTuple = tuple()

Declare an Empty dictionary in Python—>>>


Here are two ways to create an empty dictionary in Python:

. Using curly braces


my_dict = {}
. Using the dict() function:
my_dict = dict()

Declare an Empty dictionary in Python—>>>


There are two ways to create an empty set in Python:

Using the built-in set() function—>>>


my_set = set()
This will create an empty set called my_set.

using curly braces—>>>


my_set = {}

_____________________________________________________________________
_______________________________

Enumerate function in python


The enumerate function is a built-in function in Python that allows you to loop
over a sequence (such as a list, tuple, or string) and get the index and value of
each element in the sequence at the same time. Here's a basic example of how
it works:

# Loop over a list and print the index and value of each element
fruits = ['apple', 'banana', 'mango']
for index, fruit in enumerate(fruits):
print(index, fruit)

The output of this code will be:


0 apple
1 banana
2 mango

As you can see, the enumerate function returns a tuple containing the index
and value of each element in the sequence. You can use the for loop to unpack
these tuples and assign them to variables, as shown in the example above.

_____________________________________________________________________
_______________________________

How importing in python works


Importing in Python is the process of loading code from a Python module into
the current script. This allows you to use the functions and variables defined in
the module in your current script, as well as any additional modules that the
imported module may depend on.
To import a module in Python, you use the import statement followed by the
name of the module. For example, to import the math module, which contains a
variety of mathematical functions, you would use the following statement:
import math

Once a module is imported, you can use any of the functions and variables
defined in the module by using the dot notation. For example, to use the sqrt
function from the math module, you would write:
import math

result = math.sqrt(9)
print(result) # Output: 3.0

from keyword
You can also import specific functions or variables from a module using the
from keyword. For example, to import only the sqrt function from the math
module, you would write:
from math import sqrt

result = sqrt(9)
print(result) # Output: 3.0

You can also import multiple functions or variables at once by separating them
with a comma:
from math import sqrt, pi

result = sqrt(9)
print(result) # Output: 3.0

print(pi) # Output: 3.141592653589793

importing everything
It's also possible to import all functions and variables from a module using the *
wildcard. However, this is generally not recommended as it can lead to
confusion and make it harder to understand where specific functions and
variables are coming from.
from math import *

result = sqrt(9)
print(result) # Output: 3.0

print(pi) # Output: 3.141592653589793

Python also allows you to rename imported modules using the as keyword. This
can be useful if you want to use a shorter or more descriptive name for a
module, or if you want to avoid naming conflicts with other modules or variables
in your code.

The "as" keyword


import math as m
result = m.sqrt(9)
print(result) # Output: 3.0

print(m.pi) # Output: 3.141592653589793

The dir function


Finally, Python has a built-in function called dir that you can use to view the
names of all the functions and variables defined in a module. This can be
helpful for exploring and understanding the contents of a new module.
import math

print(dir(math))

This will output a list of all the names defined in the math module, including
functions like sqrt and pi, as well as other variables and constants.
In summary, the import statement in Python allows you to access the functions
and variables defined in a module from within your current script. You can
import the entire module, specific functions or variables, or use the * wildcard
to import everything. You can also use the as keyword to rename a module, and
the dir function to view the contents of a module.

_____________________________________________________________________
_______________________________

Lambda Functions in Python


In Python, a lambda function is a small anonymous function without a name. It
is defined using the lambda keyword and has the following syntax:

lambda arguments: expression

Lambda functions are often used in situations where a small function is


required for a short period of time. They are commonly used as arguments to
higher-order functions, such as map, filter, and reduce.
Here is an example of how to use a lambda function:
# Function to double the input
def double(x):
return x * 2

# Lambda function to double the input


lambda x: x * 2

The above lambda function has the same functionality as the double function
defined earlier. However, the lambda function is anonymous, as it does not have
a name.
Lambda functions can have multiple arguments, just like regular functions. Here
is an example of a lambda function with multiple arguments:
# Function to calculate the product of two numbers
def multiply(x, y):
return x * y

# Lambda function to calculate the product of two numbers


lambda x, y: x * y

Lambda functions can also include multiple statements, but they are limited to
a single expression. For example:
# Lambda function to calculate the product of two numbers,
# with additional print statement
lambda x, y: print(f'{x} * {y} = {x * y}')

_____________________________________________________________________
_______________________________

'is' vs '==' in Python


In Python, is and == are both comparison operators that can be used to check
if two values are equal. However, there are some important differences between
the two that you should be aware of.
The is operator compares the identity of two objects, while the == operator
compares the values of the objects. This means that is will only return True if
the objects being compared are the exact same object in memory, while == will
return True if the objects have the same value.
For example:
a = [1, 2, 3]
b = [1, 2, 3]

print(a == b) # True
print(a is b) # False

In this case, a and b are two separate lists that have the same values, so ==
returns True. However, a and b are not the same object in memory, so is returns
False.

One important thing to note is that, in Python, strings and integers are
immutable, which means that once they are created, their value cannot be
changed. This means that, for strings and integers, is and == will always return
the same result:
a = "hello"
b = "hello"

print(a == b) # True
print(a is b) # True

a=5
b=5

print(a == b) # True
print(a is b) # True

In these cases, a and b are both pointing to the same object in memory, so is
and == both return True.
For mutable objects such as lists and dictionaries, is and == can behave
differently. In general, you should use == when you want to compare the values
of two objects, and use is when you want to check if two objects are the same
object in memory.

_____________________________________________________________________
_______________________________

Advantages of recursion:
● Simplifies complex problems:
Recursion can simplify complex problems by breaking them down into
smaller, more manageable pieces. Recursive code can be more readable
and easier to understand than iterative code.

● Reduces code length:


Recursion can often reduce the length of code. For example, the following
recursive function calculates the factorial of a number:

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)

Disadvantages of recursion:
● Difficult to trace:
Recursion can be difficult to trace, especially for complex functions. This
can make it difficult to debug recursive code.

● Requires an if statement:
Every recursive function must have an if statement to force the function to
return without the recursive call being executed. This can make recursive
code more complex and difficult to understand.

● Memory usage:
Recursive functions can use a lot of memory, especially for large input
values. This can lead to stack overflows.

● Time complexity:
Recursive functions can have high time complexity, especially for large
input values. This can make recursive functions slow.

_____________________________________________________________________
_______________________________

A recursion error in Python occurs when the maximum recursion


depth is exceeded. This means that a recursive function has been
called too many times without reaching its base case.

There are a few things that can cause a recursion error:


● The recursive function may not have a base case. This is the case when the
function continues to call itself indefinitely.
● The recursive function may be calling itself too many times. This can
happen if the function is not properly optimized.
● The recursion limit may be set too low. The recursion limit is the maximum
number of times that a function can call itself before it raises an error.

To fix a recursion error, you can try the following:


● Check to make sure that the recursive function has a base case.
● Optimize the recursive function to reduce the number of times that it calls
itself.
● Increase the recursion limit.

Here is an example of a recursive function that does not have a


base case :
def p():
print("Hello")
p()
p()
_____________________________________________________________________
_______________________________

● upper(): Converts all characters in a string to uppercase.


● find(substring): Returns the lowest index in the string where substring is
found.
● lower(): Converts all characters in a string to lowercase.
● capitalize(): Capitalizes the first character of the string.
● count(substring): Returns the number of occurrences of substring in the
string.
● join(iterable): Concatenates elements of an iterable (e.g., list) into a string,
with the specified delimiter.
● len(): Returns the length of the string.
● isalnum(): Returns True if all characters in the string are alphanumeric.
● isalpha(): Returns True if all characters in the string are alphabetic.
● isdigit(): Returns True if all characters in the string are digits.
● islower(): Returns True if all alphabetic characters in the string are
lowercase.
● isnumeric(): Returns True if all characters in the string are numeric.
● isspace(): Returns True if all characters in the string are whitespace.
● isupper(): Returns True if all alphabetic characters in the string are
uppercase.
● max(): Returns the character with the highest Unicode code point in the
string.
● min(): Returns the character with the lowest Unicode code point in the
string.
● replace(old, new): Returns a copy of the string with all occurrences of old
replaced by new.
● split(separator): Splits the string into a list of substrings using the
specified separator.

# Accessing Values in Strings


my_string = "Hello"
print(my_string[0]) # Output: H

# Updating Strings
# Strings are immutable, so we create a new string
new_string = my_string + " World"
print(new_string) # Output: Hello World

# Slicing Strings
print(my_string[1:4]) # Output: ell

# String Methods
print(my_string.upper()) # Output: HELLO
print(my_string.find('e')) # Output: 1
print(my_string.lower()) # Output: hello
print(my_string.capitalize()) # Output: Hello
print(my_string.count('l')) # Output: 2
print(' '.join(['Hello', 'World'])) # Output: Hello World
print(len(my_string)) # Output: 5
print(my_string.isalnum()) # Output: True
print(my_string.isalpha()) # Output: True
print(my_string.isdigit()) # Output: False
print(my_string.islower()) # Output: False
print(my_string.isnumeric()) # Output: False
print(my_string.isspace()) # Output: False
print(my_string.isupper()) # Output: False
print(max(my_string)) # Output: o
print(min(my_string)) # Output: H
print(my_string.replace('Hello', 'Hi')) # Output: Hi
print(my_string.split('l')) # Output: ['He', '', 'o']

_____________________________________________________________________
_______________________________

Python Class and Objects


A class is a blueprint or a template for creating objects, providing initial values
for state (member variables or attributes), and implementations of behavior
(member functions or methods). The user-defined objects are created using
the class keyword.

Creating a Class:
Let us now create a class using the class keyword.
class Details:
name = "Rohan"
age = 20

Creating an Object:
Object is the instance of the class used to access the properties of the class.
When an object of a class is created, the class is said to be instantiated.
Example:
obj1 = Details()

Now we can print values:


Example:
class Details:
name = "Rohan"
age = 20

obj1 = Details()
print(obj1.name)
print(obj1.age)

Output:
Rohan
20

_____________________________________________________________________
_______________________________

Inner Class in Python


A class defined in another class is known as an inner class or nested class. If
an object is created using child class means inner class then the object can
also be used by parent class or root class. A parent class can have one or more
inner classes but generally inner classes are avoided.
Why inner class?
For the grouping of two or more classes. Suppose we have two classes remote
and battery. Every remote needs a battery but a battery without a remote won’t
be used. So, we make the Battery an inner class to the Remote. It helps us to
save code. With the help of the inner class or nested class, we can hide the
inner class from the outside world. Hence, Hiding the code is another good
feature of the inner class. By using the inner class, we can easily understand
the classes because the classes are closely related. We do not need to search
for classes in the whole code, they all are almost together. Though inner or
nested classes are not used widely in Python it will be a better feature to
implement code because it is straightforward to organize when we use inner
class or nested class.

Types of inner classes are as follows:


. Multiple inner class
. Multilevel inner class
Multiple inner class
The class contains one or more inner classes known as multiple inner classes.
We can have multiple inner class in a class, it is easy to implement multiple
inner classes.
Multilevel inner class
The class contains an inner class and that inner class again contains another
inner class, this hierarchy is known as the multilevel inner class.
_____________________________________________________________________
_______________________________

Instance objects
An instance object is a specific occurrence of a class. It is created when you
call the constructor of a class. The constructor is a special method that is used
to initialize the object.
For example, the following code creates an instance of the Employee class:
Syntax
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary

emp1 = Employee("Zara", 2000)

_____________________________________________________________________
_______________________________

Built-In Class Attributes in Python


In Python, built-in class attributes are properties associated with a class itself,
rather than its instances. Common built-in class attributes include __doc__,
which holds the class documentation string, and __name__, which stores the
class name. __module__ indicates the module in which the class is defined, and
__bases__ holds a tuple of the base classes. These attributes provide metadata
about the class and are accessible.

__doc__ Attribute in Python


The __doc__ attribute contains the string of the class documents.
Documentation strings, often called docstrings, are used to describe what a
class or function does. Docstrings are enclosed in triple quotes (”” or “””) and
are usually placed immediately after the class or function definition.
Syntax:
print(ClassName.__doc__)
Example
class GeeksCourse:
"""
This class represents a programming course on GeeksforGeeks.
It covers various topics and provides valuable resources for learners.
"""
print(GeeksCourse.__doc__)
__name__ Attribute in Python
The __name__ is a special attribute in Python that provides the name of the
class to which it belongs. It is used to retrieve the name of a class within the
class definition or in instances of the class.
Syntax :
print(ClassName.__name__)
In the below example, the class Geeks is defined with a docstring. By
printing Geeks.__name__, the __name__ attribute is accessed, and it outputs
the name “Geeks.”
Example :
class Geeks:
"""
Example Class
"""
print(Geeks.__name__)

__module__ Attribute in Python


The __module__ attribute in Python represents the name of the module in
which a class is defined. It allows you to access and retrieve the module name
to which a particular class belongs.__module__ ` contains the name of that
module. This attribute is especially useful when working with courses defined in
modules.
Syntax:
print(ClassName.__module__)
In the below example, the class Geeks is defined with a docstring. By
printing Geeks.__module__, the __module__ attribute is accessed, and it
outputs the name of the module in which the class is defined.
Example :
class Geeks:
"""
Class
"""
print(Geeks.__module__)

__bases__ Attribute in Python


The __bases__ attribute in Python is used to access a tuple containing the
base classes of a class. It provides information about the direct parent classes
from which the class inherits.
Syntax:
print(ClassName.__bases__)

__dict__ Attribute in Python


The __dict__ attribute in Python is a dictionary containing the namespace of a
class or instance. It holds the attributes and methods defined for the class or
object, allowing dynamic inspection and manipulation of its members.
Syntax:
print(ClassName.__dict__)

_____________________________________________________________________
_______________________________

self parameter in class


The self parameter is a reference to the current instance of the class, and is
used to access variables that belongs to the class.
It must be provided as the extra parameter inside the method definition.

Example:

class Details:
name = "Rohan"
age = 20
def desc(self):
print("My name is", self.name, "and I'm", self.age, "years old.")

obj1 = Details()
obj1.desc()

Output:
My name is Rohan and I'm 20 years old.

Another Example
class Person:
name = "Harry"
occupation = "Software Developer"
networth = 10

def info(self):
print(f"{self.name} is a {self.occupation}")

a = Person()
b = Person()
c = Person()

a.name = "Shubham"
a.occupation = "Accountant"

b.name = "Nitika"
b.occupation = "HR"
a.info()
b.info()
c.info()

_____________________________________________________________________
_______________________________

Constructors
A constructor is a special method in a class used to create and initialize an
object of a class. There are different types of constructors. Constructor is
invoked automatically when an object of a class is created.
A constructor is a unique function that gets called automatically when an object
is created of a class. The main purpose of a constructor is to initialize or assign
values to the data members of that class. It cannot return any value other than
None.

Syntax of Python Constructor


def __init__(self):
# initializations

init is one of the reserved functions in Python. In Object Oriented Programming,


it is known as a constructor.

Types of Constructors in Python


. Parameterized Constructor
. Default Constructor

Parameterized Constructor in Python


When the constructor accepts arguments along with self, it is known as
parameterized constructor.
These arguments can be used inside the class to assign the values to the data
members.

Example:
class Details:
def __init__(self, animal, group):
self.animal = animal
self.group = group

obj1 = Details("Crab", "Crustaceans")


print(obj1.animal, "belongs to the", obj1.group, "group.")

Output:
Crab belongs to the Crustaceans group.
Default Constructor in Python
When the constructor doesn't accept any arguments from the object and has
only one argument, self, in the constructor, it is known as a Default constructor.

Example:
class Details:
def __init__(self):
print("animal Crab belongs to Crustaceans group")
obj1=Details()

Output:
animal Crab belongs to Crustaceans group

_____________________________________________________________________
_______________________________

Inheritance->
Inheritance allows us to define a class that inherits all the methods and
properties from another class.Inheritance is one in which a new class is
created that inherits the properties of the already exist class. It supports the
concept of code reusability and reduces the length of the code in object-
oriented programming.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived
class.

Syntax ->
class Student(Person):
#code
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.

# Base class
class Parent:
def func1(self):
print("This function is in parent class.")

# Derived class
class Child(Parent):
def func2(self):
print("This function is in child class.")

# Driver's code
object = Child()
object.func1()
object.func2()

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.
class Mother:
def mother(self):
print("She take cares of household things")

# Base class2
class Father:
def father(self):
print("He take cares of outer things")

# Derived class

class Child(Mother, Father):


def son(self):
print("He take cares of parents when he grows
older")

# Driver's code
s1 = Child()
s1.mother()
s1.father()
s1.son()
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.
class Grandfather:
def grandf(self):
print("He is my grandfather")

# Intermediate class

class Father(Grandfather):
def SonOfGrandFather(self):
print("He is my father")

# Derived class

class Son(Father):
def SonOfFather(self):
print("He is my son")

#Driver code
s1 = Son()
s1.grandf()
s1.SonOfGrandFather()
s1.SonOfFather()

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.
# Base class
class Parent:
def func1(self):
print("This function is in parent class.")

# Derived class1
class Child1(Parent):
def func2(self):
print("This function is in child 1.")

# Derivied class2
class Child2(Parent):
def func3(self):
print("This function is in child 2.")

object1 = Child1()
object2 = Child2()
object1.func1()
object1.func2()
object2.func1()
object2.func3()

Hybrid Inheritance:
Inheritance consisting of multiple types of inheritance is called hybrid
inheritance.
class School:
def func1(self):
print("This function is in school.")

class Student1(School):
def func2(self):
print("This function is in student 1. ")

class Student2(School):
def func3(self):
print("This function is in student 2.")

class Student3(Student1, School):


def func4(self):
print("This function is in student 3.")

object = Student3()
object.func1()
object.func2()

Difference between Inheritance and Polymorphism:


S.NO Inheritance Polymorphism
1. Inheritance is one Whereas
in which a new polymorphism is
class is created that which can be
(derived class) defined in
S.NO Inheritance Polymorphism
1. Inheritance is one Whereas
in which a new polymorphism is
class is created that which can be
(derived class) defined in
that inherits the multiple forms.
features from the
already existing
class(Base class).
2. It is basically Whereas it is
applied to basically applied
classes. to functions or
methods.
3. Inheritance Polymorphism
supports the allows the object
concept of to decide which
reusability and form of the
reduces code function to
length in object- implement at
oriented compile-time
programming. (overloading) as
well as run-time
(overriding).
4. Inheritance can Whereas it can be
be single, hybrid, compiled-time
multiple, polymorphism
hierarchical and (overload) as well
multilevel as run-time
inheritance. polymorphism
(overriding).
5. It is used in While it is also
pattern designing. used in pattern
designing.
6. Example : Example :
The class bike The class bike
can be inherit can have method
from the class of name set_color(),
two-wheel which changes
5. It is used in While it is also
pattern designing. used in pattern
designing.
6. Example : Example :
The class bike The class bike
can be inherit can have method
from the class of name set_color(),
two-wheel which changes
vehicles, which is the bike’s color
turn could be a based on the
subclass of name of color you
vehicles. have entered.

_____________________________________________________________________
_______________________________

Polymorphism in Python
In object-oriented-based Python programming, Polymorphism means the same
function name is being used for different types. Each function is differentiated
based on its data type and number of arguments. So, each function has a
different signature. This allows developers to write clean, readable, and resilient
codes.

There are mainly four types ->


. Duck typing
. Operator overloading
. Method overloading
. Method Overriding

. Duck Typing : Duck typing is a type system where the class of an object is
not checked when a method is called. Instead, the method is only called if
the object has the required attributes. This allows for more flexibility and
code reuse, as objects of different classes can be used interchangeably as
long as they have the same methods.
This will give us a error because Cat class did not have walk() method.

. Method overloading : Two or more methods have the same name but
different numbers of parameters or different types of parameters, or both.
These methods are called overloaded methods and this is called
.

method overloading. This cannot be achieved directly in Python. It can be


achieved by Default Arguments and *args.

Using Default Argument

Using *args
. Method Overriding : Method overriding is an ability of any object-oriented
programming language that allows a subclass or child class to provide a
specific implementation of a method that is already provided by one of its
super-classes or parent classes. When a method in a subclass has the
same name, same parameters or signature and same return type(or sub-
type) as a method in its super-class, then the method in the subclass is
said to override the method in the super-class.
. Operator Overloading in Python
Operator Overloading means giving extended meaning beyond their predefined
operational meaning. For example operator + is used to add two integers as
well as join two strings and merge two lists. It is achievable because ‘+’
operator is overloaded by int class and str class. You might have noticed that
the same built-in operator or function shows different behavior for objects of
different classes, this is called Operator Overloading.
_____________________________________________________________________
_______________________________

What is Data Hiding?


Data hiding is a part of object-oriented programming, which is generally used
to hide the data information from the user. It includes internal object details
such as data members, internal working. It maintained the data integrity and
restricted access to the class member. The main working of data hiding is that
it combines the data and functions into a single unit to conceal data within a
class. We cannot directly access the data from outside the class.
This process is also known as the data encapsulation. It is done by hiding the
working information to user. In the process, we declare class members as
private so that no other class can access these data members. It is accessible
only within the class.

Data Hiding in Python


Python is the most popular programming language as it applies in every
technical domain and has a straightforward syntax and vast libraries. In the
official Python documentation, Data hiding isolates the client from a part of
program implementation. Some of the essential members must be hidden from
the user. Programs or modules only reflected how we could use them, but users
cannot be familiar with how the application works. Thus it provides security and
avoiding dependency as well.
We can perform data hiding in Python using the __ double underscore before
prefix. This makes the class members private and inaccessible to the other
classes.

Example -
class CounterClass:
__privateCount = 0
def count(self):
self.__privateCount += 1
print(self.__privateCount)

counter = CounterClass()
counter.count()
counter.count()
print(counter.__privateCount)

Output:
1
2
Traceback (most recent call last):
File "<string>", line 17, in <module>
AttributeError: 'CounterClass' object has no attribute '__privateCount'

However we can access the private member using the class name->
print(counter.CounterClass__privatecounter)

Output:
1
2
2

Advantages of Data Hiding


● The class objects are disconnected from the irrelevant data.
● It enhances the security against hackers that are unable to access
important data.
● It isolates object as the basic concept of OOP.
● It helps programmer from incorrect linking to the corrupt data.
● We can isolate the object from the basic concept of OOP.
● It provides the high security which stops damage to violate data by hiding it
from the public.
Disadvantages of Data Hiding
Every coin has two sides if there are advantages then there will be
disadvantage as well. Here are the some disadvantages are given below.
● Sometimes programmers need to write the extra lien of the code.
● The data hiding prevents linkage that act as link between visible and
invisible data makes the object faster.
● It forces the programmers to write extra code to hide the important data
from the common users.

You might also like