1.0.imp Python Notes-yogesh
1.0.imp Python Notes-yogesh
INTRODUCTION:
Python Comments:
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');
Python Indentation
if 2>1:
print("2 is the bigger person");
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
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
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])
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())
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())
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())
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.
16. upper()
Python String upper() method converts all lowercase characters in a string into uppercase
characters and returns it.
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.
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.
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'
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))
• Arithmetic Operators
• Logical Operators
• Assignment Operators
• Membership Operators
• Identity Operators
+ Addition 10 + 20 = 30
- Subtraction 20 – 10 = 10
* Multiplication 10 * 20 = 200
/ Division 20 / 10 = 2
% Modulus 22 % 10 = 2
** Exponent 4**3 = 16
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
= Assignment Operator a = 10
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
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.
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])
print(my_list[:])
Run Code
Output
[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.
print(my_list[:2])
Run Code
Output
[1, 2]
print(my_list[2:4])
Run Code
Output
[3, 4]
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]
print(my_list[1:4:2])
Run Code
Output
[2, 4]
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.
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)
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 !']
Output:
Original List:
['Geeks', 4, 'geeks !']
Sliced Lists:
['geeks !', 4, 'Geeks']
['geeks !']
['geeks !']
Example 3:
Python3
# Initialize list
List = [-999, 'G4G', 1706256, '^_^', 3.1496]
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, '^_^']
# 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.
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:
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)
Output
Output
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: []
Output
List: []
3. copy()
Definition and Usage
The copy() method returns a copy of the specified list.
Syntax
list.copy()
Output
If you modify the new_list in the above example, my_list will not be modified.
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
new_list = old_list
new_list.append('a')
print('New List:', new_list)
print('Old List:', old_list)
Output
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
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
Output
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
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']
Note: The index() method only returns the first occurrence of the matching element
Output
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()
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']
Output
Output
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]
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
If the index passed to the method is not in range, it throws IndexError: pop index
Output
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
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)
Output
Output
10. reverse()
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]
Output
Output
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
# 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))
Output:
Traceback (most recent call last):
File "e0eaddff843a8695575daec34506f126.py", line 3, in
tuple1[0]=4
TypeError: 'tuple' object does not support item assignment
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
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))
>>> max(tup)
890
max(): gives the sum of the elements present in the tuple as an output.
For example,
COPY CODE
>>> 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'>
With the len() function, you can returns the length of the tuple:
a = (1,2,3,4,5)
print(len(a))
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,..}
Sets are mutable. However, since they are unordered, indexing has no meaning.
Output
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()
numbers = {2, 3, 4, 5}
# discards 3 from the set
numbers.discard(3)
print('Set after discard:', numbers)
Run Code
The union of two sets A and B include all the elements of set A and B and not include
duplicates.
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
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
We use the - operator or the difference() method to perform the difference between two
Output
The symmetric difference between two sets A and B includes all elements
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}
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])
Output
Frozenset operations
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
Create a Dictionary
# Create a dictionary to store employee record
D = {'name': 'Bob',
'age': 25,
'job': 'Dev',
'city': 'New York',
'email': 'bob@web.com'}
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}
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'))
D1.update(D2)
print(D1)
# Prints {'name': 'Bob', 'age': 30, 'job': 'Dev',
# 'city': 'New York', 'email': 'bob@web.com'}
for x in D:
print(D[x])
# Prints Bob 25 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
print(len(D))
# Prints 3
Python Dictionary Methods
Method Description
fromkeys() Creates a new dictionary with the specified keys and values
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
# 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())
Method Description
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]
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])
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”)
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”)
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")
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
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")
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")
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
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
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
Output: 1
Enter the year: 2020
Enter the month: 4
Leap Year
There are 30 days in this month
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
count = 0
while (count < 3):
count = count + 1
print("Hello Geek")
Output
Hello Geek
Hello Geek
Hello Geek
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
count = 0
while (count == 0):
print("Hello Geek")
age = 32
i=1
n=5
while i <= n:
print(i)
i=i+1
Output
1
2
3
4
5
Output
Enter a number: 12
Enter a number: 4
Enter a number: -5
Enter a number: 0
total = 11
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)
Syntax of range()
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.
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]
for i in digits:
print(i)
else:
print("No items left.")
Run Code
Output
0
1
5
No items left.
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
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()
for x in adj:
for y in fruits:
print(x, y)
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']
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
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
sum_positives = 0
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
Standard library functions - These are built-in functions in Python that are available
to use.
requirements
These library functions are defined inside the module. And, to use them we must
include the module inside our program.
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!')
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:
# 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)
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')
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;
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 myFun(a):
for i in a:
print(i)
def myFun(*argv):
for arg in argv:
print(arg)
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:
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
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
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.
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()
This is because we can only access the global variable but cannot modify it from inside the
function.
We use the global keyword to read and write a global variable inside a function.
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
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
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 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 Module1 as a
a.add(20,10)
a.div(20,10)
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))
# 1 * 2 * 3 * 4 = 24
print(math.factorial(4))
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)
# Approach 2
from india import *
from bharat import *
indian()
bharatiya()
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.
Syntax:
import package_name.module_name
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()
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")
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
class Myclass:
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()
@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.
mc1 = Myclass1() # mc1 is instance variable which will store Myclass1 Object
mc1.m1() # We are printing Instance Method
mc1 = Myclass1()
mc1.m1()
Myclass1().m2("Anil")
mc1 = Myclass1()
mc1.m1()
Myclass1().m2()
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.
def mul(self):
print(self.a*self.b)
mc2 = Myclass2()
mc2.add()
mc2.mul()
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)
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()
class Myclass5:
def add(self,x,y):
print(x+y)
def display(self):
print("Hello")
mc5.add(1000,2000) # Named Object mc5 accessing the add method from class
mc5.display() # Named Object mc5 accessing the display method from class
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.
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()
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()
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()
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.
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)
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]))
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.
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()
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.
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!"
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
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
This is because the eat() method of the Dog subclass overrides the same method of
For example,
class Animal:
name = ""
def eat(self):
print("I can eat")
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
to call the eat() method of the Animal superclass from the Dog subclass.
So, when we call the eat() method using the labrador object
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
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.
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
Encapsulation in Python
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)
Output:
Name: Jessa Salary: 8000
Jessa is working on NLP
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)
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
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
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
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()
Syntax
To open a file for reading it is enough to specify the name of the file:
f = open("demofile.txt")
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()
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()
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")
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.
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")