— Python Programming——
— Python Programming——
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 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
_____________________________________________________________________
___________________________________
Example->
a=1
print(type(a))
b = "1"
print(type(b))
Type—>>
3. Boolean data:
Boolean data consists of values True or False.
Output:
[8, 2.3, [-4, 5], ['apple', 'banana']]
Output:
(('parrot', 'sparrow'), ('Lion', 'Tiger'))
Example:
dict1 = {"name":"Sakshi", "age":20, "canVote":True}
print(dict1)
Output:
{'name': 'Sakshi', 'age': 20, 'canVote': True}
_____________________________________________________________________
___________________________________
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 .
Ouput:
<class 'int'>
<class 'float'>
10.0
<class 'float'>
_____________________________________________________________________
___________________________________
_____________________________________________________________________
___________________________________
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
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.
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.")
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")
_____________________________________________________________________
___________________________________
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
Output:
A, b, h, i, s, h, e, k,
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.
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
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'
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
Example1:
Example1:
return Statement
The return statement is used to return the value of the expression back to the
calling function.
Example:
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]
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
Output:
Yellow is present.
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.
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.
Output:
['dog', 'pig', 'goat’]
Here, jump index is 3. Hence it prints every 3rd element within given index.
_____________________________________________________________________
_______________________________
index = 0
while index < len(my_list):
print(my_list[index])
index += 1
Output:
12345
def square(x):
return x ** 2
5. Using enumerate():
enumerate() can be used to iterate over both the elements and their indices:
python
Output:
Index 0: 1
Index 1: 2
Index 2: 3
Index 3: 4
Index 4: 5
Examples:
● Slice with Positive Indices:
my_list = [1, 2, 3, 4, 5, 6, 7, 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]
● 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]
my_list = [1, 2, 3, 4, 5]
my_list = [1, 2, 3, 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]
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]
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]
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']
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)
_____________________________________________________________________
_______________________________
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]
Output:
Spain
Italy
India
Output:
Germany
India
Italy
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.
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":
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
_____________________________________________________________________
_______________________________
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
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
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.
# 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:
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.
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'}
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'}
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'}
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.
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')])
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.`
# Output: Jack
print(my_dict['name'])
# Output: 26
print(my_dict.get('age'))
# 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
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}
Output :
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
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
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}
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
}
}
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
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)
_____________________________________________________________________
_______________________________
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")
_____________________________________________________________________
_______________________________
Example 1 —>
def add(x):
return x + 2
def multiply(x):
return x * 2
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)
_____________________________________________________________________
_______________________________
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.
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
_____________________________________________________________________
_______________________________
Example:
a = []
print("Values of a:", a)
print("Type of a:", type(a))
print("Size of a:", len(a))
# Way 1
emptyTuple = ()
You can also initialize an empty tuple by using the tuple function.
# Way 2
emptyTuple = tuple()
_____________________________________________________________________
_______________________________
# 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)
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.
_____________________________________________________________________
_______________________________
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
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
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.
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.
_____________________________________________________________________
_______________________________
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 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}')
_____________________________________________________________________
_______________________________
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.
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.
_____________________________________________________________________
_______________________________
# 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']
_____________________________________________________________________
_______________________________
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()
obj1 = Details()
print(obj1.name)
print(obj1.age)
Output:
Rohan
20
_____________________________________________________________________
_______________________________
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
_____________________________________________________________________
_______________________________
_____________________________________________________________________
_______________________________
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.
Example:
class Details:
def __init__(self, animal, group):
self.animal = animal
self.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
# 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.")
object = Student3()
object.func1()
object.func2()
_____________________________________________________________________
_______________________________
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.
. 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
.
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.
_____________________________________________________________________
_______________________________
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