0% found this document useful (0 votes)
26 views135 pages

1.0.imp Python Notes-yogesh

python notes for prractice
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
26 views135 pages

1.0.imp Python Notes-yogesh

python notes for prractice
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 135

Python Notes

INTRODUCTION:
Python Comments:

Single line Comment

 #print(“Hello All”)—It will not print

 print("Hello All") #“how r u” It will print Hello All and ignore how r u.
Multiline Comment
'''
print("Hello All")
print("How r u")
print("All Good?")
'''
Python Quotations:
Python supports the single quote and the double quote for string literals.
 print(‘We need a chaperone');

 print("We need a 'chaperone”);

Python Indentation
 if 2>1:
print("2 is the bigger person");

'''--- It will not work becz of indents are not given



if 2>1:
print("2 is the bigger 1");--- It will work
Space should be privided.space left side is called indent

Python Keywords
reserved words used in Python programming that have special meanings to the interpreter.
We cannot use a keyword as a variable name, function name, or any other identifier.
Python Keywords List
False await Else import pass
None break Except in raise
True class Finally is return
and continue For lambda try
as Def From nonlocal while
assert Del Global not with
async Elif If or yield

Python Identifiers
Identifier is a user-defined name given to a variable, function, class, module, etc. The
identifier is a combination of character digits and an underscore. They are case-sensitive
i.e., ‘Name and ‘name’, and ‘NAME’ are three different identifiers in python.
Rules for Naming Python Identifiers
 It cannot be a reserved python keyword.
 It should not contain white space.
 It can be a combination of A-Z, a-z, 0-9, or underscore.
 It should start with an alphabet character or an underscore ( _ ).
 It should not contain any special character other than an underscore ( _ )
 We cannot use special symbols like !, @, #, $, and so on
 The first letter of an identifier cannot be a digit.

Python Variables:
Python variables are the reserved memory locations used to store values within a Python
Program. This means that when you create a variable you reserve some space in the
memory.
Swapping Variables
Swapping means interchanging values. To swap Python variables, you don’t need to do
much.
a,b='red','blue'
a,b=b,a

The rules to name Variables are given below.


 The first character of the variable must be an alphabet or underscore ( _ ).
 All the characters except the first character may be an alphabet of lower-case(a-z),
upper-case (A-Z), underscore, or digit (0-9).
 Variables name must not contain any white-space, or special character (!, @, #, %, ^, &,
*).
 Variables name must not be similar to any keyword defined in the language.
 Variables names are case sensitive; for example, myname, and MyName is not the same.

I. Python Data Types

1.
Python Numbers
There are four numeric Python data types.
a. int
int stands for integer. This Python Data Type holds signed integers. We can use the type()
function to find which class it belongs to.
>>> a=-7
>>> print(type(a))
Output
<class ‘int’>

b. float
This Python Data Type holds floating-point real values. An int can only store the number 3,
but float can store 3.25 if you want.
>>> a=3.0
>>> print(type(a))
Output
<class ‘float’>

c. long
This Python Data type holds a long integer of unlimited length. But this construct does not
exist in Python 3.x.

d. complex
This Python Data type holds a complex number. A complex number looks like this: a+bj Here,
a and b are the real parts of the number, and j is imaginary.
>>> a=2+3j
>>> print(type(a))
Output
<class ‘complex’>

2. Strings

1. capitalize() 6. Isinstance () 11. isnumeric() 16. upper()

2. casefold() 7. index() 12. isdigit() 17. title()

3. count() 8. isalnum() 13. islower() 18. len()


A string is a sequence of characters.
>>> city='Ahmedabad' 9. isalpha()
4. endswith() 14. istitle() 20. swapcase()
String Multiplication
5. find() 10. isdecimal() 15.operation
isupper() "Hello" *2 returns
21.join()
The operator * is known as a repetition operator as the Hello
Hello.
a="Hello"
print(a*2)
String Methods
1. capitalize()
(Converts the first letter to uppercase)
print(text.capitalize())

>>print('hi there Yogesh IS here'.capitalize())


>>Hi there yogesh is here

2. casefold()
(Converts all characters to lowercase, including accented characters)
# print(text.casefold())
print('hi there Yogesh IS here'.casefold())
hi there yogesh is here

3. count()
Example: "Mississippi".count("ss")
Output: 2 (Counts the number of occurrences of "ss" within the string)
# print(text.count("e"))

4. endswith()
returns True if a string ends with the given suffix, otherwise returns False.
print(text.endswith("TesTiNG"))

5. find()
returns the lowest index or first occurrence of the substring if it is found in a given string.
If it is not found, then it returns -1.
Syntax: str_obj.find(sub, start, end)
Parameters:
 sub: Substring that needs to be searched in the given string.
 start (optional): Starting position where the substring needs to be checked
within the string.
 end (optional): End position is the index of the last value for the specified
range. It is excluded while checking.
Return: Returns the lowest index of the substring if it is found in a given string. If it’s not
found then it returns -1.
# print(text.find('A'))
# print(text.find('Aut'))
# print(text.find('A',0))
# print(text.find('A',11))
# print(text.find('A',2,3))

6. Isinstance ()
Use the isinstance() function to tell if Python variables belong to a particular class. It takes
two parameters- the variable/value, and the class.
>>> a=2+3j
>>> print(type(a))
>>> print(isinstance(a,complex))
print(isinstance(10,int))
print(isinstance('10',int))
print(isinstance('10',str))

True
False
True

7. index()
Method allows a user to find the index of the first occurrence of an existing substring
inside a given string.
Syntax- index(sub, start, end])

Example: "How much wood would a woodchuck chuck?".index("wood")


Output: 3
(Same as find() but raises a ValueError if the substring is not found)
# print(String.index('A'))
# print(String.index('A',1))
# print(String.index('A',10,30))
The main difference is that Python find() produces -1 as output if it is unable to find the
substring, whereas index() throws a ValueError exception.

8. isalnum()
method checks whether all the characters in a given string are either alphabet or numeric
(alphanumeric) characters.
Syntax: string_name.isalnum()
Parameter: isalnum() method takes no parameters
Return:
 True: If all the characters are alphanumeric
 False: If one or more characters are not alphanumeric
String1="Credence"
print(String1.isalnum())-- True
String1="123ACS"
print(String1.isalnum())-- True

9. isalpha()
method is used to check whether all characters in the String is an alphabet.
# String = 'Credence_Automation_TesTiNG'
# String1="Credence"
# print(String.isalpha())
# print(String1.isalpha())

10. isdecimal()
returns true if all characters in a string are decimal, else it returns False.
Return: boolean value. True – all characters are decimal, False – one or more than one
character is not decimal.

s = "12345"
print(s.isdecimal())

# contains alphabets
s = "12credence34"
print(s.isdecimal())

# contains numbers and spaces


s = "12 34"
print(s.isdecimal())

11. isnumeric()
Python String isnumeric() method returns “True” if all characters in the string are numeric
characters, otherwise returns “False”.
s = "12345"
print(s.isnumeric())

# contains alphabets
s = "12credence34"
print(s.isnumeric())

# contains numbers and spaces


s = "12 34"
print(s.isnumeric())

12. isdigit()
returns “True” if all characters in the string are digits, Otherwise, It returns “False”.

s = "12345"
print(s.isdigit())

# contains alphabets
s = "12credence34"
print(s.isdigit())

# contains numbers and spaces


s = "12 34"
print(s.isdigit())

The differences between the these 3 methods

13. islower()
method checks if all characters in the string are lowercase.
Syntax: string.islower()
# a="yusuf"
# print(a.islower())
# a="yuSuf"
# print(a.islower())

14. istitle()
When all words in a string begin with uppercase letters and the remaining characters are
lowercase letters, the string is called title-cased. This function ignores digits and special
characters.
# First character in each word is
# uppercase and remaining lowercase
s = 'Credence For Credence'
print(s.istitle())

15. isupper()
method returns whether all characters in a string are uppercase or not.
First character in each word is
# uppercase and remaining lowercase
s = 'Credence For Credence'
print(s.isupper())

16. lower()
Python String lower() method converts all uppercase characters in a string into lowercase
characters and returns it.

# First character in first


# word is lowercase
s = 'credence For Credence'
print(s.lower())

# Third word has uppercase


# characters at middle
s = 'Credence For CREDENCE'
print(s.lower())
# Ignore the digit 6041, hence returns True
s = '6041 Is My Number'
print(s.lower())

# word has uppercase


# characters at middle
s = 'CREDENCE'
print(s.lower())

16. upper()
Python String upper() method converts all lowercase characters in a string into uppercase
characters and returns it.

# First character in each word is


# uppercase and remaining uppercase
s = 'Credence For Credence'
print(s.upper())

17. title()

title() method in Python is used to convert the first character in each word to uppercase
and the remaining characters to lowercase in the string and returns a new string.

# First character in each word is


# titlecase and remaining titlecase
s = 'Credence For Credence'
print(s.title())

# First character in first


# word is titlecase
s = 'credence For Credence'
print(s.title())

18. len()

len() function is an inbuilt function in Python. It can be used to find the length of an
object.
s = 'Credence For Credence'
print(len(s))

19.replace()

String replace() in Python returns a copy of the string where occurrences of a substring are
replaced with another substring.
Syntax: string.replace(old, new, count)
Parameters:
 count – (Optional ) the number of times you want to replace the old substring
with the new substring.

string = "grrks FOR grrks"


# replace all instances of 'r' (old) with 'e' (new)
new_string = string.replace("r", "e" )
print(string)
print(new_string)

Replace all Instances of a String using replace() in Python


Here, we will replace all the geeks with GeeksforGeeks using replace() function.
string = "geeks for geeks \ngeeks for geeks"
print(string)
# Prints the string by replacing only
# 3 occurrence of Geeks
print(string.replace("geeks", "GeeksforGeeks"))

Replace only a certain number of Instances using replace() in Python


In this example, we are replacing certain numbers of words. i.e. “ek” with “a”
with count=3.

string = "geeks for geeks geeks geeks geeks"


# Prints the string by replacing
# e by a
print(string.replace("e", "a"))
# Prints the string by replacing only
# 3 occurrence of ek by a
print(string.replace("ek", "a", 3))

20. swapcase()
method converts all uppercase characters to lowercase and vice versa of the given string
and returns it.
string = "gEEksFORgeeks"
print(string.swapcase())

21.join()
join() is an inbuilt string function in Python used to join elements of the sequence
separated by a string separator. This function joins elements of a sequence and makes it a
string.
Syntax: string_name.join(iterable)
Parameters:
 Iterable – objects capable of returning their members one at a time. Some
examples are List, Tuple, String, Dictionary, and Set
Return Value: The join() method returns a string concatenated with the elements
of iterable.

String = "Credence"
print("$".join(String))
print(",".join(String))

s1 = 'abc'
s2 = '123'

# each element of s2 is separated by s1


# '1'+ 'abc'+ '2'+ 'abc'+ '3'
print('s1.join(s2):', s1.join(s2))

# each element of s1 is separated by s2


# 'a'+ '123'+ 'b'+ '123'+ 'b'
print('s2.join(s1):', s2.join(s1))

How to check data type and address of variable?


id() Function:
Syntax :
id(object)

type() Function:
type(object) is an inbuilt function in Python.
The type() function returns the data type of the specified object
a=100
print(type (a))

Difference between identifiers Variables Data Types


Candiadtename =’Yusuf’---- candidatename is ur variable which holds the Yusuf
string. Which has string datatype.
Candiadteid =101—candidateid is also ur variable which holds the 101 number.
Which has int datatype.
But both these variables are identifies by different names so we can call it them as
identifiers.
Type Casting in Python/ Type Conversion in Python
In programming, type conversion is the process of converting data of one type to another.
For example: converting int data to str.
There are two types of type conversion in Python.
 Implicit Conversion/Type Casting - automatic type conversion
 Explicit Conversion/Type Casting - manual type conversion
Implicit Type Conversion
In this, methods, Python converts data type into another data type automatically. In
this process, users don’t have to involve in this process.
# 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))

Explicit Type Casting


In this method, Python need user involvement to convert the variable data type into
certain data type in order to the operation required.
Mainly in type casting can be done with these data type function:
 Int() : Int() function take float or string as an argument and return int type
object.
 float() : float() function take int or string as an argument and return float type
object.
 str() : str() function take float or int as an argument and return string type
object.

Let’s see some example of type casting:


Type Casting int to float:
# int variable
a=5
# typecast to float
n = float(a)
Output:
5.0
Type Casting float to int:
# int variable
a = 5.9
# typecast to int
n = int(a)
print(n)
Output:
5

Type casting int to string:


# int variable
a=5
n = str(a)
print(n)
Output:
5

Type Casting string to int:


a = "5"
n = int(a)
print(n)
Output:
5

Type Casting String to float:


a = "5.9"
n = float(a)
print(n)
Output:
5.9
Python Operators
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.
Types of Python Operators
Python language supports the following types of operators.

• Arithmetic Operators

• Comparison (Relational) Operators

• Logical Operators

• Assignment Operators

• Membership Operators

• Identity Operators

Arithmetic Operators in Python


Python Arithmetic operators are used to perform basic mathematical operations
like addition, subtraction, multiplication, and division.
Operator Name Example

+ Addition 10 + 20 = 30

- Subtraction 20 – 10 = 10

* Multiplication 10 * 20 = 200

/ Division 20 / 10 = 2

% Modulus 22 % 10 = 2

** Exponent 4**3 = 16

Python Comparison Operators


Comparison operators compare two values/variables and return a boolean
result: True or False. For example,
a=5
b =2

print (a > b) # True

Operator Meaning Example


== Is Equal To 3 == 5 gives us False

!= Not Equal To 3 != 5 gives us True

> Greater Than 3 > 5 gives us False

< Less Than 3 < 5 gives us True

>= Greater Than or Equal To 3 >= 5 give us False

<= Less Than or Equal To 3 <= 5 gives us True

Logical Operators in Python


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

Operator Description

And The condition will also be true if the expression is true. If the two
expressions a and b are the same, then a and b must both be true.

Or The condition will be true if one of the phrases is true. If a and b are the
two expressions, then an or b must be true if and is true and b is false.

Not If an expression a is true, then not (a) will be false and vice versa.

a=5
b=6

print((a > 2) and (b >= 6)) # True


print((a > 6) and (b >= 2)) # False

print((a > 2) or (b >= 6)) # True


print((a > 6) or (b >= 2)) # True
print((a > 6) and (b >= 16)) # False

print (not a) # False


x=5
print(not x < 10) # False
Python Assignment Operators
Operator Name Example

= Assignment Operator a = 10

+= Addition Assignment a += 5 (Same as a = a + 5)

-= Subtraction Assignment a -= 5 (Same as a = a - 5)

*= Multiplication Assignment a *= 5 (Same as a = a * 5)

/= Division Assignment a /= 5 (Same as a = a / 5)

%= Remainder Assignment a %= 5 (Same as a = a % 5)

**= Exponent Assignment a **= 2 (Same as a = a ** 2)

Identity Operators in Python


In Python, is and is not are the identity operators both are used to check if two values are
located on the same part of the memory. Two variables that are equal do not imply that
they are identical.
is True if the operands are identical
is not True if the operands are not identical
Let’s see an example of Identity Operators in Python .
a = 10
b = 20
c = a #(10)
print(a is not b)
print(a is c)
Output
True
True

Membership operators
In Python, in and not in are the membership operators. They are used to test whether a

value or variable is found in a sequence (string, list, tuple, set and dictionary).

2. List
A list in Python is used to store the sequence of various types of data. Python lists are
mutable type which implies that we may modify its element after it has been formed.
Although Python has six data types that may hold sequences, the list is the most popular and
dependable form.
Characteristics of Lists
The list has the following characteristics:
o The lists are ordered.
o The element of the list can access by index.
o The lists are the mutable type.
o The lists are allow to accept duplicates.
o A list can store the number of various elements.
List Declaration
# a simple list
list1 = [1, 2, "Python", "Program", 15.9]
Python List Operations
The concatenation (+) and repetition (*) operators work in the same way as they were
working with the strings. The different operations of list are
1. Repetition
2. Concatenation
3. Length
4. Membership
5. Iteration
1. Repetition
The repetition operator enables the list elements to be repeated multiple times.
list1 = [12, 14, 16, 18, 20]
l = list1 * 2
print(l)
Output:
[12, 14, 16, 18, 20, 12, 14, 16, 18, 20]

2. Concatenation
It concatenates the list mentioned on either side of the operator.
list1 = [12, 14, 16, 18, 20]
list2 = [9, 10, 32, 54, 86]
# concatenation operator +
l = list1 + list2
print(l)
Output:
[12, 14, 16, 18, 20, 9, 10, 32, 54, 86]

3. Length
It is used to get the length of the list
list1 = [12, 14, 16, 18, 20, 23, 27, 39, 40]
# finding length of the list
len(list1)
Output:
9

4. Iteration
The for loop is used to iterate over the list elements.
list1 = [12, 14, 16, 39, 40]
for i in list1:
print(i)
Output:
12
14
16
39
40

5. Membership
It returns true if a particular item exists in a particular list otherwise false.
list1 = [100, 200, 300, 400, 500]

print(600 in list1)
print(300 in list1)
print(500 in list1)
Output:
False
True
True
True

Ordered List Checking


1. a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6 ]
2. b = [ 1, 2, 5, "Ram", 3.50, "Rahul", 6 ]
3. a == b
Output:
False

1. # example
2. a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6]
3. b = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6]
4. a == b
Output:
True
Lists permanently preserve the element's order. It is the arranged gathering of things
because of this.

List Indexing and Splitting


The indexing is processed in the same way as it happens with the strings. The elements of
the list can be accessed by using the slice operator [].
The index starts from 0 and goes to length - 1. The first element of the list is stored at the
0th index, the second element of the list is stored at the 1st index, and so on.

We can get the sub-list of the list using the following syntax.
1. list_varible(start:stop:step)
o The start denotes the starting index position of the list.
o The stop denotes the last index position of the list.
o The step is used to skip the nth element within a start:stop
list = [1,2,3,4,5,6,7]
print(list[0])
print(list[1])
print(list[2])
print(list[3])

Get all the Items


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

print(my_list[:])
Run Code

Output

[1, 2, 3, 4, 5]

Get all the Items After a Specific Position


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

print(my_list[2:])
Run Code

Output

[3, 4, 5]
Note: indexing starts from 0. Item on index 2 is also included.

Get all the Items Before a Specific Position


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

print(my_list[:2])
Run Code

Output

[1, 2]

Get all the Items from One Position to Another Position


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

print(my_list[2:4])
Run Code

Output

[3, 4]

Get the Items at Specified Intervals


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

print(my_list[::2])
Run Code

Output

[1, 3, 5]

If you want the indexing to start from the last item, you can use negative sign -.
my_list = [1, 2, 3, 4, 5]

print(my_list[::-2])
Run Code

Output
[5, 3, 1]

from start to stop.


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

print(my_list[1:4:2])
Run Code

Output

[2, 4]

The items from index 1 to 4 are sliced with intervals of 2.

1. list = [1,2,3,4,5]
2. print(list[-1])
3. print(list[-3:])
4. print(list[:-1])
5. print(list[-3:-1])
Output:
5
[3, 4, 5]
[1, 2, 3, 4]
[3, 4]
As we discussed above, we can get an element by using negative indexing. In the above
code, the first print statement returned the rightmost element of the list. The second print
statement returned the sub-list, and so on.

Indexing
1. Positive Indexes

2. Negative Indexes
Now, let us look at the below diagram which illustrates a list along with its negative
indexes.

Lst = [50, 70, 30, 20, 90, 10, 50]


# Display list
print(Lst[-7::1])

Slicing
As mentioned earlier list slicing is a common practice in Python and can be used both with
positive indexes as well as negative indexes. The below diagram illustrates the technique
of list slicing:

 Python3

# Initialize list
Lst = [50, 70, 30, 20, 90, 10, 50]
# Display list
print(Lst[1:5])

Output:
[70, 30, 20, 90]
Below are some examples which depict the use of list slicing in Python:
Example 1:

 Python3

# Initialize list
List = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Show original list
print("\nOriginal List:\n", List)

# Display sliced list


print(List[3:9:2])

# Display sliced list


print(List[::2])

# Display sliced list


print(List[::])

Output:
Original List:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Sliced Lists:
[4, 6, 8]
[1, 3, 5, 7, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Leaving any argument like Initial, End or IndexJump blank will lead to the use of default
values i.e 0 as Initial, length of list as End and 1 as IndexJump.
Example 2:

 Python3

# Initialize list
List = ['Geeks', 4, 'geeks !']

# Show original list


print("\nOriginal List:\n", List)

print("\nSliced Lists: ")

# Display sliced list


print(List[::-1])

# Display sliced list


print(List[::-3])

# Display sliced list


print(List[:1:-2])

Output:
Original List:
['Geeks', 4, 'geeks !']

Sliced Lists:
['geeks !', 4, 'Geeks']
['geeks !']
['geeks !']

Example 3:

 Python3

# Initialize list
List = [-999, 'G4G', 1706256, '^_^', 3.1496]

# Show original list


print("\nOriginal List:\n", List)

# Display sliced list


print(List[10::2])

# Display sliced list


print(List[1:1:1])

Output:
Original List:
[-999, 'G4G', 1706256, '^_^', 3.1496]

Sliced Lists:
[]
[]
If some slicing expressions are made that do not make sense or are incomputable then
empty lists are generated.

Example 4:

 Python3

# Initialize list
List = [-999, 'G4G', 1706256, 3.1496, '^_^']

# Show original list


print("\nOriginal List:\n", List)
# Modified List
List[2:4] = ['Geeks', 'for', 'Geeks', '!']

# Display sliced list


print(List)

# Modified List
List[:6] = []
print(List)

Output:
Original List:
[-999, 'G4G', 1706256, 3.1496, '^_^']

Sliced Lists:
[-999, 'G4G', 'Geeks', 'for', 'Geeks', '!', '^_^']
['^_^']
List slicing can be used to modify lists or even delete elements from a list.

Updating List Values


Lists are the most versatile data structures in Python since they are mutable, and their
values can be updated by using the slice and assignment operator. Python also provides
append() and insert() methods, which can be used to add values to the list.
1. # updating list values
2. list = [1, 2, 3, 4, 5, 6]
3. print(list)
4. # It will assign value to the value to the second index
5. list[2] = 10
6. print(list)
7. # Adding multiple-element
8. list[1:3] = [89, 78]
9. print(list)
10. # It will add value at the end of the list
11. list[-1] = 25
12. print(list)
Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]

To change the value of a specific item, refer to the index number:


Change the second item
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)

To change the value of items within a specific range, define a list with the new values, and
refer to the range of index numbers where you want to insert the new values:
Change the values "banana" and "cherry" with the values "blackcurrant" and "watermelon":
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)

If you insert more items than you replace, the new items will be inserted where you
specified, and the remaining items will move accordingly:

Change the second value by replacing it with two new values:


thislist = ["apple", "banana", "cherry"]
thislist[1:2] = ["blackcurrant", "watermelon"]
print(thislist) #['apple', 'blackcurrant', 'watermelon', 'cherry']

If you insert less items than you replace, the new items will be inserted where you specified,
and the remaining items will move accordingly:
Example
Change the second and third value by replacing it with one value:
thislist = ["apple", "banana", "cherry"]
thislist[1:3] = ["watermelon"]
print(thislist) #['apple', 'watermelon']
List methods in Python

1. append()
adding elements to the end of the List.
Syntax: list.append(item)

Example 1: Adding Element to a List


animals = ['cat', 'dog', 'rabbit']
animals.append('Tiger’)
print('Updated animals list: ', animals)

Output

Updated animals list: ['cat', 'dog', 'rabbit', 'guinea pig']

Example 2: Adding List to a List


animals = ['cat', 'dog', 'rabbit']
wild_animals = ['tiger', 'fox']
animals.append(wild_animals)
print('Updated animals list: ', animals)

Output

Updated animals list: ['cat', 'dog', 'rabbit', ['tiger', 'fox']]

2. clear()
The clear() method removes all the elements from a list.
Syntax
list.clear()
fruits = ['apple', 'banana', 'cherry', 'orange']
fruits.clear()
list = [{1, 2}, ('a'), ['1.1', '2.2']]
list.clear()
print('List:', list)

Output

List: []

Example 2: Emptying the List Using del


list = [{1, 2}, ('a'), ['1.1', '2.2']]
del list[:]
print('List:', list)
Run Code

Output
List: []

3. copy()
Definition and Usage
The copy() method returns a copy of the specified list.
Syntax
list.copy()

Example: Copying a List


my_list = ['cat', 0, 6.7]
new_list = my_list.copy()
print('Copied List:', new_list)

Output

Copied List: ['cat', 0, 6.7]

If you modify the new_list in the above example, my_list will not be modified.

List copy using =


We can also use the = operator to copy a list. For example,

old_list = [1, 2, 3]
new_list = old_list

If you modify new_list, old_list is also modified. It is because the new list is referencing or

pointing to the same old_list object.


old_list = [1, 2, 3]

new_list = old_list
new_list.append('a')
print('New List:', new_list)
print('Old List:', old_list)

Output

Old List: [1, 2, 3, 'a']


New List: [1, 2, 3, 'a']

However, if you need the original list unchanged when the new list is modified, you can
use the copy() method.
Example: Copy List Using Slicing Syntax
list = ['cat', 0, 6.7]
new_list = list[:]
new_list.append('dog')
print('Old List:', list)
print('New List:', new_list)

Output

Old List: ['cat', 0, 6.7]


New List: ['cat', 0, 6.7, 'dog']

4.count()
Definition and Usage
The count() method returns the number of elements with the specified value.
Syntax
list.count(value)
Example 1
numbers = [2, 3, 5, 2, 11, 2, 7]
count = numbers.count(2)
print('Count of 2:', count)

# Output: Count of 2: 3

Example 2: Use of count()


vowels = ['a', 'e', 'i', 'o', 'i', 'u']
count = vowels.count('i')
print('The count of i is:', count)
# count element 'p'
count = vowels.count('p')
print('The count of p is:', count)

Output

The count of i is: 2


The count of p is: 0

5. extend()
The extend() method adds all the elements of an iterable (list, tuple, string etc.) to the end
of the list.
Example
# create a list
odd_numbers = [1, 3, 5]
# create another list
numbers = [1, 4]
# add all elements of prime_numbers to numbers
numbers.extend(odd_numbers)
print('List after extend():', numbers)
# Output: List after extend(): [1, 4, 1, 3, 5]
Run Code

Python extend() Vs append()


If you need to add an element to the end of a list, you can use the append() method.
a1 = [1, 2]
a2 = [1, 2]
b = (3, 4)
# a1 = [1, 2, 3, 4]
a1.extend(b)
print(a1)
# a2 = [1, 2, (3, 4)]
a2.append(b)
print(a2)
Run Code

Output

[1, 2, 3, 4]
[1, 2, (3, 4)]

6.index()
The index() method returns the index of the specified element in the list.
Example
animals = ['cat', 'dog', 'rabbit', 'horse']

# get the index of 'dog'


index = animals.index('dog')
print(index)
# Output: 1
Run Code

Syntax of List index()


The syntax of the list index() method is:
list.index(element, start, end)

 If the element is not found, a ValueError exception is raised.

Note: The index() method only returns the first occurrence of the matching element

Example 2: Index of the Element not Present in the List


# vowels list
vowels = ['a', 'e', 'i', 'o', 'u']
# index of 'p' is vowels
index = vowels.index('p')
print('The index of p:', index)
Run Code

Output

ValueError: 'p' is not in list

Example 3: Working of index() With Start and End Parameters


# alphabets list
alphabets = ['a', 'e', 'i', 'o', 'g', 'l', 'i', 'u']
# index of 'i' in alphabets
index = alphabets.index('e') # 1
print('The index of e:', index)
# 'i' after the 4th index is searched
index = alphabets.index('i', 4) # 6
print('The index of i:', index)
# 'i' between 3rd and 5th index is searched
index = alphabets.index('i', 3, 5) # Error!
print('The index of i:', index)
Run Code

Output

The index of e: 1
The index of i: 6
Traceback (most recent call last):
File "*lt;string>", line 13, in
ValueError: 'i' is not in list

7.insert()

Definition and Usage


The insert() method inserts the specified value at the specified position.
Syntax
list.insert(pos, elmnt)
Parameter Values

Example
fruits = ['apple', 'banana', 'cherry']

fruits.insert(1, "orange")
Example
vowel = ['a', 'e', 'i', 'u']
# 'o' is inserted at index 3 (4th position)
vowel.insert(3, 'o')
print('List:', vowel)
# Output: List: ['a', 'e', 'i', 'o', 'u']

Example 1: Inserting an Element to the List


# create a list of prime numbers
prime_numbers = [2, 3, 5, 7]
# insert 11 at index 4
prime_numbers.insert(4, 11)
print('List:', prime_numbers)
Run Code

Output

List: [2, 3, 5, 7, 11]

Example 2: Inserting a Tuple (as an Element) to the List


mixed_list = [{1, 2}, [5, 6, 7]]
# number tuple
number_tuple = (3, 4)
# inserting a tuple to the list
mixed_list.insert(1, number_tuple)
print('Updated List:', mixed_list)
Run Code

Output

Updated List: [{1, 2}, (3, 4), [5, 6, 7]]

8.pop()
The pop() method removes the item at the given index from the list and returns the
removed item.
Example
prime_numbers = [2, 3, 5, 7]
# remove the element at index 2
removed_element = prime_numbers.pop(2)
print('Removed Element:', removed_element)
print('Updated List:', prime_numbers)
# Output:
# Removed Element: 5
# Updated List: [2, 3, 7]

Syntax of List pop()

list.pop(index)

pop() parameters
 The pop() method takes a single argument (index).

 The argument passed to the method is optional. If not passed, the default index -1 is

passed as an argument (index of the last item).

 If the index passed to the method is not in range, it throws IndexError: pop index

out of range exception.

Return Value from pop()


The pop() method returns the item present at the given index. This item is also removed

from the list.

Example 1: Pop item at the given index from the list


# programming languages list
languages = ['Python', 'Java', 'C++', 'French', 'C']
# remove and return the 4th item
return_value = languages.pop(3)
print('Return Value:', return_value)
# Updated List
print('Updated List:', languages)
Run Code

Output

Return Value: French


Updated List: ['Python', 'Java', 'C++', 'C']

Note: Index in Python starts from 0, not 1.

If you need to pop the 4th element, you need to pass 3 to the pop() method.
Example 2: pop() without an index, and for negative indices
# programming languages list
languages = ['Python', 'Java', 'C++', 'Ruby', 'C']
# remove and return the last item
print('When index is not passed:')
print('Return Value:', languages.pop())
print('Updated List:', languages)
# remove and return the last item
print('\nWhen -1 is passed:')
print('Return Value:', languages.pop(-1))
print('Updated List:', languages)
# remove and return the third last item
print('\nWhen -3 is passed:')
print('Return Value:', languages.pop(-3))
print('Updated List:', languages)
Run Code

Output

When index is not passed:


Return Value: C
Updated List: ['Python', 'Java', 'C++', 'Ruby']
When -1 is passed:
Return Value: Ruby
Updated List: ['Python', 'Java', 'C++']
When -3 is passed:
Return Value: Python
Updated List: ['Java', 'C++']

9.remove()
The remove() method removes the first matching element (which is passed as an argument)
from the list.
Example
# create a list
prime_numbers = [2, 3, 5, 7, 9, 11]
# remove 9 from the list
prime_numbers.remove(9)
# Updated prime_numbers List
print('Updated List: ', prime_numbers)
# Output: Updated List: [2, 3, 5, 7, 11]
Syntax of List remove()
The syntax of the remove() method is:

list.remove(element)

Example 1: Remove element from the list


# animals list
animals = ['cat', 'dog', 'rabbit', 'guinea pig']
animals.remove('rabbit')
print('Updated animals list: ', animals)
Run Code

Output

Updated animals list: ['cat', 'dog', 'guinea pig']

Example 2: remove() method on a list having duplicate elements

method only removes the first matching element.


# animals list
animals = ['cat', 'dog', 'dog', 'guinea pig', 'dog']
animals.remove('dog')
print('Updated animals list: ', animals)

Output

Updated animals list: ['cat', 'dog', 'guinea pig', 'dog']

10. reverse()

The reverse() method reverses the elements of the list.


Example
prime_numbers = [2, 3, 5, 7]
prime_numbers.reverse()
print('Reversed List:', prime_numbers)
Output: Reversed List: [7, 5, 3, 2]

Example 2: Reverse a List Using Slicing Operator


systems = ['Windows', 'macOS', 'Linux']
print('Original List:', systems)
reversed_list = systems[::-1]
print('Updated List:', reversed_list)

11.sort()
The sort() method sorts the items of a list in ascending or descending order.
Example
prime_numbers = [11, 3, 7, 5, 2]
prime_numbers.sort()
print(prime_numbers)
# Output: [2, 3, 5, 7, 11]

Example 1: Sort a given list


vowels = ['e', 'a', 'u', 'o', 'i']
vowels.sort()
print('Sorted list:', vowels)

Output

Sorted list: ['a', 'e', 'i', 'o', 'u']

Example 2: Sort the list in Descending order


vowels = ['e', 'a', 'u', 'o', 'i']
vowels.sort(reverse=True)
print('Sorted list (in Descending):', vowels)

Output

Sorted list (in Descending): ['u', 'o', 'i', 'e', 'a']

3. Tuple
A tuple is an ordered collection of values.
Tuples are a lot like lists:
 Tuples are ordered – Tuples maintains a left-to-right positional ordering among the
items they contain.
 Accessed by index – Items in a tuple can be accessed using an index.
 Tuples can contain any sort of object – It can be numbers, strings, lists and even
other tuples.
 Allow Duplicates
except:
 – you can’t add, delete, or change items after the tuple is defined.Creating a Tuple
# Empty tuple
my_tuple = ()
print(my_tuple)
# Tuple having integers
my_tuple = (1, 2, 3)
print(my_tuple)
# tuple with mixed datatypes
my_tuple = (1, "Hello", 3.4)
print(my_tuple)
# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)

Output

()
(1, 2, 3)
(1, 'Hello', 3.4)
('mouse', [8, 4, 6], (1, 2, 3))

As mentioned earlier, we can also create tuples without using parentheses: But we mostly

use ().

my_tuple = 1, 2, 3
my_tuple = 1, "Hello", 3.4

Tuple Concatenation,Repetition,Membership,Iteration and Length


# Concatenate
T = ('red', 'green', 'blue') + (1, 2, 3)
print(T)
# Prints ('red', 'green', 'blue', 1, 2, 3)

# Replicate(Repeatation / Multiplication)

T = ('red', 'Green') * 3
print(T)
# Prints ('red', 'Green', 'red', 'Green', 'red', 'Green')

#Membership
T = ('red', 'green', 'blue')
print("red" in T)
#Iteration
for i in tup1:
print(i)

#Length
tuple1 = (12, 14, 16, 18, 20, 23, 27, 39, 40)

print(len(tuple1))

Change Tuple Items


Tuples are immutable (unchangeable). Once a tuple is created, it cannot be modified.
tuple1 = (0, 1, 2, 3)
tuple1[0] = 4
print(tuple1)

Output:
Traceback (most recent call last):
File "e0eaddff843a8695575daec34506f126.py", line 3, in
tuple1[0]=4
TypeError: 'tuple' object does not support item assignment

Accessing Values in Tuples


You can access individual items in a tuple using an index in square brackets. Note that tuple
indexing starts from 0.
The indices for the elements in a tuple are illustrated as below:
T = ('red', 'green', 'blue', 'yellow', 'black')
print(T[0])
# Prints red
print(T[2])
# Prints blue

Tuple Slicing
To access a range of items in a tuple, you need to slice a tuple using a slicing operator. Tuple
slicing is similar to list slicing.
T = ('a', 'b', 'c', 'd', 'e', 'f')

print(T[2:5])
# Prints ('c', 'd', 'e')

Delete a Tuple
Tuples cannot be modified, so obviously you cannot delete any item from it. However, you
can delete the tuple completely with del keyword.
T = ('red', 'green', 'blue')
del T
***Tuple Packing & Unpacking
Tuple Packing
When a tuple is created, the items in the tuple are packed together into the object.
T = ('red', 'green', 'blue', 'cyan')
print(T)
# Prints ('red', 'green', 'blue', 'cyan')
In above example, the values ‘red’, ‘green’, ‘blue’ and ‘cyan’ are packed together in a tuple.

Tuple Unpacking
When a packed tuple is assigned to a new tuple, the individual items are unpacked (assigned
to the items of a new tuple).
T = ('red', 'green', 'blue', 'cyan')
(a, b, c, d) = T
print(a)
# Prints red
print(b)
# Prints green

# T = ('red', 'green', 'blue', 'cyan') #Packing


# (a, b, c) = T # Unpacking
# print(a) # ValueError: too many values to unpack (expected 3)

# T = ('red', 'green', 'blue') #Packing


# (a, b, c, d) = T # Unpacking
# print(a) # not enough values to unpack (expected 4, got 3)

Python Tuple Methods


Following are the tuple methods that we can use while working with a tuple in python.
 count(): Returns the count of the items.
 index(): It returns the index of the item specified.
 tuple()-Use tuple() to converts a data type to tuple. For example, in the code chunk
below, you convert a Python list to a tuple.

a = (1,2,1,3,1,3,1,2,1,4,1,5,1,5)
print(a.count(1))
print(a.index(5))
abc=("Yusuf","Amit","Pooja","raj", "Pritesh","Priya","Yusuf")
print(abc.count("Yusuf"))
print(abc.index("Yusuf"))
print(abc.index("Yusuf",1,7))
print(abc.index("Yusuf",-7,-1))
print(abc.index("Yusuf",-1,-7))

a_list = [1,2,3,4,5]
b_tuple = tuple(a_list)
print(type(b_tuple))

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


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

>>> max(tup)

890

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

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

>>> sum(tup)

1023

tup2 = ("Yusuf","yusuf")

print(max(tup2))
print(min(tup2))

sorted()

To return a tuple with the elements in an sorted order, use sorted(), just like in the following
example:
tuple_ = (5, 2, 24, 3, 1, 6, 7)
sorted_ = tuple(sorted(tuple_))
print('Sorted Tuple :', sorted_)
print(type(sorted_))
Output:
Sorted Tuple : (1, 2, 3, 5, 6, 7, 24)
<class 'tuple'>

tuple_ = (5, 2, 24, 3, 1, 6, 7)


sorted_ = tuple(sorted(tuple_, reverse=True))
print('Sorted Tuple :', sorted_)
print(type(sorted_))
Output:
Sorted Tuple : (24, 7, 6, 5, 3, 2, 1)
<class 'tuple'>
len()

With the len() function, you can returns the length of the tuple:
a = (1,2,3,4,5)
print(len(a))

Change Tuple Values with converting it into list


Once a tuple is created, you cannot change its values. Tuples are unchangeable,
or immutable as it also is called.
But there is a workaround. You can convert the tuple into a list, change the list, and convert
the list back into a tuple.
Example
Convert the tuple into a list to be able to change it:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)

prin

Python Set
Unlike other collections in Python, there is no index attached to the elements of the set, i.e.,
we cannot directly access any element of the set by the index. However, we can print them
all together, or we can get the list of elements by looping through the set.
x = {1,2.3, "py", (1,2,3)}
print(x)

Creating a set
Syntax:
variable = set(iterable element)

By Curly {} brackets:
Syntax:
variable = {element1, element2,..}

Example 2: Using set() method (Constructor)


Days = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sund
ay"])
print(Days)

Properties of Set Data Type:


Set follow three properties:
1. Unordered
2. Unique
3. mutable
Traversal the set or Iterate Over a Set in Python
Syntax:
for element in set:
print(element)
Program:
x={'p','h','t','n','o'}
for y in x:

Add and Update Set Items in Python

Sets are mutable. However, since they are unordered, indexing has no meaning.

Add Items to a Set in Python


In Python, we use the add() method to add an item to a set. For example,
numbers = {21, 34, 54, 12}
print('Initial Set:',numbers)
# using add() method
numbers.add(32)
print('Updated Set:', numbers)
Run Code

Output

Initial Set: {34, 12, 21, 54}


Updated Set: {32, 34, 12, 21, 54}

Update Python Set

Update() method is used to add multiple elements into the set.


companies = {'Lacoste', 'Ralph Lauren'}
tech_companies = ['apple', 'google', 'apple']
companies.update(tech_companies)
print(companies)
# Output: {'google', 'apple', 'Lacoste', 'Ralph Lauren'}
Here, all the unique elements of tech_companies are added to the companies set.

Deletion from the set


Deletion operation on the set can be performed by these four methods:
1. remove
2. discard
3. pop
4. clear
Remove
Remove method removes an element from the set which is passed in the method from the
set. If the element is not present in the set then it raises an error message.
Syntax:
set.remove(element)
Discard
Discard method removes an element from the set which is passed in the method from the
set. If the element is not present in the set then it gives no error message.
Syntax:
set.discard(element)

pop()
The pop() method randomly removes an item from a set and returns the removed item.
Syntax:
variable = set.pop()

clear()
clear() method removes all the elements of the set (set becomes null).
Syntax:
set.clear()

languages = {'Python', 'Java', 'English'}


# remove English from the set
languages.remove('English')
print(languages)
# Output: {'Python', 'Java'}

numbers = {2, 3, 4, 5}
# discards 3 from the set
numbers.discard(3)
print('Set after discard:', numbers)
Run Code

A = {'a', 'b', 'c', 'd'}


removed_item = A.pop()
print(removed_item)
# Output: c
# set of prime numbers
primeNumbers = {2, 3, 5, 7}
# clear all elements
primeNumbers.clear()
print(primeNumbers)
# set()

Python Set Operations


Python Set provides different built-in methods to perform mathematical set operations like

union, intersection, subtraction, and symmetric difference.


Union of Two Sets

The union of two sets A and B include all the elements of set A and B and not include

duplicates.

Set Union in Python

We use the | operator or the union() method to perform the set union operation. For

example,
A = {1, 3, 5,2}
B = {0, 2, 4,1}
print('Union using |:', A | B)
print('Union using union():', A.union(B))

Output

Union using |: {0, 1, 2, 3, 4, 5}


Union using union(): {0, 1, 2, 3, 4, 5}

Note: A|B and union() is equivalent to A ⋃ B set operation.

Set Intersection
The intersection of two sets A and B include the common elements between set A and B.
A = {1, 3, 5}
B = {1, 2, 3}
print('Intersection using &:', A & B)
print('Intersection using intersection():', A.intersection(B))

Output

Intersection using &: {1, 3}


Intersection using intersection(): {1, 3}

Note: A&B and intersection() is equivalent to A ⋂ B set operation.

Difference between Two Sets


The difference between two sets A and B include elements of set i that are not present on
set B.

Set Difference in Python

We use the - operator or the difference() method to perform the difference between two

sets. For example,


A = {2, 3, 5}
B = {1, 2, 6}
print('Difference using &:', A - B)
print('Difference using difference():', A.difference(B))

Output

Difference using &: {3, 5}


Difference using difference(): {3, 5}

Note: A - B and A.difference(B) is equivalent to A - B set operation.


Set Symmetric Difference

The symmetric difference between two sets A and B includes all elements

of A and B without the common elements.

Set Symmetric Difference in Python

In Python, we use the ^ operator or the symmetric_difference() method to perform

symmetric difference between two sets. For example,


A = {2, 3, 5}
B = {1, 2, 6}
print('using ^:', A ^ B)
print('using symmetric_difference():', A.symmetric_difference(B))

Output

using ^: {1, 3, 5, 6}
using symmetric_difference(): {1, 3, 5, 6}

issubset
Issubset checks if the first set is a subset of another set.
Syntax:
bool variable=set1.issubset(set2)
isdisjoint
Isdisjoint checks if there is no common element between two sets.
Syntax:
bool variable=set1.isdisjoint(set2)
# Initialization of set x and y
x={1,2}
y={1,2,3,4}

# check if set x is subsite of y


z=x.issubset(y)
print('Check if x is subset of y: ', z)

# Initialization set x and y


x={1,2}
y={3,4}

# Check if set x and y are disjoint


Z=x.isdisjoint(y)
print('Check if set x and y are disjoint:',z)

Operator with set:


There are many operators which can be used with sets . Some of them are as follow:
== Checks if two sets are equal or have the same elements.
!= Checks if two sets are not equal or have different elements.
<= Checks if the first set is a subset of another set.
< Checks if the first set is a proper subset of another set.
>= Checks if the first set is a superset of another set.
> Checks if the first set is a proper superset of another set.
& This operator takes the intersection of two sets.
| This operator takes the union of two sets.
- This operator takes the difference of two sets.
^ This operator takes the Symmetric Difference of two sets.
Program
# Initialization of set x and y
x = {'a','b','c'}
y = {'a','b','c'}
print('Set x: ', x)
print('Set y: ', y)
# Operator with set
print('Set x == y: ', x==y)
print('Set x != y: ', x != y)
# Initialization of set x and y
x = {1,2}
y = {1,2,3,4}
print('Set x: ', x)
print('Set y: ', y)
print('Set x <= y: ', x <= y)
print('Set x < y: ', x < y)
# Initialization of set x and y
x = {1,2,3,4}
y = {1,2,3}
print('Set x superset y:', x >= y)
print('Set x proper superset y:', x > y)
print('Intersection x & y:', x & y)
print('Union of x & y:', x | y)
print('Difference of x & y:', x - y)
print('Symmetric Difference of x & y:', x ^ y)
Output:
Some Build in Methods:
There is some built in function in the set:
Copy () To shallow copy a set to another set.
in Check if an element is in the set.
not in Check if an element is not in the set.
len () Find the number of elements in the set.
max () Find the max element in the set.
min () Find the minimum element in the set.
sorted () Sort the elements of the set.
sum () Find the sum of elements of the set.
all () Check if all the iterable elements of the set are true.
any () Check if any of the iterable elements of the set is true.
Program:
# Initialization of set x
x={20,1,2,3,4,10}
# copy set x to set z
z=x.copy()
print('Copy set x to set z: ', z)
print('Print length of set z: ',len(z) )
print('Print min of set z: ',min(z))
print('Print max of set z: ',max(z))
print('Print Sum of set z: ',sum(z))
# Sort set z
print(sorted(z))
print(sorted(z, reverse=True))
print(all(x))
print(any(x))
print(5 in x)
print(5 not in x)

Python frozenset()
Frozen set is just an immutable version of a Python set object. While elements of a set can

be modified at any time, elements of the frozen set remain the same after creation.
Due to this, frozen sets can be used as keys in Dictionary or as elements of another set. But

like sets, it is not ordered (the elements can be set at any index).
The syntax of frozenset() function is:

frozenset([iterable])

Example 1: Working of Python frozenset()


# tuple of vowels
vowels = ('a', 'e', 'i', 'o', 'u')
fSet = frozenset(vowels)
print('The frozen set is:', fSet)
print('The empty frozen set is:', frozenset())
# frozensets are immutable
fSet.add('v')
Run Code

Output

The frozen set is: frozenset({'a', 'o', 'u', 'i', 'e'})


The empty frozen set is: frozenset()
Traceback (most recent call last):
File "<string>, line 8, in <module>
fSet.add('v')
AttributeError: 'frozenset' object has no attribute 'add'

Frozenset operations

Like normal sets, frozenset can also perform different operations


like copy, difference, intersection, symmetric_difference, and union.
# Frozensets
# initialize A and B
A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])
# copying a frozenset
C = A.copy() # Output: frozenset({1, 2, 3, 4})
print(C)
# union
print(A.union(B)) # Output: frozenset({1, 2, 3, 4, 5, 6})
# intersection
print(A.intersection(B)) # Output: frozenset({3, 4})
# difference
print(A.difference(B)) # Output: frozenset({1, 2})
# symmetric_difference
print(A.symmetric_difference(B)) # Output: frozenset({1, 2, 5, 6})
Run Code

Output

frozenset({1, 2, 3, 4})
frozenset({1, 2, 3, 4, 5, 6})
frozenset({3, 4})
frozenset({1, 2})
frozenset({1, 2, 5, 6})

Similarly, other set methods like isdisjoint, issubset, and issuperset are also available.
# Frozensets
# initialize A, B and C
A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])
C = frozenset([5, 6])
# isdisjoint() method
print(A.isdisjoint(C)) # Output: True
# issubset() method
print(C.issubset(B)) # Output: True
# issuperset() method
print(B.issuperset(C)) # Output: True
Run Code

Output

True
True
True

Boolean Data Type


Python boolean Generally, it is used to represent the truth values of the expressions. For
example, 1==1 is True whereas 2<1 is False.
The boolean value can be of two types only i.e. either True or False.
a = True ,print(type(a)) ,b = False ,print(type(b)

Python Dictionary Data Type


Dictionary holds pair of values, one being the Key and the other corresponding pair
element being its Key:value. Values in a dictionary can be of any data type and can be
duplicated, whereas keys can’t be repeated and must be immutable.
Note – Dictionary keys are case sensitive, the same name but different cases of Key will be
treated distinctly.
An effective data structure for storing data in Python is dictionaries, in which can simulate
the real-life data arrangement where some specific value exists for some particular key.
o Python Dictionary is used to store the data in a key-value pair format.
o It is the mutable data-structure.
o Key is immutable value is mutable
o Keys must consist of just one element.
o Value can be any type such as list, tuple, integer, etc.

Create a Dictionary
# Create a dictionary to store employee record
D = {'name': 'Bob',
'age': 25,
'job': 'Dev',
'city': 'New York',
'email': 'bob@web.com'}

The dict() Constructor


# Create a dictionary with a list of two-item tuples
L = [('name', 'Bob'),
('age', 25),
('job', 'Dev')]
D = dict(L)
print(D)
# Prints {'name': 'Bob', 'age': 25, 'job': 'Dev'}

# Create a dictionary with a tuple of two-item lists


T = (['name', 'Bob'],
['age', 25],
['job', 'Dev'])
D = dict(T)
print(D)
# Prints {'name': 'Bob', 'age': 25, 'job': 'Dev'}
When the keys are simple strings, it is sometimes easier to specify key:value pairs
using keyword arguments.
D = dict(name = 'Bob',
age = 25,
job = 'Dev')
print(D)
# Prints {'name': 'Bob', 'age': 25, 'job': 'Dev'}
Other Ways to Create Dictionaries
# Create a dictionary with list of zipped keys/values
keys = ['name', 'age', 'job']
values = ['Bob', 25, 'Dev']
D = dict(zip(keys, values))
print(D)
# Prints {'name': 'Bob', 'age': 25, 'job': 'Dev'}

You’ll often want to create a dictionary with default values for each key.
The fromkeys() method offers a way to do this.
# Initialize dictionary with default value '0' for each key
keys = ['a', 'b', 'c']
defaultValue = 0

D = dict.fromkeys(keys,defaultValue)
print(D)
# Prints {'a': 0, 'b': 0, 'c': 0}

Important Properties of a Dictionary


Keys must be unique:
Key must be immutable type:
Value can be of any type:

Access Dictionary Items


You can fetch a value from a dictionary by referring to its key in square brackets [].
D = {'name': 'Bob',
'age': 25,
'job': 'Dev'}
print(D['name'])
# Prints Bob

If you refer to a key that is not in the dictionary, you’ll get an exception.
print(D['salary'])
print(D['salary'])
# Triggers KeyError: 'salary'
To avoid such exception, you can use the special dictionary get() method.
print(D.get('name'))

#Accessing an element of a nested dictionary


# Creating a Dictionary
Dict = {'Dict1': {1: 'Geeks'}, 'Dict2': {'Name': 'For'}}
# Accessing element using key
print(Dict['Dict1'])
print(Dict['Dict1'][1])
print(Dict['Dict2']['Name'])

Add or Update Dictionary Items


D = {'name': 'Bob','age': 25, 'job': 'Dev'}
D['name'] = 'Sam'
print(D)
# Prints {'name': 'Sam', 'age': 25, 'job': 'Dev'}
If the key is new, it is added to the dictionary with its value.
D = {'name': 'Bob','age': 25,'job': 'Dev'}
D['city'] = 'New York'
print(D)
# Prints {'name': 'Bob', 'age': 25, 'job': 'Dev', 'city': 'New York'}

Merge Two Dictionaries


Use the built-in update() method to merge the keys and values of one dictionary into
another. Note that this method blindly overwrites values of the same key if there’s a clash.
D1 = {'name': 'Bob','age': 25,'job': 'Dev'}
D2 = {'age': 30,'city': 'New York','email': 'bob@web.com'}

D1.update(D2)
print(D1)
# Prints {'name': 'Bob', 'age': 30, 'job': 'Dev',
# 'city': 'New York', 'email': 'bob@web.com'}

Remove Dictionary Items


There are several ways to remove items from a dictionary.
Remove an Item by Key
If you know the key of the item you want, you can use pop() method. It removes the key and
returns its value.
D = {'name': 'Bob', 'age': 25, 'job': 'Dev'}
x = D.pop('age')
print(D)
# Prints {'name': 'Bob', 'job': 'Dev'}

# get removed value


print(x)
# Prints 25
If you don’t need the removed value, use the del statement.
D = {'name': 'Bob','age': 25,'job': 'Dev'}
del D['age']
print(D)
# Prints {'name': 'Bob', 'job': 'Dev'}

Remove Last Inserted Item


The popitem() method removes and returns the last inserted item.
D = {'name': 'Bob','age': 25,'job': 'Dev'}
x = D.popitem()
print(D)
# Prints {'name': 'Bob', 'age': 25}
# get removed pair
print(x)
# Prints ('job', 'Dev')

Remove all Items


To delete all keys and values from a dictionary, use clear() method.
D = {'name': 'Bob','age': 25,'job': 'Dev'}
D.clear()
print(D)
# Prints {}

Get All Keys, Values and Key:Value Pairs


D = {'name': 'Bob',
'age': 25,
'job': 'Dev'}

# get all keys


print(list(D.keys()))
# Prints ['name', 'age', 'job']
# get all values
print(list(D.values()))
# Prints ['Bob', 25, 'Dev']
# get all pairs
print(list(D.items()))
# Prints [('name', 'Bob'), ('age', 25), ('job', 'Dev')]

Iterate Through a Dictionary


If you use a dictionary in a for loop, it traverses the keys of the dictionary by default.
D = {'name': 'Bob',
'age': 25,
'job': 'Dev'}
for x in D:
print(x)
# Prints name age job
To iterate over the values of a dictionary, index from key to value inside the for loop.
D = {'name': 'Bob',
'age': 25,
'job': 'Dev'}

for x in D:
print(D[x])
# Prints Bob 25 Dev

Check if a Key or Value Exists


If you want to know whether a key exists in a dictionary, use in and not in operators with if
statement.
D = {'name': 'Bob',
'age': 25,
'job': 'Dev'}

print('name' in D)
# Prints True
print('salary' in D)
# Prints False
To check if a certain value exists in a dictionary, you can use method values(), which returns
the values as a list, and then use the in operator.
D = {'name': 'Bob',
'age': 25,
'job': 'Dev'}

print('Bob' in D.values())
# Prints True
print('Sam' in D.values())
# Prints False

Find Dictionary Length


To find how many key:value pairs a dictionary has, use len() method.
D = {'name': 'Bob',
'age': 25,
'job': 'Dev'}

print(len(D))
# Prints 3
Python Dictionary Methods
Method Description

clear() Removes all items from the dictionary

copy() Returns a shallow copy of the dictionary

fromkeys() Creates a new dictionary with the specified keys and values

get() Returns the value of the specified key

items() Returns a list of key:value pair

keys() Returns a list of all keys from dictionary

pop() Removes and returns single dictionary item with specified key.

popitem() Removes and returns last inserted key:value pair from the dictionary.

setdefault() Returns the value of the specified key, if present. Else, inserts the key with a specified va

update() Updates the dictionary with the specified key:value pairs

values() Returns a list of all values from dictionary

# demo for all dictionary methods


dict1 = {1: "Python", 2: "Java", 3: "Ruby", 4: "Scala"}

# copy() method
dict2 = dict1.copy()
print(dict2)

# clear() method
dict1.clear()
print(dict1)

# get() method
print(dict2.get(1))

# items() method
print(dict2.items())

# keys() method
print(dict2.keys())

# pop() method
dict2.pop(4)
print(dict2)
# popitem() method
dict2.popitem()
print(dict2)

# update() method
dict2.update({3: "C++"})
print(dict2)

# values() method
print(dict2.values())

Built-in Dictionary Functions

Method Description

all() Returns True if all list items are true

any() Returns True if any list item is true

len() Returns the number of items in the list

sorted() Returns a sorted list

o len()
Code
1. dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}
2. len(dict)
Output
4

o any()
The any() method returns True indeed if one dictionary key does have a Boolean expression
of True, much like it does for lists and tuples.
Code
dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}
print(any({'':'','':'',3:''}))
Output
True

o all()
Unlike in any() method, all() only returns True if each of the dictionary's keys contain a True
Boolean value.
Code
1. dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}
2. print(all({1:'',2:'','':''}))
print(all({1:'',2:'',3:'',4:''}))
Output
False
True

o sorted()
The sorted() method returns an ordered series of the dictionary's keys, much like it does
with lists as well as tuples. The initial Python dictionary is not changed by the ascending
sorting.
Code
1. dict = {7: "Ayan", 5: "Bunny", 8: "Ram", 1: "Bheem"}
2. sorted(dict)
Output
[ 1, 5, 7, 8]

Built-in Dictionary methods


The built-in python dictionary methods along with the description and Code are given below.
o clear()
dict = {1: "Microsoft", 2: "Google", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
dict.clear()
print(dict)
Output
{}

copy()
dict = {1: "Microsoft", 2: "Google", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
dict_demo = dict.copy()
print(dict_demo)
Output
{1: 'Microsoft', 2: 'Google', 3: 'Facebook', 4: 'Amazon', 5: 'Flipkart'}

pop()
dict = {1: "Microsoft", 2: "Google", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
dict_demo = dict.copy()
x = dict_demo.pop(1)
print(x)
Output
{2: 'Google', 3: 'Facebook', 4: 'Amazon', 5: 'Flipkart'}

popitem()
dict = {1: "Microsoft", 2: "Google", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
dict_demo.popitem()
print(dict_demo)
Output
{1: 'Microsoft', 2: 'Google', 3: 'Facebook'}

keys()
dict = {1: "Microsoft", 2: "Google", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
print(dict_demo.keys())
Output
dict_keys([1, 2, 3, 4, 5])

items()
dict = {1: "Microsoft", 2: "Google", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
print(dict_demo.items())
Output
dict_items([(1, 'Microsoft'), (2, 'Google'), (3, 'Facebook'), (4, 'Amazon'), (5, 'Flipkart')])

get()
dict = {1: "Microsoft", 2: "Google", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
print(dict_demo.get(3))
Output
Facebook

update()
dict = {1: "Microsoft", 2: "Google", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
dict_demo.update({3: "TCS"})
print(dict_demo)
Output
{1: 'Microsoft', 2: 'Google', 3: 'TCS'}

values()
1. dict = {1: "Microsoft", 2: "Google", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
2. print(dict_demo.values())
Output
dict_values(['Microsoft', 'Google', 'TCS'])
Python input() Function
The input() function takes input from the user and returns it.

Syntax
Input()
input ([prompt])

Conditional Statements in Python


In Python we can achieve decision making by using the following statements:
 if statements
 if-else statements
 elif statements
 Nested if and if-else statements
 elif ladder
In this tutorial, we will discuss all the statements in detail with some real-time examples.
#1) if statements
The if condition evaluates a Boolean expression and executes the block of code only when
the Boolean expression becomes TRUE.
Syntax:
If ( EXPRESSION == TRUE ):
Block of code
else:
Block of code
Here, the condition will be evaluated to a Boolean expression (true or false). If the condition
is true, then the statement or program present inside the ” if ” block will be executed and if
the condition is false, then the statements or program present inside the “else” block will be
executed.

Let’s see some examples of ” if ” statements.


kitchen= "Apple"

if (kitchen == "Apple"):
print("Ha Hai Apple")
print("Thik hai")

if (kitchen == "Mango"):
print("Ha Hai Mango")
print("Thik hai ")

if (kitchen == "Mango"):
print("Ha Hai Apple")

Example: 1

num = 5
if (num < 10):
print(“Num is smaller than 10”)

print(“This statement will always be executed”)


Output: Num is smaller than 10.
This statement will always be executed.

Example: 2
a=7
b=0
if (a > b):
print(“a is greater than b”)
Output:
a is greater than b

In the above example, we are checking the relationship between a and b using the greater
than (>) operator in the if condition. If “a” is greater than “b” then we will get the above
output.
Example: 3
a=0
b=7
if (b > a):
print(“b is greater than a”)
Output:
b is greater than a.

Example: 4
a=7
b=0
if (a):
print(“true”)
Output:
true

If you observe, in the above example, we are not using or evaluating any condition in the “if”
statement. Always remember that in any programming language, the positive integer will be
treated as true value and an integer which is equal to 0 will be treated as false.
Here the value of a is 7 which is positive, hence it prints true in the console output.
Example: 5
# python program to illustrate If statement

i = 10

if (i > 15):
print("10 is less than 15")
print("I am Not in if")

Output:
I am Not in if

Example: 6
if (‘Python’ in [‘Java', ‘Python’, ‘C#’]):
print(“true”)
Output:
true

Here, we are verifying if the element ‘Python’ is present in the given list or not. Hence it
prints true because “ Python “ is present in the given list.

Let’s take one real-life example where we will use the Python if statement.
For Example: You have written an exam for a total score of 100 and if your score is above or
equal to 40 then you will be considered as PASS in the exam.
Let’s write the code for it.
Example: 7
passing_Score = 40
my_Score = 67
if(my_Score >= passing_Score):
print(“Congratulations! You have passed your exam”)
Output:
Congratulations! You have passed your exam.

Remember to use the (:) operator at the end of the if statement, because whatever the code
you write after the colon operator will be a part of “if block” and indentation is very
important in Python.
Example: 8
passing_Score = 60
my_Score = 67
if(my_Score >= passing_Score):
print(“You passed the exam”)
print(“Congratulations!”)
Output:
You passed the exam
Congratulations!

Here, print(“Congratulations!”) statement will always be executed even though the given
condition is true or false.
The problem with the above code is the statement ‘print(“Congratulations!”)’ will always be
executed even if the condition is evaluated to true or false. But in real-time, if you pass the
exam or if you fail in the exam, then the system will say Congratulations!!!.
In order to avoid this, Python provides one conditional statement called if-else.
#2) if-else statements
The statement itself says if a given condition is true then execute the statements present
inside the “if block” and if the condition is false then execute the “else” block.
The “else” block will execute only when the condition becomes false
Syntax:
If (EXPRESSION == TRUE):
Statement (Body of the block)
else:
Statement (Body of the block)
Here, the condition will be evaluated to a Boolean expression (true or false). If the condition
is true then the statements or program present inside the “if” block will be executed and if
the condition is false then the statements or program present inside the “else” block will be
executed.

Example: 1
num = 5
if(num > 10):
print(“number is greater than 10”)
else:
print(“number is less than 10”)

print (“This statement will always be executed” )


Output:
number is less than 10.
This statement will always be executed.

In the above example, we have declared a variable called ‘num’ with the value as 5 and in
the “if” statement we are checking if the number is greater than 5 or not.
If the number is greater than 5 then, the block of code inside the “if” block will be executed
and if the condition fails then the block of code present inside the “else” block will be
executed.
Example: 2
a=7
b=0
if (a > b):
print(“a is greater than b”)
else:
print(“b is greater than a”)
Output:
a is greater than b

In the above code if “a” is greater than “b” then the statements present inside the “if” block
will be executed and the statements present inside the “else” block will be skipped.
Example: 3
a=7
b=0
if (a < b):
print( “a is smaller than b” )
else:
print( “b is smaller than a” )
Output:
b is smaller than a

In the above code, “a” is smaller than “b”, hence statements present inside the “else” block
will be executed and statements present inside the “if” block will be skipped.
Now let’s take a real-time example.
Example: 4
passing_Score = 60
my_Score = 67
if(my_Score >= passing_Score):
print(“Congratulations! You passed the exam”)
print("You are passed in the exam")
else:
print(“Sorry! You failed the exam, better luck next time”)
Output:
Congratulations! You passed the exam
You are passed in the exam

Example: 5
passing_Score = 60
my_Score = 47
if(my_Score >= passing_Score):
print(“Congratulations! You passed the exam”)
print("You are passed in the exam")
else:
print(“Sorry! You failed the exam, better luck next time”)
Output:
Sorry! You failed the exam, better luck next time

Example: 6

i = 20
if (i < 15):
print("i is smaller than 15")
print("i'm in if Block")
else:
print("i is greater than 15")
print("i'm in else Block")
print("i'm not in if and not in else Block")

#3) elif statements


Elif
The elif keyword is Python's way of saying "if the previous conditions were not true, then
try this condition".
In Python, we have one more conditional statement called “elif” statements. “elif”
statement is used to check multiple conditions only if the given condition is false. It’s similar
to an “if-else” statement and the only difference is that in “else” we will not check the
condition but in “elif” we will check the condition.
“elif” statements are similar to “if-else” statements but “elif” statements evaluate multiple
conditions.
Syntax:
if (condition):
#Set of statement to execute if condition is true
elif (condition):
#Set of statements to be executed when if condition is false and elif condition is true
else:
#Set of statement to be executed when both if and elif conditions are false
Example: 1
num = 10
if (num == 0):
print(“Number is Zero”)
elif (num > 5):
print(“Number is greater than 5”)
else:
print(“Number is smaller than 5”)
Output:
Number is greater than 5

Example: 2
num = -7
if (num > 0):
print(“Number is positive”)
elif (num < 0):
print(“Number is negative”)
else:
print(“Number is Zero”)
Output:
Number is negative

#4) Nested if-else statements


Nested “if-else” statements mean that an “if” statement or “if-else” statement is present
inside another if or if-else block. Python provides this feature as well, this in turn will help us
to check multiple conditions in a given program.
An “if” statement is present inside another “if” statement which is present inside another
“if” statements and so on.

Nested if Syntax:
if(condition):
#Statements to execute if condition is true
if(condition):
#Statements to execute if condition is true
#end of nested if
#end of if
Example: 1
num = 5
if(num >0):
print(“number is positive”)

if(num<10):
print(“number is less than 10”)
Output:
number is positive
number is less than 10

Example: 2
num = 7
if (num != 0):
if (num > 0):
print(“Number is greater than Zero”)
Output:
Number is greater than Zero
Example: 3
i = 10
if (i == 10):
if (i < 20):
print (i, "is smaller than 20")
if (i < 21):
print (i, "is smaller than 21")

Output:
10 is not smaller than 20
10 is smaller than 21

Example: 4
i = 10
if (i == 10):

# First if statement
if (i < 15):
print("i is smaller than 15")

Nested if-else Syntax:


if(condition):
#Statements to execute if condition is true
if(condition):
#Statements to execute if condition is true
else:
#Statements to execute if condition is false
else:
#Statements to execute if condition is false
Here we have included the “if-else” block inside an if block, you can also include an “if-else”
block inside “else” block.
Example: 5
num = -7
if (num != 0):
if (num > 0):
print(“Number is positive”)
else:
print(“Number is negative”)
else:
print(“Number is Zero”)
Output:
Number is negative

Example: 6
i = 10
if (i == 10):
# First if statement
if (i < 15):
print("i is smaller than 15")
# Nested - if statement
# Will only be executed if statement above
# it is true
if (i < 12):
print("i is smaller than 12 too")
else:
print("i is greater than 15")
Output:
i is smaller than 15
i is smaller than 12 too

Example: 7

num = 5
if (num < 4):
print("Num is smaller than 10")
if (num<4):
print("Num is less than 8")
if (num < 5):
print("Num is less than 5")
else:
print("num is not less than 5")
else:
print("num is not less than 8")

else:
print("num is not less than 10")

#5) elif Ladder


“elif” statements are structured in the form of a ladder.
Syntax:
if (condition):
#Set of statement to execute if condition is true
elif (condition):
#Set of statements to be executed when if condition is false and elif condition is true
elif (condition):
#Set of statements to be executed when both if and first elif condition is false and second elif condition is t
elif (condition):
#Set of statements to be executed when if, first elif and second elif conditions are false and third elif statem
else:
#Set of statement to be executed when all if and elif conditions are false
Example: 1

i = 20
if (i == 10):
print("i is 10")
elif (i == 15):
print("i is 15")
elif (i == 20):
print("i is 20")
else:
print("i is not present")
Output:
i is 20

Example: 2
my_marks = 90
if (my_marks < 35):
print(“Sorry!, You failed the exam”)
elif(my_marks > 60 and my_marks < 90):
print(“Passed in First class”)
else:
print(“Passed with distinction”)
Output:
Passed in First class with distinction

Python If Statement In One Line


Example: 1
num = 7
if (num > 0): print(“Number is greater than Zero”)
Output:
Number is greater than Zero

Example: 2
a = 10
if (a): print( " The given value of a: " ); print(a)
Output:
The given value of a: 10

Example: 1
num = 7
if (num > 0): print(“Number is greater than Zero”)
else: print(“Number is smaller than Zero”)
Output:
Number is smaller than Zero

Example: 2
if (‘a’ in ‘fruits’): print(“Apple”); print(“Orange”)
else: print(“Mango”); print(“Grapes”)
Output:
Mango
Grapes

Elif Statements In One Line


Example: 1
num = 7
if (num < 0): print("Number is smaller than Zero")
elif (num > 0): print("Number is greater than Zero")
else: print("Number is Zero")
Output:
Number is greater than Zero

Example: 2
if (‘a’ in ‘fruits’): print(“Apple”); print(“Orange”)
elif (‘e’ in ‘fruits’): print(“Mango”); print(“Grapes”)
else: print(“No fruits available”)
Output:

Example: 1
num1 = 10
num2 = 20
num3 = 30
if (num1 == 10 and num2 == 20 and num3 == 30):
print(“All the conditions are true”)
Output:
All the conditions are true

Here, in the “if” statement we are checking multiple conditions using AND operator, which
means if all the conditions are true only when the statements inside an if block will be
executed.
We can also specify the OR operators as well.
Example: 2
fruitName = “Apple”
if (fruitName == “Mango” or fruitName == “Apple” or fruitName == “Grapes”):
print(“It’s a fruit”)
Output:
It’s a fruit
Here, in an “if” statement out of three conditions, only one condition is true as that’s the
rule of the OR operator. If any one condition is true then the condition will become true and
the statement present inside the if block will be executed.
Let’s consider a real-time scenario to find the number of days present in a month and we
know that during a leap year the number of days will change. We will see this in a
programmatic way using “if, elif and else” statements.
Example: 3

currentYear = int(input (" Enter the year: " ) )


month = int(input("Enter the month: " ) )
if ((currentYear % 4 ) == 0):
print("Leap Year")
if(month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12):
print("There are 31 days in this month " )
elif ( month == 4 or month == 6 or month == 9 or month == 11 ):
print("There are 30 days in this month " )
elif ( month == 2 ):
print("There are 29 days in this month " )
else:
print("Invalid month ")
elif ( ( currentYear % 4 ) != 0):
print("Non Leap Year " )
if ( month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12 ):
print("There are 31 days in this month" )
elif ( month == 4 or month == 6 or month == 9 or month == 11 ):
print("There are 30 days in this month " )
elif ( month == 2 ):
print("There are 28 days in this month ")
else:
print("Invalid month " )
else:
print( " Invalid Year " )

Output: 1
Enter the year: 2020
Enter the month: 4
Leap Year
There are 30 days in this month

Loops Statements in Python


In general, statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on. There may be a situation when you need
to execute a block of code several times.
In Python, there are three different types of loops: for loop, while loop, and nested loop.

While Loop in Python


In python, a while loop is used to execute a block of statements repeatedly until a given
condition is satisfied. And when the condition becomes false, break the line immediately
after the loop in the program is executed.
The while loop is to be used in situations where the number of iterations is unknown at
first. The block of statements is executed in the while loop until the condition specified in
the while loop is satisfied. It is also called a pre-tested loop.

count = 0
while (count < 3):
print("Credence")

count = 0
while (count < 3):
count = count + 1
print("Credence")

count = 0
while (count < 3):
print("Credence")
count = count + 1
else:
print("Not Found ")

i=0
while i < 6:
print(i)
i = i+1

Let’s see a simple example of while loop in Python.

count = 0
while (count < 3):
count = count + 1
print("Hello Geek")

Output
Hello Geek
Hello Geek
Hello Geek

Using else statement with While Loop in Python


The else clause is only executed when your while condition becomes false. If you break out
of the loop, or if an exception is raised, it won’t be executed.
Examples of While Loop with else statement
Here is an example of while loop with else statement in Python:

count = 0
while (count < 3):
count = count + 1
print("Hello Geek")
else:
print("In Else Block")

Output
Hello Geek
Hello Geek
Hello Geek
In Else Block

Infinite While Loop in Python


If we want a block of code to execute infinite number of time, we can use the while loop in
Python to do so.

count = 0
while (count == 0):
print("Hello Geek")
age = 32

# the test condition is always True


while age > 18:
print('You can vote')

i=1
n=5
while i <= n:
print(i)
i=i+1

Output

1
2
3
4
5

Example 2: Python while Loop


# program to calculate the sum of numbers
# until the user enters zero
total = 0
number = int(input('Enter a number: '))
# add numbers until number is zero
while number != 0:
total += number # total = total + number
# take integer input again
number = int(input('Enter a number: '))
print('total =', total)

Output

Enter a number: 12
Enter a number: 4
Enter a number: -5
Enter a number: 0
total = 11

Python for Loop


In Python, the for loop is used to run a block of code for a certain number of times.

Example
Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
Looping Through a String
Even strings are iterable objects, they contain a sequence of characters:
Example
for x in "banana":
print(x)

a=5
for i in range(0, a):
print(i)

The range() Function


The range() function returns a sequence of numbers between the give range

A range is a series of values between two numeric intervals.

Syntax of range()

range(start, stop, step)

# use of range() to define a range of values


values = range(4)
# iterate from i = 0 to i = 3
for i in values:
print(i)

Output

0
1
2
3

In the above example, we have used the for loop to iterate over a range from 0 to 3.

The value of i is set to 0 and it is updated to the next number of the range on each iteration.

This process continues until 3 is reached.

Iteration Condition Action

1st True 0 is printed. i is increased to 1.

2nd True 1 is printed. i is increased to 2.

3rd True 2 is printed. i is increased to 3.

4th True 3 is printed. i is increased to 4.

5th False The loop is terminated

Example
Using the range() function:
for x in range(6):
print(x)
# numbers from 2 to 4 (5 is not included)
numbers = range(2, 5)
print(list(numbers)) # [2, 3, 4]
# numbers from -2 to 3 (4 is not included)
numbers = range(-2, 4)
print(list(numbers)) # [-2, -1, 0, 1, 2, 3]
# returns an empty sequence of numbers
numbers = range(4, 2)
print(list(numbers)) # []
# numbers from 2 to 10 with increment 3 between numbers
numbers = range(2, 10, 3)
print(list(numbers)) # [2, 5, 8]
# numbers from 4 to -1 with increment of -1
numbers = range(4, -1, -1)
print(list(numbers)) # [4, 3, 2, 1, 0]

# numbers from 1 to 4 with increment of 1


# range(0, 5, 1) is equivalent to range(5)
numbers = range(0, 5, 1)
print(list(numbers)) # [0, 1, 2, 3, 4]

Python for loop with else


digits = [0, 1, 5]

for i in digits:
print(i)
else:
print("No items left.")
Run Code

Output

0
1
5
No items left.

fruits = ['banana', 'apple', 'mango']


for index in range(len(fruits)):
print ('Current fruit :', fruits[index])

print ("Good bye!")

nums = (1, 2, 3, 4)
sum_nums = 0
for num in nums:
sum_nums = sum_nums + num
print(f'Sum of numbers is {sum_nums}')

# Output
# Sum of numbers is 10

Python for Vs while loops


The for loop is usually used when the number of iterations is known. For example,
# this loop is iterated 4 times (0 to 3)
for i in range(4):
print(i)
Run Code

The while loop is usually used when the number of iterations is unknown. For example,

while condition:
# run code until the condition evaluates to False

3. Nested Loops
A nested loop is a loop inside a loop.
i in range(1, 5):
for j in range(i):
print(i, end=' ')
print()

adj = ["red", "big", "tasty"]


fruits = ["apple", "banana", "cherry"]

for x in adj:
for y in fruits:
print(x, y)

for i in range(1, 7):


for j in range(i):
print(i,end= " ")
print("")

i=1
while i<=5:
j=1
while j<=i:
print(j,end=" ")
j=j+1
print("")
i=i+1

kitchen= "Apple"
for i in kitchen:
print("Fly kr")
for x in range(6):
print(x)
else:
print("End While Loo Fly")
else:
print("End for loop")
# Initialize list1 and list2
# with some strings
list1 = ['I am ', 'You are ']
list2 = ['healthy', 'fine', 'Yusuf']

# Store length of list2 in list2_size


list2_size = len(list2)

# Running outer for loop to


# iterate through a list1.

for item in list1:

# Printing outside inner loop


print("start outer for loop ")
# Initialize counter i with 0
i=0
# Running inner While loop to
# iterate through a list2.
while (i < list2_size):
# Printing inside inner loop
print("start while loop ")
print(item, list2[i])
# Incrementing the value of i
i=i+1
print("End while loop ")
# Printing outside inner loop
print("end for loop ")
print(text)

for num in range(10,20): #to iterate between 10 to 20


for i in range(2,num): #to iterate on the factors of the number
if num%i == 0: #to determine the first factor
j=num/i #to calculate the second factor
print ('%d equals %d * %d' % (num,i,j))
break #to move to the next number, the #first FOR
else:
print (num, 'is a prime number')

words= ["Apple", "Banana", "Car", "Dolphin" ]


for word in words:
#This loop is fetching word from the list
print ("The following lines will print each letters of ", word)
for letter in word:
#This loop is fetching letter for the word
print (letter)
print("") #This print is used to print a blank line
Control Statements in Python
Break statement
Continue statement
Pass statement

for char in 'Python':


if (char == 'h'):
break
print('Current character: ', char)

for char in 'Python':


if (char == 'h'):
continue
print('Current character: ', char)

for char in 'Python':


if (char == 'h'):
pass
print('Current character: ', char)

Break statement
The break statement in Python is used to terminate or abandon the loop containing the
statement and brings the control out of the loop.
for char in 'Python':
if (char == 'h'):
break
print('Current character: ', char)

Output:
Current character: P
Current character: y
Current character: t

# Prints all letters except 'e' and 's'


for letter in 'geeksforgeeks':
if letter == 'e' or letter == 's':
break
print('Current Letter :', letter)

Continue statement
When a program encounters a continue statement in Python, it skips the execution of the
current iteration when the condition is met and lets the loop continue to move to the next
iteration.
for char in ‘Python’:
if (char == ‘y’):
continue
print(“Current character: “, char)

Output:
Current character: P
Current character: t
Current character: h
Current character: o
Current character: n

nums = [1, 2, -3, 4, -5, 6]

sum_positives = 0

for num in nums:


if num < 0:
continue
sum_positives += num

print(f'Sum of Positive Numbers: {sum_positives}')

Pass statement

The pass statement is a null operator and is used when the programmer wants to do nothing
when the condition is satisfied. This control statement in Python does not terminate or skip
the execution, it simply passes to the next iteration.
A loop cannot be left empty otherwise the interpreter will throw an error and to avoid this,
a programmer can use the pass statement.
A coder can put the pass statement to prevent the interpreter from throwing an error when
a loop or a code block is left empty.
Input:
for letter in 'Flexiple':
if letter == 'x':
pass
print ('Letters: ', letter)

Python Functions
Python Functions is a block of statements that return the specific task.
The idea is to put some commonly or repeatedly done tasks together and make a function
so that instead of writing the same code again and again for different inputs, we can do
the function calls to reuse code contained in it over and over again.

Benefits-
Code Reusability
Code Readability

Types of function

There are two types of function in Python programming:

 Standard library functions - These are built-in functions in Python that are available

to use.

 User-defined functions - We can create our own functions based on our

requirements

Python Library Functions/Built in functions


In Python, standard library functions are the built-in functions that can be used
directly in our program. For example,
 print() - prints the string inside the quotation marks

 len() - returns the length

 sort() - returns sorting order asc or desc

These library functions are defined inside the module. And, to use them we must
include the module inside our program.

Python Function Declaration

The syntax to declare a function is:

def function_name(arguments):
# function body
return

Here,
 def - keyword used to declare a function
 function_name - any name given to the function
 arguments - any value passed to function
 return (optional) - returns value from a function
 : - block of statement’s within fucntion
Let's see an example,

def greet():
print('Hello World!')

Calling a Function in Python

In the above example, we have declared a function named greet() .

def greet():
print('Hello World!')
# call the function
greet()

Example: Python Function


def greet():
print('Hello World!')
# call the function
greet()

print('Outside function')
Run Code
Output

Hello World!
Outside function

def arithmatic(a,b):
print(a+b)
print(a-b)
print(a*b)
print(a/b)
arithmatic(200,50)

Function Arguments/Parameters

Example
def my_function(fname):
print(fname)

my_function("Yusuf")
my_function("Priya")
my_function("Tushar")
Number of Arguments
By default, a function must be called with the correct number of arguments.
Meaning that if your function expects 2 arguments, you have to call the function
with 2 arguments, not more, and not less.
Example
This function expects 2 arguments, and gets 2 arguments:

Python Function Arguments


def add_numbers(num1, num2):
sum = num1 + num2
print("Sum: ",sum)
add_numbers(5, 4)

# Output: Sum: 9
Python Fun
The following are the types of arguments that we can use to call a function:
1. Default arguments
2. Keyword arguments
3. Required arguments/Positional
4. Arbitrary Keyword Arguments/Variable-length arguments

1) Default Arguments
A default argument is a kind of parameter that takes as input a default value if no value is
supplied for the argument when the function is called. Default arguments are demonstrated
in the following instance.\
def myFun(x, y=50):
print("x: ", x)
print("y: ", y)
myFun(10)

def myFun(x, y=50):


print("x: ", x)
print("y: ", y)
myFun(10)
myFun(10,20)

def printinfo( name, age = 35 ):


"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return;

Keyword arguments
You can also send arguments with the key = value syntax.
def student(firstname, lastname):
print(firstname, lastname)
# Keyword arguments
student(firstname='Yusuf', lastname='Tamboli')
student(lastname='Tamboli', firstname='Yusuf')

def printinfo( name, age ):


"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return;

# Now you can call printinfo function


printinfo( age=50, name="miki" )

Required/Positional Arguments
Required arguments are the arguments passed to a function in correct positional
order. Here, the number of arguments in the function call should match exactly with
the function definition.
To call the function printme(), you definitely need to pass one argument, otherwise it
gives a syntax error as follows −
def printme( str ):
"This prints a passed string into this function"
print (str)
return;

# Now you can call printme function


printme()
When the above code is executed, it produces the following result −
Traceback (most recent call last):
File "test.py", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)

def printme( str ):


"This prints a passed string into this function"
print (str)
# Now you can call printme function
printme("Yusuf")

We used the Position argument during the function call so that the first argument
(or value) is assigned to name and the second argument (or value) is assigned to
age. By changing the position, or if you forget the order of the positions, the values
can be used in the wrong places, as shown in the Case-2 example below, where 27
is assigned to the name and Suraj is assigned to the age.

def nameAge(name, age):


print("Hi, I am", name)
print("My age is ", age)

# You will get correct output because


# argument is given in order
print("Case-1:")
nameAge("Suraj", 27)
# You will get incorrect output because
# argument is not in order
print("\nCase-2:")
nameAge(27, "Suraj")

Arbitrary Keyword Arguments


In Python Arbitrary Keyword Arguments, *args, and **kwargs can pass a variable
number of arguments to a function using special symbols. There are two special
symbols:
 *args in Python (Variable length Non-Keyword Arguments)
 **kwargs in Python (Variable length Keyword Arguments)

Variable length non-keywords argument


def numbers(*b):
print(b)
numbers(10,20,30)

def myFun(a):
for i in a:
print(i)

myFun('Hello Welcome to GeeksforGeeks')

def myFun(*argv):
for arg in argv:
print(arg)

myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')

Variable length keyword arguments


def numbers(**b):
print(a)
print(b)
numbers(a=10,b=20,c=30)
Passing a List as an Argument
Example
def my_function(a):
for x in a:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)

return Statement
We write a return statement in a function to leave a function and give the calculated
value when a defined function is called.
To let a function return a value, use the return statement:

# Defining a function without return statement


def square(num):
num ** 2

# Calling function and passing arguments.


print("Without return statement")
print(square(52))

# Defining a function with return statement


def square(num):
return num ** 2
# Calling function and passing arguments.
print("With return statement")
print(square(52))

def arithmatic(a,b):

c=a+b
d=a-b
e=a*b
f=a/b
return c,d,e,f

Recursive Function
A recursive function is a function that repeats its behavior until a specified condition is met.

def greet():
print("Hello")
greet()
greet()

def count(num):
if (num<=0):
print("Stop")
else:
print(num)
count(num-1)
count(5)

Example -
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
num = int(input("Enter a number: "))
print(factorial(num))

Fibonacci Sequence
example -
def fib(n) :
if n==0:
return 0
elif n ==1 :
return 1
else :
return fib(n-1) +fib(n-2)
num = int(input("Enter a number: "))
print(fib(num))
Output:
Enter a number: 7
The 7 element of fibonacci series is: 13
# Function for nth Fibonacci number
def Fibonacci(n):
# Check if input is 0 then it will
# print incorrect input
if n < 0:
print("Incorrect input")
# Check if n is 0
# then it will return 0
elif n == 0:
return 0
# Check if n is 1,2
# it will return 1
elif n == 1 or n == 2:
return 1
else:
return Fibonacci(n-1) + Fibonacci(n-2)
# Driver Program
print(Fibonacci(9))

def fib(n):
previsouno=0
preprevisouno =1

print(previsouno)
print(preprevisouno)
for i in range(2,n):
c= previsouno+preprevisouno
previsouno = preprevisouno
preprevisouno = c
print(previsouno+preprevisouno)
fib(0)

def fib(n):
previsouno=0
preprevisouno =1
if (n==1):
print(previsouno)
else:

print(previsouno)
print(preprevisouno)
for i in range(2,n):
c= previsouno+preprevisouno
previsouno = preprevisouno
preprevisouno = c
print(previsouno+preprevisouno)
fib(5)
Python Variable Scope

Python Global variables -defined outside function and can be used globaly
local variables -defined inside function and only access by that function
1. Local Variables

2. Global Variables

Python Local Variables


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

f()
Can a local variable be used outside a function?
def greet():
# local variable
message = 'Hello'
print('Local', message)
greet()
print(message)
Output

Local Hello
NameError: name 'message' is not defined

Python Global Variables


# declare global variable
message = 'Hello'
def greet():
# declare local variable
print('Local', message)
greet()
print('Global', message)
Run Code

Output

Local Hello
Global Hello
Python Global Keyword

In Python, the global keyword allows us to modify the variable outside of the

current scope.
It is used to create a global variable and make changes to the variable in a
local context.

Access and Modify Python Global Variable


First let's try to access a global variable from the inside of a function,
c = 1 # global variable

def add():
print(c)
add()
# Output: 1
However, if we try to modify the global variable from inside a function as:
# global variable
c=1
def add():
# increment c by 2
c=c+2

print(c)

add()

UnboundLocalError: local variable 'c' referenced before assignment

This is because we can only access the global variable but cannot modify it from inside the

function.

The solution for this is to use the global keyword.


# global variable
c=1
def add():
global c
c=c+2
print(c)
add()
# Output: 3

Global in Nested Functions


In Python, we can also use the global keyword in a nested function. For
example,
def outer_function():
num = 20
def inner_function():
global num
num = 25
print("Before calling inner_function(): ", num) inner_function()
print("After calling inner_function(): ", num)
outer_function()
print("Outside both function: ", num)
Run Code
Output

Before calling inner_function(): 20


After calling inner_function(): 20
Outside both function: 25

Rules of global Keyword


The basic rules for global keyword in Python are:
 When we create a variable inside a function, it is local by default.

 When we define a variable outside of a function, it is global by default. You don't

have to use the global keyword.

 We use the global keyword to read and write a global variable inside a function.

 Use of the global keyword outside a function has no effect.


Python Exception Handling
Python Exceptions
What is an Exception?
When a Python program meets an error, it stops the execution of the rest of
the program. An error in Python might be either an error in the syntax of an
expression or a Python exception. We will see what an exception is. Also, we
will see the difference between a syntax error and an exception
Exceptions versus Syntax Errors
Syntax Error: As the name suggests this error is caused by the wrong syntax
in the code. It leads to the termination of the program.
# initialize the amount variable
amount = 10000
# check that You are eligible to
# purchase Dsa Self Paced or not
if(amount > 2999)
print("You are eligible to purchase Dsa Self Paced")
Output:
SyntaxError: invalid syntax

#Python code after removing the syntax error


string = "Python Exceptions"
for s in string:
if (s != o:
print( s )
Output:
if (s != o:
^
SyntaxError: invalid syntax
The arrow in the output shows where the interpreter encountered a syntactic
error. There was one unclosed bracket in this case. Close it and rerun the
program:

Exceptions: Exceptions are raised when the program is syntactically correct,


but the code results in an error. This error does not stop the execution of the
program, however, it changes the normal flow of the program.

# initialize the amount variable


marks = 10000
# perform division with 0
a = marks / 0
print(a)
Output:
ZeroDivisionError

Different types of exceptions in python:


 SyntaxError: This exception is raised when the interpreter
encounters a syntax error in the code, such as a misspelled
keyword, a missing colon, or an unbalanced parenthesis.
 TypeError: This exception is raised when an operation or function
is applied to an object of the wrong type, such as adding a string to
an integer.
 NameError: This exception is raised when a variable or function
name is not found in the current scope.
 IndexError: This exception is raised when an index is out of range
for a list, tuple, or other sequence types.
 KeyError: This exception is raised when a key is not found in a
dictionary.
 ValueError: This exception is raised when a function or method is
called with an invalid argument or input, such as trying to convert a
string to an integer when the string does not represent a valid
integer.
 AttributeError: This exception is raised when an attribute or
method is not found on an object, such as trying to access a non-
existent attribute of a class instance.
 IOError: This exception is raised when an I/O operation, such as
reading or writing a file, fails due to an input/output error.
 ZeroDivisionError: This exception is raised when an attempt is
made to divide a number by zero.
 ImportError: This exception is raised when an import statement
fails to find or load a module.

Exception Handling in Python


The try block lets you test a block of code for errors.
The except block lets you handle the error.
The else block lets you execute code when there is no error.
The lets you execute code, regardless of the result of the try- and except
blocks.
The cause of an exception is often external to the program itself. For
example, an incorrect input, a malfunctioning IO device etc. Because the
program abruptly terminates on encountering an exception, it may cause
damage to system resources, such as files. Hence, the exceptions should be
properly handled so that an abrupt termination of the program is
prevented.
try :
#statements in try block
except :
#executed when error in try block
try:
a=5
b='0'
print(a/b)
except:
print('Some error occurred.')
print("Out of try except blocks.")

Output
Some error occurred.
Out of try except blocks.

example
x=5
y = "hello"
try:
z=x+y
except TypeError:
print("Error: cannot add an int and a str")
Output
Error: cannot add an int and a str

example
try:
even_numbers = [2,4,6,8]
print(even_numbers[5])
except ZeroDivisionError:
print("Denominator cannot be 0.")
except IndexError:
print("Index Out of Bound.")
# Output: Index Out of Bound

You can mention a specific type of exception in front of the except keyword.
Example: Catch Specific Error Type
try:
a=5
b='0'
print (a+b)
except TypeError:
print('Unsupported operation')
print ("Out of try except blocks")

Output
Unsupported operation
Out of try except blocks

As mentioned above, a single try block may have multiple except blocks. The
following example uses two except blocks to process two different
exception types:
Example:
try:
a=5
b=0
print (a/b)
except TypeError:
print('Unsupported operation')
except ZeroDivisionError:
print ('Division by zero not allowed')
print ('Out of try except blocks')

Output
Division by zero not allowed
Out of try except blocks

However, if variable b is set to '0', TypeError will be encountered and


processed by corresponding except block.

Try with Else Clause


In Python, you can also use the else clause on the try-except block which
must be present after all the except clauses. The code enters the else block
only if the try clause does not raise an exception.
Example: Try with else clause

def AbyB(a , b):


try:
c = ((a+b) / (a-b))
except ZeroDivisionError:
print ("a/b result in 0")
else:
print (c)
AbyB(2.0, 3.0)
AbyB(3.0, 3.0)
else and finally
ax:
try:
#statements in try block
except:
#executed when error in try block
else:
#executed if try block is error-free
finally:
#executed irrespective of exception occured or not
The finally block consists of statements which should be processed
regardless of an exception occurring in the try block or not. As a
consequence, the error-free try block skips the except clause and enters the
finally block before going on to execute the rest of the code. If, however,
there's an exception in the try block, the appropriate except block will be
processed, and the statements in the finally block will be processed before
proceeding to the rest of the code.
The example below accepts two numbers from the user and performs their
division. It demonstrates the uses of else and finally blocks.

Example: try, except, else, finally blocks


Copy
try:
print('try block')
x=int(input('Enter a number: '))
y=int(input('Enter another number: '))
z= x / y
except ZeroDivisionError:
print("except ZeroDivisionError block")
print("Division by 0 not accepted")
else:
print("else block")
print("Division = ", z)
finally:
print("finally block")
x=0
y=0
print ("Out of try, except, else and finally blocks." )
The first run is a normal case. The out of the else and finally blocks is
displayed because the try block is error-free.
Output
try block
Enter a number: 10
Enter another number: 2
else block
Division = 5.0
finally block
Out of try, except, else and finally blocks.
The second run is a case of division by zero, hence, the except block and the
finally block are executed, but the else block is not executed.
Output
try block
Enter a number: 10
Enter another number: 0
except ZeroDivisionError block
Division by 0 not accepted
finally block
Out of try, except, else and finally blocks.
In the third run case, an uncaught exception occurs. The finally block is still
executed but the program terminates and does not execute the program
after the finally block.
Output
try block
Enter a number: 10
Enter another number: xyz
finally block
Traceback (most recent call last):
File "C:\python36\codes\test.py", line 3, in <module>
y=int(input('Enter another number: '))
ValueError: invalid literal for int() with base 10: 'xyz'

# Python program to demonstrate finally

# No exception Exception raised in try block


try:
k = 5//0 # raises divide by zero exception.
print(k)

# handles zerodivision exception


except ZeroDivisionError:
print("Can't divide by zero")

finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')

Output:
Can't divide by zero
This is always executed

Python Module

A Python module is a file containing Python definitions and statements. A


module can define functions, classes, and variables. A module can also
include runnable code.
Create a simple Python module
Let’s create a simple Module1.py in which we define 4 functions, add , sub
,mul and div.

def add(a,b):
print(a+b)

def sub(a,b):
print(a-b)

def mul(a,b):
print(a*b)

def div(a,b):
print(a/b)

Import Module in Python


We can import the functions, and classes defined in a module to another
module using the import statement in some other Python source file.
Syntax of Python Import
import Module1
Note: This does not import the functions or classes directly instead imports
the module only. To access the functions inside the module the dot(.)
operator is used.
Importing modules in Python
Now, we are importing the calc that we created earlier to perform add
operation.

import Module1
Module1.add(20,10)
Module1.sub(20,10)
Module1.mul(20,10)
Module1.div(20,10)
The from-import Statement in Python
Python’s from statement lets you import specific attributes from a module
without importing the module as a whole.
# from Module1 import add,div
# add(20,10)
# div(20,10)

Import all Names


The * symbol used with the from import statement is used to import all the
names from a module to a current namespace.
Syntax:
from Module1 import *
From import * Statement
The use of * has its advantages and disadvantages. If you know exactly what
you will be needing from the module, it is not recommended to use *, else
do so.
# from Module1 import *
# add(20,10)
# sub(20,10)

Renaming the Python module


We can rename the module while importing it using the keyword.
Syntax: Import Module_name as Alias_name

import Module1 as a
a.add(20,10)
a.div(20,10)

Python built-in modules


There are several built-in modules in Python, which you can import
whenever you like.

import math
x = dir(math)
print(x)
# importing built-in module math
import math
# using square root(sqrt) function contained
# in math module
print(math.sqrt(25))

# using pi function contained in math module


print(math.pi)
# using factorial function contained in math module

# 1 * 2 * 3 * 4 = 24
print(math.factorial(4))

How to check Built in Modules available in python?


print(help('modules'))

How to check Built in functions which are available in specific built in module in python?
import math
x = dir(math)
print(x)

How to check all functions available in india module which is user defined
Module1
import india
x = dir(india)
print(x)

How to use call 2 modules in the 3 rd Python module


# Approach 1
import india
import bharat
india.indian()
india.bharatiya()
bharat.indian()
bharat.bharatiya()

# Approach 2
from india import *
from bharat import *
indian()
bharatiya()

# But This will call bharat module as it is imported at last

# To call specific module we use below approach


from india import *
indian()
bharatiya()

from bharat import *


indian()
bharatiya()
Python Packages
A Python module may contain several classes, functions, variables, etc.
whereas a Python package can contains several module. In simpler terms a
package is folder that contains various modules as files.

Creating Package
Let’s create a package named demopack1 that will contain two modules
mod1 and mod2. To create this module follow the below steps –
 Create a folder named demo1 demopack1.
 Inside this folder create an empty Python file i.e. __init__.py
 Then create two modules mod1 and mod2 in this folder.

Import Modules from a Package


We can import these modules using the from…import statement and the
dot(.) operator.

Syntax:
import package_name.module_name

Example: Import Module from package


We will import the modules from the above created package and will use the
functions inside those modules.
from demopack1 import mod1
from demopack1 import mod2

mod1.gfg()
mod2.sum(20,10)

import Pack1.Module1
Pack1.Module1.add(20,10)
Pack1.Module1.show()

import Pack1.Module2
Pack1.Module2.mul(20,10)
Pack1.Module2.show()

from Pack1 import Module1


from Pack1 import Module2
Module1.add(20,10)
Module1.show()
Module2.mul(20,10)
Module2.show()

import Pack1.Module1
import Pack1.Module2
import Pack2.Module3

Pack1.Module1.add(20,10)
Pack1.Module2.div(20,10)
Pack2.Module3.mul(20,10)
Pack1.Module1.show()
Pack1.Module2.show()
Pack2.Module3.show()

import sys
sys.path.append("D:/Python Selenium Practice/Pack1")

sys.path.append("D:/Python Selenium Practice/Pack1/Pack2")

from Pack1 import Module1


from Pack1 import Module2
from Pack2 import Module3

Module1.add(20,10)
Module2.mul(20,10)
Module3.add(30,10)
Module1.show()
Module2.show()
Module3.show()
Python OOPS Concepts

Object Oriented Programming is a way of computer programming using the idea of “objects”
to represents data and methods. It is also, an approach used for creating neat and reusable
code instead of a redundant one.
What are Python OOPs Concepts?
Major OOP (object-oriented programming) concepts in Python include Class, Object,
Method, Inheritance, Polymorphism, Data Abstraction, and Encapsulation.
What are Classes and Objects?
A class is a collection of objects or you can say it is a blueprint of objects defining the
common attributes and behavior. Now the question arises, how do you do that?
Class is defined under a “Class” Keyword.
 Classes are created by keyword class.
 Attributes are the variables that belong to a class.
 Attributes are always public and can be accessed using the dot (.)
operator. Eg.: Myclass.Myattribute
Example: Creating an empty Class in Python
class Dog:
pass

Objects:
The object is an entity that has a state and behavior associated with it. It
may be any real-world object like a mouse, keyboard, chair, table, pen, etc.
Integers, strings, floating-point numbers, even arrays, and dictionaries, are
all objects.
An object consists of :
 State: It is represented by the attributes of an object. It also
reflects the properties of an object.
 Behavior: It is represented by the methods of an object. It also
reflects the response of an object to other objects.
 Identity: It gives a unique name to an object and enables one
object to interact with other objects.
Class and Object
Class is logical entity which contains logic
class contains variables (attributes/state) and methods (behaviour)
logic will be included in the method
we can create variables and methods in class.
An object is physical entity which is created for class.
We can create any no of objects for a class
Class is Blueprint of An Object

Examples and sub topics


Creating basic class and Object which includes methods
instance method and static method
static method with parameters
declaring variables inside the class
local variables, global variables and class variables
local variables, global variables and class variables with same name
creating multiple objects for same class
named object and nameless objects
how to check memory locations of objects
Constructor
Converting local variable to class variable
How to call current class method in another method
Constructor with Arguments

Creating basic class and Object which includes methods

class Myclass:

def myfun(self): # self keyword- it says myfun method belongs to Myclass


pass

def display(self,name): # self is just keyword which say dispay is method belongs Myclass, name is
argument.
print("name is:", name)

mc=Myclass() # Myclass is actual object and mc is reference variable means vraible which holds
Myclass object
mc.myfun() # kuch nhi milega
mc.display("Yusuf") # name is: Yusuf

Myclass().myfun()
Myclass().display()

instance method and static method


class Myclass1():
def m1(self): # Instance Method - When i create a method withing a class by default it is instance
method
print("We are printing Instance Method")

@staticmethod
def m2(): # Static Method
# In this self is treated as actual arguments not like instance method menas
# we must have to pass the argument while accesing this method using object.

print("We are printing Static Method")

mc1 = Myclass1() # mc1 is instance variable which will store Myclass1 Object
mc1.m1() # We are printing Instance Method

# Myclass1().m2("Anil") # We are printing Static Method with self.


# Myclass1().m2() # We are printing Static Method without self
#Difference between instance and static method
# static method -
# staticmethod keyword use is manadatory,
# dont need to create an object to access that method,
# no need to use self, if u use then it will be taken as argument then u have to pass the arguments
while accessing it.

static method with parameters


class Myclass1():
def m1(self):
print("We are printing Instance Method")
@staticmethod
def m2(self): # Static Method
print("We are printing Static Method")

mc1 = Myclass1()
mc1.m1()
Myclass1().m2("Anil")

static method without parameter


class Myclass1():
def m1(self):
print("We are printing Instance Method")
@staticmethod
def m2(): # Static Method
print("We are printing Static Method")

mc1 = Myclass1()
mc1.m1()
Myclass1().m2()

Difference between instance and static method


static method -
@staticmethod keyword use is manadatory,
no need to use self, if u use then it will be taken as argument then u have to pass the
arguments while accessing it.

instance method -
@staticmethod keyword use is not manadatory,
must need to use self, if u use then it will be taken as keyword which will say m1 method is
part of Myclass1.

declaring variables inside the class


class Myclass2:

a = 100 # Class variable


b = 200 # class Variable
def add(self):
# print(a+b) # It will not add becz a and b are not defined in add method
print(self.a+self.b) # it will add becz self will used to access the class variables

def mul(self):
print(self.a*self.b)

mc2 = Myclass2()

mc2.add()
mc2.mul()

local variables, global variables and class variables

i,j = 100,200 # Global Variables


class Myclass3:
a,b= 10,20 # Class variables

def add(self,x,y):
print(x+y) # accessing x and y are Local Variables but we havent defined thats why it will not add
values.
print(self.a+self.b)
print(i+j)

mc3 = Myclass3()

mc3.add(1000,2000)

local variables, global variables and class variables with same name
a,b=100,200 # Global variables
class Myclass4:
a,b=10,20 # Class Variables
def add(self,a,b): # Local Variables
print(a+b) # access local with normal print
print(self.a+self.b) # access class with self keyword
print(a+b) # access local with normal print
print(globals()['a']+globals()['b']) # access global with globals method

mc4=Myclass4()
mc4.add(1000,2000)

creating multiple objects for same class


class Myclass5:
def add(self,x,y):
print(x+y)

mc5= Myclass5()
mc6= Myclass5()
mc5.add(1000,2000)
mc6.add(1000,2000)

class Myclass5:
def add(self,x,y):
print(x+y)
def display(self):
print("Hello")

mc5= Myclass5()
mc6= Myclass5()
mc5.add(1000,2000)
mc5.display()
mc6.add(1000,2000)
mc6.display()

named and nameless objects

class Myclass5:
def add(self,x,y):
print(x+y)
def display(self):
print("Hello")

mc5= Myclass5() # Named Object mc5

mc5.add(1000,2000) # Named Object mc5 accessing the add method from class
mc5.display() # Named Object mc5 accessing the display method from class

Myclass5().add(1000,2000) # Nameless Object accessing the add method from class


Myclass5().display() # Nameless Object accessing the display method from class

how to check memory locations of objects


class Myclass5:
def add(self,x,y):
print(x+y)
def display(self):

print("Hello")
mc5= Myclass5()
mc6= Myclass5()
mc5.add(1000,2000)
mc5.display()
mc6.add(1000,2000)
mc6.display()

print(id(mc5))
print(id(mc6))
Constructor
Constructors are generally used for initializing an object. In Python the __init__() method
is called the constructor and is always called when an object is created.

The constructor is called automatically when you create an object using the class name and
parentheses.
Types of constructors :
 default constructor: The default constructor is a simple constructor which
doesn’t accept any arguments. Its definition has only one argument which is a
reference to the instance being constructed.
 parameterized constructor: constructor with parameters is known as
parameterized constructor. The parameterized constructor takes its first
argument as a reference to the instance being constructed known as self and
the rest of the arguments are provided by the programmer.

Syntax of constructor declaration :


def __init__(self):
# body of the constructor
Difference between method and constructor
Method defines the logic in the body and constructor will use to assign the values(variables)
We have to create an object to call method

Constructor used for initialization


We don’t have to call an object to access the constructor

Constructor without Arguments(default Constructor)


class Myclass7():
def __init__(self):
print("This is Constructor")
mc7 = Myclass7()

Constructor with Arguments(Parameterized Constructor)


class Myclass10():
def __init__(self,name):
print(name)
mc10=Myclass10("Abhi")

class Myclass10():
name="Amit" #class variable
def __init__(self,name): # local Variable
print(name)
print(self.name)

mc10=Myclass10("Abhi")
Converting local variable to class variable
class Myclass8:
def values(self,val1,val2): # val1 and val2 are local variables
print(val1)
print(val2)
def add(self):
print(val1+val2) # cant print becz val1 and val2 are part of values method

mc8=Myclass8()
mc8.values(10,20)
mc8.add()

class Myclass8:
def values(self,val1,val2): # val1 and val2 are local variables
print(val1)
print(val2)
self.val1=val1 # val1 become class variable
self.val2=val2 # val2 become class variable
def add(self):
print(self.val1+self.val2) # cant print becz val1 and val2 are part of values method
mc8=Myclass8()

mc8.values(10,20)
mc8.add()

Parameterized Constructor
class Myclass8:
def __init__(self,val1,val2): # val1 and val2 are Parameterized Constructor local variables
print(val1)
print(val2)
self.val1=val1 # val1 become class variable
self.val2=val2 # val2 become class variable
def add(self):
print(self.val1+self.val2) # cant print becz val1 and val2 are part of values method

mc8=Myclass8(10,20)
mc8.add()

How to call current class method in another method


class Myclass9:
def m1(self):
print("This is m1 method")
self.m2(100)
def m2(self,a):
print("This is m2 method and value of argument is:",a)
m9=Myclass9()

m9.m1()

Requirement
Class name- Emp
Constructor – accepts eid,ename,esal
Display method – prints eid,ename,esal

class emp:
def __init__(self,eid,ename,esal): # local varaible
self.eid = eid
self.ename = ename
self.esal = esal
def display(self):
print("Empid: {} Empname:{} Empsal:{}".format(self.eid,self.ename,self.esal))
e1=emp(10,"Yusuf",60000)

e1.display()

Python Inheritance
Inheritance allows us to define a class that inherits all the methods and properties from
another class.
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.
Parent class - superclass Baseclass
Child class - subclass Derived Class
Benefits of inheritance are:
 It represents real-world relationships well.
 It provides the reusability of a code. We don’t have to write the same code
again and again. Also, it allows us to add more features to a class without
modifying it.
 It is transitive in nature, which means that if class B inherits from another class
A, then all the subclasses of B would automatically inherit from class A.
 Inheritance offers a simple, understandable model structure.
 Less development and maintenance expenses result from an inheritance.
Different types of Inheritance:
 Single inheritance: When a child class inherits from only one parent class, it is
called single inheritance. We saw an example above.
 Multiple inheritances: When a child class inherits from multiple parent classes,
it is called multiple inheritances.
 Multilevel inheritance: When we have a child and grandchild relationship.
 Hierarchical inheritance More than one derived class are created from a single
base.
 Hybrid inheritance: This form combines more than one form of inheritance.
Basically, it is a blend of more than one type of inheritance.

1. Single inheritance: When only child class inherits from only one parent class, it is called
single inheritance
class A:
def m1(self):
print("This m1 method is from Parent A")
#a1=A()
#a1.m1() # Parent class object call m1
class B(A):
pass
b1=B()
b1.m1() # Child class object call m1

class A:
def m1(self):
print("This m1 method is from Parent A")
class B(A):
def m2(self):
print("This m2 method is from Parent B")
aobj=A()
aobj.m1() # Parent class object call m1
bobj=B()
bobj.m2() # Child class object call child method m2
bobj.m1() # Child class object call parent method m1

class Parent:
def flats(self,delhi,Pune):
print("Parent ka flat hai Delhi me",delhi)
print("unka pune bhi flat hai ",Pune)

class Child(Parent):
def Print(self):
print("Mera kuch nahi hai")
print("Parent ka sab apna hai")
c = Child()

c.Print()
c.flats('1BHK','2BHK')

class A:
a,b=100,200
def m1(self):
print(self.a+self.b)

class B(A):
x,y=10,20
def m2(self):
print(self.x + self.y)

bobj=B()
bobj.m2()
bobj.m1()

2.Multiple inheritances: When a child class inherits from multiple parent classes, it is
called multiple inheritances
C--A,B
class A():
def m1(self):
print("This is m1 method of Parent A")
class B():
def m2(self):
print("This is m2 method of Child B")
class C(A,B):
def m3(self):
print("This is m3 method of GrandChild C")

a1=A()
a1.m1()
# a1.m2() #invalid

b1=B()
# b1.m1() #invalid
b1.m2()

c1=C()
c1.m1()
c1.m2()
c1.m3()

3. Multilevel inheritance: When we have a child and grandchild relationship.


C--B--A
class A:
a,b=100,200
def m1(self):
print(self.a+self.b)

class B(A):
x,y=10,20
def m2(self):
print(self.x + self.y)
class C(B):
i,j=1000,2000
def m3(self):
print(self.i + self.j)
aobj=A()
aobj.m1()
# aobj.m2() # invalid
# aobj.m3() # invalid

bobj=B()
bobj.m2()
bobj.m1()
# bobj.m3() # invalid

cobj=C()
cobj.m3()
cobj.m2()
cobj.m1()

4. Hierarchical inheritance More than one derived class are created from a single base.
C--A,B--A
class A():
def m1(self):
print("This is m1 method of Parent A")
class B(A):
def m2(self):
print("This is m2 method of Child B")
class C(A):
def m3(self):
print("This is m3 method of GrandChild C")
b1=B()
b1.m1()
b1.m2()

c1=C()
c1.m1()
c1.m3()
#c1.m2() # invalid

5. Hybrid inheritances
class A(B):
def m1(self):
print("This is m1 method of Parent A")
class B(A):
def m2(self):
print("This is m2 method of Child B")

a1=A()
a1.m1()
a1.m2()
b1=B()
b1.m1()
b1.m2()

The super() Method in Python Inheritance

Previously we saw that the same method in the subclass overrides the method in the

superclass.

However, if we need to access the superclass method from the subclass, we use
the super() method.

Super() can be used in 3 ways

1. to invoke the parent class methods

2. to invoke the parent class variables

3. to invoke the parent class constructor

1. to invoke the parent class methods


class A():
def m1(self):
print("This is m1 method of Parent A")
class B(A):
def m2(self):
print("This is m2 method of Child B")
super().m1()
bobj=B()
bobj.m2()

2. to invoke the parent class variables


class A:
a,b=100,200
def m1(self):
print(self.a+self.b)

class B(A):
i,j=10,20
def m2(self,x,y):
print(x+y) # local variable
print(self.i + self.j) # child class variables
print(self.a + self.b) # parent class variables
bobj=B()
bobj.m2(10,200)

a,b= 10000,20000

class A:
a,b=100,200
def m1(self):
print(self.a+self.b)

class B(A):
a,b=10,20
def m2(self,a,b):
print(a+b) # local variable 300
print(self.a + self.b) # child class variables 30
print(self.a + self.b) # Child class variables 30
print(super().a + super().b) # parent class variables 300
print(a+b) # local variables 300
print(globals() ['a'] + globals() ['b']) # global variables
bobj=B()
bobj.m2(1,2)

3. to invoke the parent class constructor


class A():
def __init__(self):
print("This is constructor of parent A")
class B(A):
pass

bobj=B()

class A():
def __init__(self):
print("This is constructor of parent A")
class B(A):
def __init__(self):
print("This is constructor of parent B")

bobj=B()

class A():
def __init__(self):
print("This is constructor of parent A")
class B(A):
def __init__(self):
print("This is constructor of parent B")
super().__init__() # calls the parent call consrtuctor
A.__init__(self) # calls the parent call consrtuctor
bobj=B()
Polymorphism in Python
What is Polymorphism: The word polymorphism means having many forms. In programming,
polymorphism means the same function name (but different values) being used for different types.
Example of inbuilt polymorphic functions:
# len() being used for a string
print(len("geeks"))
# len() being used for a list
print(len([10, 20, 30]))

Examples of user-defined polymorphic functions:


def add(x, y, z = 0):
return x + y+z
# Driver code
print(add(2, 3))
print(add(2, 3, 4))

Polymorphism with class methods:


class India():
def capital(self):
print("New Delhi is the capital of India.")
def language(self):
print("Hindi is the most widely spoken language of India.")
def type(self):
print("India is a developing country.")

class USA():
def capital(self):
print("Washington, D.C. is the capital of USA.")
def language(self):
print("English is the primary language of USA.")
def type(self):
print("USA is a developed country.")

obj_ind = India()
obj_usa = USA()
for country in (obj_ind, obj_usa):
country.capital()
country.language()
country.type()

Output
New Delhi is the capital of India.
Hindi is the most widely spoken language of India.
India is a developing country.
Washington, D.C. is the capital of USA.
English is the primary language of USA.
USA is a developed country.

Polymorphism with Inheritance:


In Python, Polymorphism lets us define methods in the child class that have the same name as the
methods in the parent class. In inheritance, the child class inherits the methods from the parent
class. However, it is possible to modify a method in a child class that it has inherited from the
parent class. This is particularly useful in cases where the method inherited from the parent class
doesn’t quite fit the child class. In such cases, we re-implement the method in the child class. This
process of re-implementing a method in the child class is known as Method Overriding

class Bird:
def intro(self):
print("There are many types of birds.")
def flight(self):
print("Most of the birds can fly but some cannot.")

class sparrow(Bird):
def flight(self):
print("Sparrows can fly.")

class ostrich(Bird):
def flight(self):
print("Ostriches cannot fly.")

obj_bird = Bird()
obj_spr = sparrow()
obj_ost = ostrich()

obj_bird.intro()
obj_bird.flight()

obj_spr.intro()
obj_spr.flight()

obj_ost.intro()
obj_ost.flight()

Output
There are many types of birds.
Most of the birds can fly but some cannot.
There are many types of birds.
Sparrows can fly.
There are many types of birds.
Ostriches cannot fly.

class A:
def m1(self,a=100,b=200):
print(a+b)
class B(A):
def m1(self,x=10,y=20):
print(x+y)
super().m1()
# aobj=A()
# aobj.m1()
bobj= B()
bobj.m1()

Polymorphism with a Function and objects:


It is also possible to create a function that can take any object, allowing for polymorphism. In this
example, let’s create a function called “func()” which will take an object which we will name “obj”.
Though we are using the name ‘obj’, any instantiated object will be able to be called into this
function. Next, let’s give the function something to do that uses the ‘obj’ object we passed to it. In
this case, let’s call the three methods, viz., capital(), language() and type(), each of which is defined
in the two classes ‘India’ and ‘USA’. Next, let’s create instantiations of both the ‘India’ and ‘USA’
classes if we don’t have them already. With those, we can call their action using the same func()
function:

class India():
def capital(self):
print("New Delhi is the capital of India.")
def language(self):
print("Hindi is the most widely spoken language of India.")
def type(self):
print("India is a developing country.")

class USA():
def capital(self):
print("Washington, D.C. is the capital of USA.")
def language(self):
print("English is the primary language of USA.")
def type(self):
print("USA is a developed country.")

def func(obj):
obj.capital()
obj.language()
obj.type()

obj_ind = India()
obj_usa = USA()

func(obj_ind)
func(obj_usa)

Output
New Delhi is the capital of India.
Hindi is the most widely spoken language of India.
India is a developing country.
Washington, D.C. is the capital of USA.
English is the primary language of USA.
USA is a developed country.

Simple example of polymorphism:


polymorphism in Python using inheritance and method overriding:

class Animal:
def speak(self):
raise NotImplementedError("Subclass must implement this method")

class Dog(Animal):
def speak(self):
return "Woof!"

class Cat(Animal):
def speak(self):
return "Meow!"

# Create a list of Animal objects


animals = [Dog(), Cat()]
# Call the speak method on each object
for animal in animals:
print(animal.speak())
Output
Woof!
Meow

Method Overriding
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.
NOTE:python overriding mean there are two class A and B with different name,B inherits A that
mean a is parent.both classes having same method name but when you calls the class it gives the
result from method of class B although you have inherited class A

To tackle this issue that is to use method of parent class A we can use super.
# Python program to demonstrate
# method overriding
1. class Parent():
2. def __init__(self):
3. self.value = "Inside Parent"
4. # showing a parents method
5. def show(self):
6. print(self.value)
7. # Defining a child class
8.
9. class Child(Parent):
10. def __init__(self):
11. self.value = "Inside Child"
12. # showing the child's method
13. def show(self):
14. print(self.value)
15.
16. obj1 = Parent()
17. obj2 = Child()
18. obj1.show()
19. obj2.show()

Output:
Inside Parent
Inside Child

However, what if the same method is present in both the superclass and subclass?

In this case, the method in the subclass overrides the method in the superclass. This concept is known

as method overriding in PythonExample: Method Overriding


class Animal:
# attributes and method of the parent class
name = ""
def eat(self):
print("I can eat")

# inherit from Animal


class Dog(Animal):
# override eat() method
def eat(self):
print("I like to eat bones")

# create an object of the subclass


labrador = Dog()
# call the eat() method on the labrador object
labrador.eat()
Output

I like to eat bones

In the above example, the same method eat() is present in both the Dog class and the Animal class.

Now, when we call the eat() method using the object of the Dog subclass, the method of

the Dog class is called.

This is because the eat() method of the Dog subclass overrides the same method of

the Animal superclass.

For example,
class Animal:
name = ""
def eat(self):
print("I can eat")

# inherit from Animal


class Dog(Animal):
# override eat() method
def eat(self):
# call the eat() method of the superclass using super()
super().eat()
print("I like to eat bones")

# create an object of the subclass


labrador = Dog()
labrador.eat()
Run Code

Output

I can eat
I like to eat bones

In the above example, the eat() method of the Dog subclass overrides the same method of

the Animal superclass.

Inside the Dog class, we have used

# call method of superclass


super().eat()

to call the eat() method of the Animal superclass from the Dog subclass.

So, when we call the eat() method using the labrador object

# call the eat() method


labrador.eat()

Both the overridden and the superclass version of the eat() method is executed.

Method Overloading:
Method overloading-
By default python does not accept method overloading.method overloading means class having
methods with same name and with same content or operation or program in it but different
argument

Here it throughs exception it ask for additional argument at line 7,since we have provided only two
and python gives priority two latest method
To solve this problem

We have provided default value and method name is same and it works for either number of
arguments

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.
Like other languages (for example, method overloading in C++) do, python
does not support method overloading by default. But there are different
ways to achieve method overloading in Python.
The problem with method overloading in Python is that we may overload the
methods but can only use the latest defined method.
# product
def product(a, b):
p=a*b
print(p)
def product(a, b, c):
p = a * b*c
print(p)
product(4, 5, 5)

Output
100

Method 1 (Not The Most Efficient Method):


We can use the arguments to make the same function work differently i.e. as
per the arguments

def add(datatype, *args):


if datatype == 'int':
answer = 0
if datatype == 'str':
answer = ''
for x in args:
answer = answer + x
print(answer)
add('int', 5, 6)
add('str', 'Hi ', 'Geeks')

Output
11
Hi Geeks

class Myclass5:
def add(self,x,y):
print(x+y)
def display(self):
print("Hello")

mc5= Myclass5()
mc5.add(1000,2000)
mc5.display()
mc5.add(100,200)
mc5.display()
mc5.add(10,20)
mc5.display()
Abstraction in Python
Here note that in class X has two abstract method,in Y we only mentioned one so we
cannot call the method so we created one more class Z,inhereted class Y method and
added new method in Z,so now we have two method of class X and we can create object
for class Z and we can access both methods.
Here A is abstract method we cannot access it and it has no implementation so to add
implementation we created class B,inherited class A, and then gave implementation.
abc is predefined package for abstract class and method
Abstraction is used to hide the internal functionality of the function from the users.
The users only interact with the basic implementation of the function, but inner
working is hidden. User is familiar with that "what function does" but they don't
know "how it does."
Why Abstraction is Important?
It also enhances the application efficiency.

Abstraction classes in Python


In Python, abstraction can be achieved by using abstract classes and interfaces.
A class that consists of one or more abstract method is called the abstract class.
Abstract methods do not contain their implementation. Abstract class can be
inherited by the subclass and abstract method gets its definition in the subclass.
Abstraction classes are meant to be the blueprint of the other class. An abstract class
can be useful when we are designing large functions
Syntax
1. from abc import ABC
2. class ClassName(ABC):
We import the ABC class from the abc module.

Working of the Abstract Classes


Unlike the other high-level language, Python doesn't provide the abstract class itself. We
need to import the abc module, which provides the base for defining Abstract Base classes
(ABC). The ABC works by decorating methods of the base class as abstract. It registers
concrete classes as the implementation of the abstract base. We use
the @abstractmethod decorator to define an abstract method or if we don't provide the
definition to the method, it automatically becomes the abstract method. Let's understand
the following example.
Example -
1. # Python program demonstrate
2. # abstract base class work
3. from abc import ABC, abstractmethod
4. class Car(ABC):
5. def mileage(self):
6. pass
7. class Tesla(Car):
8. def mileage(self):
9. print("The mileage is 30kmph")
10. class Suzuki(Car):
11. def mileage(self):
12. print("The mileage is 25kmph ")
13. class Duster(Car):
14. def mileage(self):
15. print("The mileage is 24kmph ")
16. class Renault(Car):
17. def mileage(self):
18. print("The mileage is 27kmph ")
19. # Driver code
20.
21. t= Tesla ()
22. t. mileage ()
23. r = Renault ()
24. r. mileage ()
25. s = Suzuki ()
26. s. mileage ()
27. d = Duster ()
28. d.mileage ()
Output:
The mileage is 30kmph
The mileage is 27kmph
The mileage is 25kmph
The mileage is 24kmph

# Python program to define


# abstract class
from abc import ABC

class Polygon(ABC):
# abstract method
def sides(self):
pass
class Triangle(Polygon):
def sides(self):
print("Triangle has 3 sides")

class Pentagon(Polygon):
def sides(self):
print("Pentagon has 5 sides")

class Hexagon(Polygon):
def sides(self):
print("Hexagon has 6 sides")

class square(Polygon):
def sides(self):
print("I have 4 sides")

# Driver code
t = Triangle()
t.sides()

s = square()
s.sides()

p = Pentagon()
p.sides()

k = Hexagon()
K.sides()
Output:
Triangle has 3 sides
Square has 4 sides
Pentagon has 5 sides
Hexagon has 6 sides
Explanation -
In the above code, we have defined the abstract base class named Polygon and we also
defined the abstract method. This base class inherited by the various subclasses. We
implemented the abstract method in each subclass. We created the object of the subclasses
and invoke the sides() method. The hidden implementations for the sides() method inside
the each subclass comes into play. The abstract method sides() method, defined in the
abstract class, is never invoked.
Points to Remember
Below are the points which we should remember about the abstract base class in Python.
o An Abstract class can contain the both method normal and abstract method.
o An Abstract cannot be instantiated; we cannot create objects for the abstract class.
Abstraction is essential to hide the core functionality from the users. We have covered the all
the basic concepts of Abstraction in Python
Example for abstraction:
Let say there are two apps BankApp(parent) and MobileApp(child) but to access or inherit properties
of BankApp MObileApp need security code.which should be implemented to access other methods of
parent class otherwise it throws error check error massage.
Once you include security method to child you can access database method,as well as security
method too
After creating object

After adding security class

Encapsulation in Python

Encapsulation is one of the most fundamental concepts in object-oriented


programming (OOP). This is the concept of wrapping data and methods that work
with data in one unit. This prevents data modification accidentally by limiting
access to variables and methods. An object's method can change a variable's value
to prevent accidental changes. These variables are called private variables.
Encapsulation is demonstrated by a class which encapsulates all data, such as
member functions, variables, and so forth.
Take a look at a real-world example of encapsulation. There are many sections in a
company, such as the accounts and finance sections. The finance section manages all
financial transactions and keeps track of all data. The sales section also handles all
sales-related activities. They keep records of all sales. Sometimes, a finance official
may need all sales data for a specific month. In this instance, he is not permitted to
access the data from the sales section. First, he will need to contact another officer
from the sales section to request the data. This is encapsulation. The data for the
sales section, as well as the employees who can manipulate it, are all wrapped
together under the single name "sales section". Encapsulation is another way to hide
data. This example shows that the data for sections such as sales, finance, and
accounts are hidden from all other sections.
Encapsulation in Python describes the concept of bundling data and methods within
a single unit. So, for example, when you create a class, it means you are
implementing encapsulation. A class is an example of encapsulation as it binds all the
data members (instance variables) and methods into a single unit.

Example:
In this example, we create an Employee class by defining employee attributes
such as name and salary as an instance variable and implementing behavior
using work() and show() instance methods.
class Employee:
# constructor
def __init__(self, name, salary, project):
# data members
self.name = name
self.salary = salary
self.project = project

# method
# to display employee's details
def show(self):
# accessing public data member
print("Name: ", self.name, 'Salary:', self.salary)

# method
def work(self):
print(self.name, 'is working on', self.project)

# creating object of a class


emp = Employee('Jessa', 8000, 'NLP')

# calling public method of the class


emp.show()
emp.work()

Output:
Name: Jessa Salary: 8000
Jessa is working on NLP

Using encapsulation, we can hide an object’s internal representation from the


outside. This is called information hiding.
Also, encapsulation allows us to restrict accessing variables and methods directly and
prevent accidental data modification by creating private data members and methods
within a class.
Encapsulation is a way to can restrict access to methods and variables from outside
of class. Whenever we are working with the class and dealing with sensitive data,
providing access to all variables used within the class is not a good choice.
For example, Suppose you have an attribute that is not visible from the outside of an
object and bundle it with methods that provide read or write access. In that case,
you can hide specific information and control access to the object’s internal state.
Encapsulation offers a way for us to access the required variable without providing
the program full-fledged access to all variables of a class. This mechanism is used to
protect the data of an object from other objects
Access Modifiers in Python
Encapsulation can be achieved by declaring the data members and methods of a class either
as private or protected. But In Python, we don’t have direct access modifiers like public,
private, and protected. We can achieve this by using
single underscore and double underscores.
Access modifiers limit access to the variables and methods of a class. Python provides three
types of access modifiers private, public, and protected.
 Public Member: Accessible anywhere from otside oclass.
 Private Member: Accessible within the class and we use _ _
 Protected Member: Accessible within the class and its sub-classes and we
use _
Private variable exapmple
class myclass():
__a=10
def display(self):
print(self.__a)
obj=myclass()
obj.display()

class myclass():
__a=10 # private class variable
x=20 # Public class variable
def display(self):
print(self.x)
print(self.__a)
# print(self.a) # we cant use private variable outside the class
obj=myclass()
obj.display()

class myclass():
__a=10
x=20
print(__a)
def display(self):
print(self.__a)
obj=myclass()
obj.display()
# print(myclass.__a) # private variables cant access outside class
print(myclass.x)

Private method exapmple

class myclass():
def __display(self):
print("This is private method")
def show(self):
print("This is public method")
self.__display()
obj=myclass()
# obj.__dispaly() we cant access private method outside the class
obj.show()

Public Member
Public data members are accessible within and outside of a class. All member
variables of the class are by default public.

class Employee:
# constructor
def __init__(self, name, salary):
# public data members
self.name = name
self.salary = salary

# public instance methods


def show(self):
# accessing public data member
print("Name: ", self.name, 'Salary:', self.salary)

# creating object of a class


emp = Employee('Jessa', 10000)

# accessing public data members


print("Name: ", emp.name, 'Salary:', emp.salary)

# calling public method of the class


emp.show()

Private Member
We can protect variables in the class by marking them private. To define a private
variable add two underscores as a prefix at the start of a variable name.
Private members are accessible only within the class, and we can’t access them
directly from the class objects.
class Employee:
# constructor
def __init__(self, name, salary):
# public data member
self.name = name
# private member
self.__salary = salary

# creating object of a class


emp = Employee('Jessa', 10000)

# accessing private data members


print('Salary:', emp.__salary)

Output
AttributeError: 'Employee' object has no attribute '__salary'

In the above example, the salary is a private variable. As you know, we can’t access the
private variable from the outside of that class.
We can access private members from outside of a class using the following two approaches
 Create public method to access private members
 Use name mangling
 Let’s see each one by one
Public method to access private members
Example: Access Private member outside of a class using an instance method
class Employee:
# constructor
def __init__(self, name, salary):
# public data member
self.name = name
# private member
self.__salary = salary

# public instance methods


def show(self):
# private members are accessible from a class
print("Name: ", self.name, 'Salary:', self.__salary)

# creating object of a class


emp = Employee('Jessa', 10000)

# calling public method of the class


emp.show()
Output:
Name: Jessa Salary: 10000

Protected Member
Protected members are accessible within the class and also available to its sub-
classes. To define a protected member, prefix the member name with a single
underscore _.
Protected data members are used when you implement inheritance and want to
allow data members access to only child classes.
Example: Proctecd member in inheritance.
class Employee(Company):
def __init__(self, name):
self.name = name
Company.__init__(self)

def show(self):
print("Employee name :", self.name)
# Accessing protected member in child class
print("Working on project :", self._project)
c = Employee("Jessa")
c.show()

# Direct access protected data member


print('Project:', c._project)
Output
Employee name : Jessa
Working on project : NLP
Project: NLP
Python File Handling
The file handling plays an important role when the data needs to be
stored permanently into the file. A file is a named location on disk to
store related information. We can access the stored information
(non-volatile) after the program termination.
The file-handling implementation is slightly lengthy or complicated in the
other programming language, but it is easier and shorter in Python.

The key function for working with files in Python is


the open() function.
The open() function takes two parameters; filename, and mode.
There are four different methods (modes) for opening a file:
"r" - Read - Default value. Opens a file for reading, error if the file
does not exist
"a" - Append - Opens a file for appending, creates the file if it does
not exist
"w" - Write - Opens a file for writing, creates the file if it does not
exist
"x" - Create - Creates the specified file, returns an error if the file
exists

Syntax
To open a file for reading it is enough to specify the name of the file:
f = open("demofile.txt")

Open a File on the Server


Assume we have the following file, located in the same folder as
Python:
demofile.txt
Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!
To open the file, use the built-in open() function.
Example
f = open("demofile.txt", "r")
print(f.read())

f the file is located in a different location, you will have to specify


the file path, like this:
Example
Open a file on a different location:
f = open("D:\\myfiles\welcome.txt", "r")
print(f.read())
Read Only Parts of the File
By default the read() method returns the whole text, but you can
also specify how many characters you want to return:
Example
Return the 5 first characters of the file:
f = open("demofile.txt", "r")
print(f.read(5))

Read Lines
You can return one line by using the readline() method:
Example
Read one line of the file:
f = open("demofile.txt", "r")
print(f.readline())

By calling readline() two times, you can read the two first lines:
Example
Read two lines of the file:
f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())

By looping through the lines of the file, you can read the whole file,
line by line:
Example
Loop through the file line by line:
f = open("demofile.txt", "r")
for x in f:
print(x)

Close Files
It is a good practice to always close the file when you are done with
it.
Example
Close the file when you are finish with it:
f = open("demofile.txt", "r")
print(f.readline())
f.close()
Write to an Existing File
To write to an existing file, you must add a parameter to
the open() function:
"a" - Append - will append to the end of the file
"w" - Write - will overwrite any existing content
Example
Open the file "demofile2.txt" and append content to the file:
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

#open and read the file after the appending:


f = open("demofile2.txt", "r")
print(f.read())

Example
Open the file "demofile3.txt" and overwrite the content:
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()

#open and read the file after the overwriting:


f = open("demofile3.txt", "r")
print(f.read())

Create a New File


To create a new file in Python, use the open() method, with one of
the following parameters:
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist
Example
Create a file called "myfile.txt":
f = open("myfile.txt", "x")
Result: a new empty file is created!
Example
Create a new file if it does not exist:
f = open("myfile.txt", "w")

Delete a File
To delete a file, you must import the OS module, and run
its os.remove() function:
Example
Remove the file "demofile.txt":
import os
os.remove("demofile.txt")

Renaming the file


.The os module provides the functions like renaming, deleting, etc.
Syntax:
1. rename(current-name, new-name)
The first argument is the current file name and the second
argument is the modified name. We can change the file name
bypassing these two arguments.
Example 1:
import os

# rename file3.txt to file4.txt


os.rename("file3.txt", "file4.txt")
Output:
The above code renamed current file3.txt to file4.txt

The with statement


The with statement was introduced in python 2.5. The with
statement is useful in the case of manipulating the files. It is used in
the scenario where a pair of statements is to be executed with a
block of code in between.
The syntax to open a file using with the statement is given below.
1. with open(<file name>, <access mode>) as <file-pointer>:
2. #statement suite
The advantage of using with statement is that it provides the
guarantee to close the file regardless of how the nested block exits.
It is always suggestible to use the with statement in the case of
files because, if the break, return, or exception occurs in the nested
block of code then it automatically closes the file, we don't need to
write the close() function. It doesn't let the file to corrupt.
Consider the following example.

Example

 wwith open("file.txt",'w') as f:
content = f.write("Yusuf");
f.close()

with open("file.txt",'a') as f:
f.write("Tushar")
f.close()

with open("file.txt",'r') as f:
print(f.read())
Handling Python FileNotFoundError
If you have received the error “FileNotFoundError: [WinError 2] The
system cannot find the file specified”, it means that there is no file
present at the path you specified.

Solution – Python FileNotFoundError


There are two ways in which you can handle FileNotFoundError.
 Use try-except and handle FileNotFoundError
 Check if file is present, and proceed with the file operation accordingly.

import os

try:
os.remove('file3.txt')
print('The file is removed.')
except FileNotFoundError:
print('The file is not present.')

import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")

You might also like