Python Notes
Python Notes
com
Programming
Code
Syntax
Similar to Grammar rules in English, Hindi, each programming language has a unique set of rules. These rules are
called the Syntax of a Programming Language.
Why Python
Python is an easy to learn, powerful programming language. With Python, it is possible to create programs with
minimal amount of code. Look at the code in Java and Python used for printing the message "Hello World"
1
www.spharktechnologies.com
Java:
JAVA
1 class Main {
2 public static void main(String[] args) {
3 System.out.println("Hello World");
4 }
5 }
Python:
PYTHON
1 print("Hello World")
Applications of Python
Big Data
Cyber Security
Game Development
Career Opportunities
DevOps Engineer
Software Developer
Data Analyst
Data Scientist
AI Scientist, etc.
Here is a simple Python code that you can use to display the message "Hello World"
Code
PYTHON
1 print("Hello World!")
Output
3
www.spharktechnologies.com
Hello World!
Possible Mistakes
Possible mistakes you may make while writing Python code to display the message "Hello World"
1 prnt("Hello World!")
1 Print("Hello World!")
Missing quotes
PYTHON
1 print(Hello World!)
4
www.spharktechnologies.com
Missing parentheses
PYTHON
1 print("Hello World!"
Code
PYTHON
1 print(2 + 5)
Output
If we want to print the exact message "2 + 5", then we add the quotes.
Code
5
www.spharktechnologies.com
PYTHON
1 print("2 + 5")
Output
2 + 5
Addition
Addition is denoted by
Code
PYTHON
1 print(2 + 5)
2 print(1 + 1.5)
Output
6
www.spharktechnologies.com
7
2.5
Subtraction
Subtraction is denoted by
Code
PYTHON
1 print(5 - 2)
Output
Multiplication
Multiplication is denoted by
* sign.
7
www.spharktechnologies.com
Code
PYTHON
1 print(2 * 5)
2 print(5 * 0.5)
Output
10
2.5
Division
Division is denoted by
/ sign.
8
www.spharktechnologies.com
Values
Data Type
In programming languages, every value or data has an associated type to it known as data type.
Some commonly used data types
String
Integer
Float
Boolean
9
www.spharktechnologies.com
This data type determines how the value or data can be used in the program. For example, mathematical operations
can be done on Integer and Float types of data.
String
Capital Letters ( A – Z )
Small Letters ( a – z )
Digits ( 0 – 9 )
Space
Some Examples
"Hello World!"
"some@example.com"
"1234"
Integer
All whole numbers (positive, negative and zero) without any fractional part come under Integers.
Examples
Float
10
www.spharktechnologies.com
Boolean
In a general sense, anything that can take one of two possible values is considered a Boolean. Examples include the
data that can take values like
True or False
Yes or No
0 or 1
On or Off , etc.
True and False are considered as Boolean values. Notice that both start with a capital letter.
10 to a variable age
PYTHON
1 age = 10
12
www.spharktechnologies.com
Sequence of Instructions
Program
A program is a sequence of instructions given to a computer.
Defining a Variable
A variable gets created when you assign a value to it for the first time.
Code
PYTHON
1 age = 10
Code
PYTHON
1 age = 10
2 print(age)
Output
13
www.spharktechnologies.com
10
Code
PYTHON
1 age = 10
2 print("age")
Output
age
Variable name enclosed in quotes will print variable rather than the value in it.
If you intend to print value, do not enclose the variable in quotes.
Order of Instructions
14
www.spharktechnologies.com
Code
PYTHON
1 print(age)
2 age = 10
Output
Variable
Spacing in Python
Code
PYTHON
1 a = 10 * 5
2 b = 5 * 0.5
3 b = a + b
15
www.spharktechnologies.com
Output
Variable Assignment
Code
PYTHON
1 a = 1
2 print(a)
3 a = 2
4 print(a)
Output
1
2
16
www.spharktechnologies.com
Code
PYTHON
1 a = 2
2 print(a)
3 a = a + 1
4 print(a)
Output
2
3
Code
PYTHON
1 a = 1
2 b = 2
3 a = b + 1
4 print(a)
5 print(b)
Output
17
www.spharktechnologies.com
3
2
Expression
Examples
a*b
a+2
5*2+3*4
BODMAS
The standard order of evaluating an expression
Brackets (B)
Orders (O)
Division (D)
Multiplication (M)
Addition (A)
Subtraction (S)
18
www.spharktechnologies.com
input() allows flexibility to take the input from the user. Reads a line of input as a string.
Code
PYTHON
1 username = input()
2 print(username)
Input
Ajay
Output
Ajay
String Concatenation
Code
PYTHON
Output
Hello World
19
www.spharktechnologies.com
Concatenation Errors
Code
PYTHON
1 a = "*" + 10
2 print(a)
Output
String Repetition
Code
PYTHON
1 a = "*" * 10
2 print(a)
Output
**********
Code
PYTHON
1 s = "Python"
2 s = ("* " * 3) + s + (" *" * 3)
3 print(s)
Output
20
www.spharktechnologies.com
* * * Python * * *
Length of String
Code
PYTHON
1 username = input()
2 length = len(username)
3 print(length)
Input
Ravi
Output
String Indexing
We can access an individual character in a string using their positions (which start from 0) .
These positions are also called as index.
Code
PYTHON
1 username = "Ravi"
2 first_letter = username[0]
3 print(first_letter)
Output
21
www.spharktechnologies.com
IndexError
Code
PYTHON
1 username = "Ravi"
2 print(username[4])
Output
Submit Feedback
22
www.spharktechnologies.com
Type Conversion
String Slicing
Code
PYTHON
1 variable_name[start_index:end_index]
Code
PYTHON
Output
Ravi
Slicing to End
If end index is not specified, slicing stops at the end of the string.
Code
PYTHON
Output
23
www.spharktechnologies.com
Ravi
Code
PYTHON
Output
Hi
type()
Code
PYTHON
1 print(type(10))
2 print(type(4.2))
3 print(type("Hi"))
Output
24
www.spharktechnologies.com
<class 'int'>
<class 'float'>
<class 'str'>
Type Conversion
Converting the value of one data type to another data type is called Type Conversion or Type Casting.
We can convert
String to Integer
Integer to Float
String to Integer
Code
PYTHON
1 a = "5"
2 a = int(a)
3 print(type(a))
4 print(a)
Output
<class 'int'>
5
Code
PYTHON
1 a = "Five"
2 a = int(a)
3 print(type(a))
Output
25
www.spharktechnologies.com
ValueError:
invalid literal for int() with base 10: 'Five'
Code
PYTHON
1 a = "5.0"
2 a = int(a)
3 print(type(a))
Output
Code
PYTHON
1 a = input()
2 a = int(a)
3 b = input()
4 b = int(b)
5 result = a + b
6 print(result)
Input
2
3
Output
26
www.spharktechnologies.com
Integer to String
Code
PYTHON
1 a = input()
2 a = int(a)
3 b = input()
4 b = int(b)
5 result = a + b
6 print("Sum: " + str(result))
Input
2
3
Output
Sum: 5
Summary
27
www.spharktechnologies.com
Relational Operators
Relational Operators are used to compare values.
Gives
Operator Name
== Is equal to
!= Is not equal to
Code
PYTHON
Output
True
True
28
www.spharktechnologies.com
Possible Mistakes
Mistake - 1
Code
PYTHON
1 print(3 = 3)
Output
Mistake - 2
Code
PYTHON
1 print(2 < = 3)
Output
Comparing Numbers
29
www.spharktechnologies.com
Code
PYTHON
1 print(2 <= 3)
2 print(2.53 >= 2.55)
Output
True
False
Code
PYTHON
1 print(12 == 12.0)
2 print(12 == 12.1)
Output
True
False
Comparing Strings
Code
PYTHON
1 print("ABC" == "ABC")
2 print("CBA" != "ABC")
30
www.spharktechnologies.com
Output
True
True
Case Sensitive
Code
PYTHON
1 print("ABC" == "abc")
Output
False
X (Capital letter) and x (small letter) are not the same in Python.
1 print(True == "True")
2 print(123 == "123")
3 print(1.1 == "1.1")
Output
31
www.spharktechnologies.com
False
False
False
Submit Feedback
32
www.spharktechnologies.com
Logical Operators
The logical operators are used to perform logical operations on Boolean values.
Gives
and
or
not
Gives
Code
PYTHON
Output
True
Code
PYTHON
Output
True
Logical OR Operator
Gives
Code
PYTHON
1 print(False or False)
Output
False
Examples of Logical OR
Code
34
www.spharktechnologies.com
PYTHON
(2 < 3) or (2 < 1)
True or (2 < 1)
True or False
Output
True
Code
PYTHON
1 print(not(False))
Output
True
35
www.spharktechnologies.com
Code
PYTHON
not(2 < 3)
not(True)
False
Output
False
Summary
1. Logical AND Operator gives True if all the booleans are true.
2. Logical OR Operator gives True if any of the booleans are true.
3. Logical NOT Operator gives the opposite value
36
www.spharktechnologies.com
Conditional Statements
Block of Code
Condition
True or False
Examples
i. 2 < 3
ii. a == b
iii. True
Conditional Statement
Conditional Statement allows you to execute a block of code only when a specific condition is
True
37
www.spharktechnologies.com
Conditional Block
Indentation
Possible Mistakes
Each statement inside a conditional block should have the same indentation (spacing).
38
www.spharktechnologies.com
Wrong Code
PYTHON
1 if True:
2 print("If Block")
3 print("Inside If")
Output
Correct Code
PYTHON
1 if True:
2 print("If Block")
3 print("Inside If")
If - Else Syntax
When If - Else conditional statement is used, Else block of code executes if the condition is
False
Using If-Else
39
www.spharktechnologies.com
Code
PYTHON
1 a = int(input())
2 if a > 0:
3 print("Positive")
4 else:
5 print("Not Positive")
6 print("End")
Input
Output
Positive
End
Else can only be used along with if condition. It is written below if conditional block
Code
PYTHON
1 if False:
2 print("If Block")
3 print("After If")
4 else:
5 print("Else Block")
6 print("After Else")
Output
40
www.spharktechnologies.com
Warning
41
www.spharktechnologies.com
Cheat Sheet
Modulus
a%b
Code
PYTHON
1 print(6 % 3)
Output
Exponent
**
a ** b
Code
PYTHON
1 print(2 ** 3)
42
www.spharktechnologies.com
Output
You can use the exponent operator to calculate the square root of a number by keeping the
exponent as
0.5
Code
PYTHON
1 print(16 ** 0.5)
Output
4.0
Submit Feedback
43
www.spharktechnologies.com
Nested Conditions
The conditional block inside another if/else conditional block is called as nested conditional block.
In the below example, Block 2 is nested conditional block and condition B is called nested conditional
statement.
Code
PYTHON
1 matches_won = int(input())
2 goals = int(input())
3 if matches_won > 8:
4 if goals > 20:
5 print("Hurray")
6 print("Winner")
Input
10
22
44
www.spharktechnologies.com
Output
Hurray
Winner
Input
10
18
Output
Winner
45
www.spharktechnologies.com
Code
PYTHON
1 a = 2
2 b = 3
3 c = 1
4 is_a_greatest = (a > b) and (a > c)
5 if is_a_greatest:
6 print(a)
7 else:
8 is_b_greatest = (b > c)
9 if is_b_greatest:
10 print(b)
Expand
Output
Elif Statement
46
www.spharktechnologies.com
Use the elif statement to have multiple conditional statements between if and else.
47
www.spharktechnologies.com
Python will execute the elif block whose expression evaluates to true.
If multiple
elif conditions are true, then only the first elif block which is True will be executed.
48
www.spharktechnologies.com
if - elif statements.
Code
49
www.spharktechnologies.com
PYTHON
1 number = 5
2 is_divisible_by_10 = (number % 10 == 0)
3 is_divisible_by_5 = (number % 5 == 0)
4 if is_divisible_by_10:
5 print("Divisible by 10")
6 elif is_divisible_by_5:
7 print("Divisible by 5")
8 else:
9 print("Not Divisible by 10 or 5")
Output
Divisible by 5
Possible Mistake
else statement.
50
www.spharktechnologies.com
Loops
So far we have seen that Python executes code in a sequence and each block of code is executed once.
Loops allow us to execute a block of code several times.
While Loop
True .
The following code snippet prints the next three consecutive numbers after a given number.
Code
PYTHON
1 a = int(input())
2 counter = 0
3 while counter < 3:
4 a = a + 1
5 print(a)
6 counter = counter + 1
51
www.spharktechnologies.com
Input
Output
5
6
7
Possible Mistakes
1. Missing Initialization
Code
PYTHON
1 a = int(input())
2 while counter < 3:
3 a = a + 1
4 print(a)
5 counter = counter + 1
6 print("End")
Input
Output
52
www.spharktechnologies.com
Code
PYTHON
1 a = int(input())
2 counter = 0
3 condition = (counter < 3)
4 while condition:
5 a = a + 1
6 print(a)
7 counter = counter + 1
Input
10
Output
True .
Code
53
www.spharktechnologies.com
PYTHON
1 a = int(input())
2 counter = 0
3 while counter < 3:
4 a = a + 1
5 print(a)
6 print("End")
Input
10
Output
Infinite Loop
54
www.spharktechnologies.com
Cheat Sheet
For Loop
Examples of sequences:
For Syntax
Code
55
www.spharktechnologies.com
PYTHON
1 word = "Python"
2 for each_char in word:
3 print(each_char)
Output
P
y
t
h
o
n
Range
Code
PYTHON
1 for number in range(3):
2 i t( b ) 56
www.spharktechnologies.com
2 print(number)
Output
0
1
2
start
Syntax: range(start, end) Stops before end (end is not included).
Code
PYTHON
Output
5
57
www.spharktechnologies.com
6
7
Submit Feedback
58
www.spharktechnologies.com
59
www.spharktechnologies.com
In this cheat sheet, let's see how to print the Hollow right-angled triangle pattern
*
* *
* *
* *
* *
* *
* * * * * * *
Now, let's see how to print the 7x7 hollow right-angled triangle pattern.
Logical approach:
60
www.spharktechnologies.com
Note
In the above image, each empty box contains 2 spaces (double space ' '), and each star is followed by a
space ('* ').
61
www.spharktechnologies.com
The above image is the 7x7 pattern of the hollow right-angled triangle
The second row has 5 spaces and the first star and the second star.
The third, fourth, fifth, and sixth rows have decreasing spaces, followed by the first star with increasing hollow
spaces, then the second star.
* * Third line 4 Double spaces 1st star-set('* ') 1 Hollow spaces 2nd star
* * Fourth line 3 Double spaces 1st star-set('* ') 2 Hollow spaces 2nd star
* * Fifth line 2 Double spaces 1st star-set('* ') 3 Hollow spaces 2nd star
* * Sixth line 1 Double spaces 1st star-set('* ') 4 Hollow spaces 2nd star
62
www.spharktechnologies.com
Now, let's see how to print the above pattern using a python program.
Code:
We can use the For loop and if-elif-else statement to execute the particular part.
PYTHON
1 N = 7
2
3 for i in range(0, N):
4
5 if i == 0: # part- 1 logic
6
7 print(' '* (N-1) + '*')
8
9 elif i == N - 1: # part- 3 logic
10
11 print('* ' * N)
12
13 else: # part- 2 logic
14 left_spaces = ' ' * (N -i-1)
15
16 hollow_spaces = (' ' * ( i - 1))
17
18 i t(l ft '* ' h ll '*') 63
www.spharktechnologies.com
Collapse
Now let's see the explanation of the for loop execution, step by step:
i=0
The first row has 6 spaces followed by one star. In order to get 6 no. of spaces, we must subtract 1 from the
N value.
Output is
1 *
i=1
In the second row, we have 5 spaces followed by the first star and hallow spaces followed by the second star. In
order to get 5 no.of spaces, we must subtract 1 and
i value from the N value.
64
www.spharktechnologies.com
Output is
*
* *
i=2
In the third row, we have 4 spaces followed by the first star and hallow spaces followed by the second star. In
order to get 4 no.of spaces, we must subtract 1 and
i value from the N value.
Output is
65
www.spharktechnologies.com
*
* *
* *
i=3
In the fourth row, we have 3 spaces followed by the first star and hallow spaces followed by the second star. In
order to get 3 no.of spaces, we must subtract 1 and
i value from the N value.
Output is
*
* *
* *
* *
i=4
In the fifth row, we have 2 spaces followed by the first star and hallow spaces followed by the second star. In
66
www.spharktechnologies.com
Output is
*
* *
* *
* *
* *
i=5
In the sixth row, we have 1 space followed by the first star and hallow spaces followed by the second star. In
order to get 1 space, we must subtract 1 and
i value from the N value.
67
www.spharktechnologies.com
Output is
*
* *
* *
* *
* *
* *
i=6
Output is
*
* *
* *
* *
* *
* * 68
www.spharktechnologies.com
* *
* * * * * * *
Submit Feedback
69
www.spharktechnologies.com
Cheat Sheet
Extended Slicing
Syntax:
variable[start_index:end_index:step]
Code
PYTHON
1 a = "Waterfall"
2 part = a[1:6:3]
3 print(part)
Output
ar
70
www.spharktechnologies.com
Methods
String Methods
isdigit()
strip()
lower()
upper()
startswith()
endswith()
Isdigit
Syntax:
str_var.isdigit()
Gives
Code
PYTHON
1 is_digit = "4748".isdigit()
2 print(is_digit)
Output
True
Strip
71
www.spharktechnologies.com
Syntax:
str_var.strip()
Code
PYTHON
Output
9876543210
Syntax:
str_var.strip(chars)
Code
PYTHON
1 name = "Ravi."
2 name = name.strip(".")
3 print(name)
Output
Ravi
72
www.spharktechnologies.com
Removes all spaces, comma(,) and full stop(.) that lead or trail the string.
Code
PYTHON
Output
ravi
Replace
Syntax:
str_var.replace(old,new)
Gives a new string after replacing all the occurrences of the old substring with the new substring.
Code
PYTHON
Output
Startswith
73
www.spharktechnologies.com
Syntax:
str_var.startswith(value)
Gives
True if the string starts with the specified value. Otherwise, False
Code
PYTHON
1 url = "https://onthegomodel.com"
2 is_secure_url = url.startswith("https://")
3 print(is_secure_url)
Output
True
Endswith
Syntax:
str_var.endswith(value)
Gives
True if the string ends with the specified value. Otherwise, False
Code
PYTHON
1 gmail_id = "rahul123@gmail.com"
2 is_gmail = gmail_id.endswith("@gmail.com")
3 print(is_gmail)
Output
True
74
www.spharktechnologies.com
True
Upper
Syntax:
str_var.upper()
Gives a new string by converting each character of the given string to uppercase.
Code
PYTHON
1 name = "ravi"
2 print(name.upper())
Output
RAVI
Lower
Syntax:
str_var.lower()
Gives a new string by converting each character of the given string to lowercase.
Code
PYTHON
1 name = "RAVI"
2 print(name.lower())
Output
ravi
75
www.spharktechnologies.com
ravi
Submit Feedback
76
www.spharktechnologies.com
Concepts
Classification Methods
isalpha()
isdecimal()
islower()
isupper()
isalnum()
capitalize()
title()
swapcase()
count()
index()
rindex()
find()
rfind()
1. Classification Methods
77
www.spharktechnologies.com
1.1 Isalpha
Syntax:
str_var.isalpha()
Gives
Example 1:
Code
PYTHON
1 is_alpha = "Rahul".isalpha()
2 print(is_alpha)
Output
True
Example 2:
Code
PYTHON
1 is_alpha = "Rahul@123".isalpha()
2 print(is_alpha)
Output
78
www.spharktechnologies.com
False
1.2 Isdecimal
Syntax:
str_var.isdecimal()
Gives
Example 1:
Code
PYTHON
1 is_decimal = "9876543210".isdecimal()
2 print(is_decimal)
Output
True
Example 2:
Code
PYTHON
1 is_decimal = "123.R".isdecimal()
2 print(is_decimal)
Output
79
www.spharktechnologies.com
False
1.3 Islower
Syntax:
str_var.islower()
Gives
Example 1:
Code
PYTHON
Output
True
Example 2:
Code
PYTHON
Output
False
80
www.spharktechnologies.com
1.4 Isupper
Syntax:
str_var.isupper()
Gives
Example 1:
Code
PYTHON
Output
True
Example 2:
Code
PYTHON
Output
False
1.5 Isalnum
81
www.spharktechnologies.com
Syntax:
str_var.isalnum()
Gives
Example 1:
Code
PYTHON
1 is_alnum = "Rahul123".isalnum()
2 print(is_alnum)
Output
True
Example 2:
Code
PYTHON
1 is_alnum = "Rahul".isalnum()
2 print(is_alnum)
Output
True
Example 3:
Code
PYTHON
82
www.spharktechnologies.com
PYTHON
1 is_alnum = "Rahul@123".isalnum()
2 print(is_alnum)
Output
False
2.1 Capitalize
Syntax:
str_var.capitalize()
Gives a new string after converting the first letter in the string to
uppercase and all other letters to lowercase.
Code
PYTHON
Output
83
www.spharktechnologies.com
2.2 Title
Syntax:
str_var.title()
Gives a new string after converting the first letter of every word to
uppercase.
Example 1:
Code
PYTHON
Output
Example 2:
Code
PYTHON
Output
84
www.spharktechnologies.com
2.3 Swapcase
Syntax:
str_var.swapcase()
Code
PYTHON
Output
My Name is Ravi
3.1 Count
Syntax:
85
www.spharktechnologies.com
Here, the
The
If
Example 1:
Code
PYTHON
Output
Example 2:
Code
PYTHON
Output
86
www.spharktechnologies.com
3.2 Index
Syntax:
Here, the
The
The
Example 1:
Code
PYTHON
Output
15
87
www.spharktechnologies.com
Example 2:
Code
PYTHON
Output
Example 3:
Code
PYTHON
Output
3.3 rIndex
Syntax:
Here, the
88
www.spharktechnologies.com
The
The
Example 1:
Code
PYTHON
Output
33
Example 2:
Code
PYTHON
Output
89
www.spharktechnologies.com
Example 3:
Code
PYTHON
Output
3.4 Find
Syntax:
Here, the
The
find() method gives the index at the first occurrence of the specified
string str .
The
90
www.spharktechnologies.com
Example 1:
Code
PYTHON
Output
15
Example 2:
Code
PYTHON
Output
Example 3:
Code
PYTHON
2 word_index = text.find("ha")
3 print(word_index)
Output
-1
3.5 rFind
Syntax:
Here, the
The
The
Example 1:
Code
PYTHON
92
www.spharktechnologies.com
Output
33
Example 2:
Code
PYTHON
Output
Example 3:
Code
PYTHON
Output
93
www.spharktechnologies.com
-1
Submit Feedback
94
www.spharktechnologies.com
Nested Loops
An inner loop within the repeating block of an outer loop is called Nested Loop.
The Inner Loop will be executed one time for each iteration of the Outer Loop.
Code
PYTHON
1 for i in range(2):
2 print("Outer: " + str(i))
3 for j in range(2):
4 print(" Inner: " + str(j))
Output
Outer: 0
Inner: 0
Inner: 1
Outer: 1
Inner: 0
Inner: 1
95
www.spharktechnologies.com
The one highlighted in the blue dotted line is the repeating block of the inner loop.
Code
PYTHON
1 for i in range(2):
2 print("Outer: " + str(i))
3 for j in range(2):
4 print(" Inner: " + str(j))
5 print("END")
In the above example, the below line is the repeating block of the nested loop.
Code
PYTHON
Output
Outer: 0
Inner: 0
Inner: 1
Outer: 1
Inner: 0
96
www.spharktechnologies.com
Inner: 1
END
97
www.spharktechnologies.com
Examples
if-elif-else
while, for
break, continue
Break
Using Break
98
www.spharktechnologies.com
i value equals to 3 the break statement gets executed and stops the
execution of the loop further.
Code
PYTHON
1 for i in range(5):
2 if i == 3:
3 break
4 print(i)
5 print("END")
Output
0
1
2
END
99
www.spharktechnologies.com
Continue
Continue makes the program skip the remaining statements in the current iteration
and begin the next iteration.
Using Continue
Generally, continue is used to skip the remaining statements in the current iteration
when a condition is satisfied.
100
www.spharktechnologies.com
i value equals to 3 the next statements in the loop body are skipped.
Code
PYTHON
1 for i in range(5):
2 if i == 3:
3 continue
4 print(i)
5 print("END")
Output
0
1
2
4
END
Pass
Generally used when we have to test the code before writing the complete code.
101
www.spharktechnologies.com
Empty Loops
We can use pass statements to test code written so far, before writing loop logic.
Submit Feedback
102
www.spharktechnologies.com
Comparing Strings
Computer internally stores characters as numbers.
Ord
ord()
Code
PYTHON
1 unicode_value = ord("A")
2 print(unicode_value)
Output
65
chr
103
www.spharktechnologies.com
To find the character with the given Unicode value, we use the
chr()
Code
PYTHON
1 char = chr(75)
2 print(char)
Output
Unicode Ranges
Printing Characters
A to Z
Code
PYTHON
104
www.spharktechnologies.com
Output
A
B
C
D
E
F
G
H
I
J
Expand
Comparing Strings
Code
PYTHON
Output
True
As unicode value of
A is 65 and B is 66, which internally compares 65 < 66 . So the output should be True
Code
105
www.spharktechnologies.com
PYTHON
Output
False
Code
PYTHON
Output
True
Best Practices
Capital Letters ( A – Z )
Small Letters ( a – z )
Digits ( 0 – 9 )
Underscore(_)
Examples:
age, total_bill
Blanks ( )
Commas ( , )
Special Characters
( ~ ! @ # $ % ^ . ?, etc. )
Capital Letters ( A – Z )
Small Letters ( a – z )
Underscore( _ )
int
str
print etc.,
Keywords
Words which are reserved for special meaning
Code
PYTHON
1 help("keywords")
Output
None
Collapse
Case Styles
108
www.spharktechnologies.com
Cheat Sheet
Data Structures
Data Structures allow us to store and organize data efficiently.
This will allow us to easily access and perform operations on the data.
List
Tuple
Set
Dictionary
List
Creating a List
Code
PYTHON
1 a = 2
2 list_a = [5, "Six", a, 8.2]
3 print(type(list a))
109
www.spharktechnologies.com
p ( yp ( _ ))
4 print(list_a)
Output
<class 'list'>
[5, 'Six', 2, 8.2]
Code
PYTHON
1 a = 2
2 list_a = [5, "Six", a, 8.2]
3 list_b = [1, list_a]
4 print(list_b)
Output
Length of a List
Code
PYTHON
1 a = 2
2 list_a = [5, "Six", a, 8.2]
3 print(len(list_a))
Output
110
www.spharktechnologies.com
Code
PYTHON
1 a = 2
2 list_a = [5, "Six", a, 8.2]
3 print(list_a[1])
Output
Six
Code
PYTHON
1 a = 2
2 list_a = [5, "Six", a, 8.2]
3 for item in list_a:
4 print(item)
Output
5
Six
2
8.2
111
www.spharktechnologies.com
List Concatenation
Similar to strings,
Code
PYTHON
1 list_a = [1, 2, 3]
2 list_b = ["a", "b", "c"]
3 list_c = list_a + list_b
4 print(list_c)
Output
Code
PYTHON
1 list_a = []
2 print(list_a)
3 for i in range(1,4):
4 list_a += [i]
5 print(list_a)
Output
[]
[1, 2, 3]
Repetition
Code
PYTHON
1 list_a = [1, 2]
2 list_b = list_a * 3
3 print(list_b)
Output
[1, 2, 1, 2, 1, 2]
List Slicing
Code
PYTHON
Output
[5, 'Six']
113
www.spharktechnologies.com
Extended Slicing
Similar to string extended slicing, we can extract alternate items using step.
Code
PYTHON
Output
['R', 'O']
Converting to List
Code
PYTHON
1 color = "Red"
2 list_a = list(color)
3 print(list_a)
Output
Code
PYTHON
114
www.spharktechnologies.com
PYTHON
1 list_a = list(range(4))
2 print(list_a)
Output
[0, 1, 2, 3]
Code
PYTHON
1 list_a = [1, 2, 3, 5]
2 print(list_a)
3 list_a[3] = 4
4 print(list_a)
Output
[1, 2, 3, 5]
[1, 2, 3, 4]
Code
PYTHON
115
www.spharktechnologies.com
PYTHON
Output
Submit Feedback
116
www.spharktechnologies.com
Cheat Sheet
Examples
"A"
1.25
[1,2,3]
Identity of an Object
This unique id can be different for each time you run the program.
Every object that you use in a Python Program will be stored in Computer Memory.
The unique id will be related to the location where the object is stored in the Computer Memory.
117
www.spharktechnologies.com
Finding Id
Code
PYTHON
1 print(id("Hello"))
Output
140589419285168
Id of Lists
PYTHON
1 list_a = [1, 2, 3]
2 list_b = [1, 2, 3]
3 print(id(list_a))
4 print(id(list_b))
Output
139637858236800
139637857505984
Modifying Lists
Modifying Lists - 1
Code
PYTHON
1 list_a = [1, 2, 3]
2 list_b = list_a
3 print(id(list_a))
4 print(id(list_b))
Output
140334087715264
140334087715264
Modifying Lists - 2
119
www.spharktechnologies.com
Code
PYTHON
1 list_a = [1, 2, 3, 5]
2 list_b = list_a
3 list_b[3] = 4
4 print("list a : " + str(list_a))
5 print("list b : " + str(list_b))
Output
list a : [1, 2, 3, 4]
list b : [1, 2, 3, 4]
Modifying Lists - 3
120
www.spharktechnologies.com
Code
PYTHON
1 list_a = [1, 2]
2 list_b = list_a
3 list_a = [6, 7]
4 print("list a : " + str(list_a))
5 print("list b : " + str(list_b))
Output
list a : [6, 7]
list b : [1, 2]
Modifying Lists - 4
121
www.spharktechnologies.com
Code
PYTHON
1 list_a = [1, 2]
2 list_b = list_a
3 list_a = list_a + [6, 7]
4 print("list a : " + str(list_a))
5 print("list b : " + str(list_b))
Output
list a : [1, 2, 6, 7]
list b : [1, 2]
Modifying Lists - 5
Compound assignment will update the existing list instead of creating a new object.
122
www.spharktechnologies.com
Code
PYTHON
1 list_a = [1, 2]
2 list_b = list_a
3 list_a += [6, 7]
4 print("list a : " + str(list_a))
5 print("list b : " + str(list_b))
Output
list a : [1, 2, 6, 7]
list b : [1, 2, 6, 7]
Modifying Lists - 6
Updating mutable objects will also effect the values in the list, as the reference is changed.
123
www.spharktechnologies.com
Code
PYTHON
1 list_a = [1,2]
2 list_b = [3, list_a]
3 list_a[1] = 4
4 print(list_a)
5 print(list_b)
Output
[1, 4]
[3, [1, 4]]
Modifying Lists - 7
Updating immutable objects will not effect the values in the list, as the reference will be
changed.
124
www.spharktechnologies.com
Code
PYTHON
1 a = 2
2 list_a = [1,a]
3 print(list_a)
4 a = 3
5 print(list_a)
Output
[1, 2]
[1, 2]
Submit Feedback
125
www.spharktechnologies.com
Splitting
str_var.split(separator)
Code
PYTHON
Output
Multiple WhiteSpaces
126
www.spharktechnologies.com
Code
PYTHON
Output
New line
Code
PYTHON
127
www.spharktechnologies.com
Output
Using Separator
Example -1
Code
PYTHON
1 nums = "1,2,3,4"
2 num_list = nums.split(',')
3 print(num_list)
Output
128
www.spharktechnologies.com
Example -2
Code
PYTHON
1 nums = "1,2,,3,4,"
2 num_list = nums.split(',')
3 print(num_list)
Output
Space as Separator
Code
PYTHON
Output
129
www.spharktechnologies.com
String as Separator
Example - 1
Code
PYTHON
Output
Example - 2
PYTHON
1 string a = "step-by-step execution of code"
130
www.spharktechnologies.com
1 string_a step by step execution of code
2 list_a = string_a.split('step')
3 print(list_a)
Output
Joining
str.join(sequence)
Takes all the items in a sequence of strings and joins them into one string.
Code
PYTHON
Output
131
www.spharktechnologies.com
Code
PYTHON
1 list_a = list(range(4))
2 string_a = ",".join(list_a)
3 print(string_a)
Output
Negative Indexing
Using a negative index returns the nth item from the end of list.
132
www.spharktechnologies.com
-1
Reversing a List
Code
133
www.spharktechnologies.com
PYTHON
1 list_a = [5, 4, 3, 2, 1]
2 list_b = list_a[::-1]
3 print(list_b)
Output
[1, 2, 3, 4, 5]
Example-1
Code
PYTHON
1 list_a = [5, 4, 3, 2, 1]
2 item = list_a[-1]
3 print(item)
Output
134
www.spharktechnologies.com
Example-2
Code
PYTHON
1 list_a = [5, 4, 3, 2, 1]
2 item = list_a[-4]
3 print(item)
Output
Code
PYTHON
1 list_a = [5, 4, 3, 2, 1]
2 list_b = list_a[-3:-1]
3 i t(li t b) 135
www.spharktechnologies.com
3 print(list_b)
Output
[3, 2]
136
www.spharktechnologies.com
Code
PYTHON
1 list_a = [5, 4, 3, 2, 1]
2 list_b = list_a[-6:-2]
3 print(list_b)
Output
[5, 4, 3]
Negative Step determines the decrement between each index for slicing.
137
www.spharktechnologies.com
Start index should be greater than the end index in this case
Example - 1
Code
PYTHON
1 list_a = [5, 4, 3, 2, 1]
2 list_b = list_a[4:2:-1]
3 print(list_b)
Output
[1, 2]
Example - 2
Code
138
www.spharktechnologies.com
PYTHON
1 list_a = [5, 4, 3, 2, 1]
2 list_b = list_a[2:4:-1]
3 print(list_b)
Output
[]
Reversing a List
1 list_a = [5, 4, 3, 2, 1]
2 list_b = list_a[::-1]
3 print(list_b)
Output
139
www.spharktechnologies.com
[1, 2, 3, 4, 5]
Reversing a String
Code
PYTHON
1 string_1 = "Program"
2 string_2 = string_1[::-1]
3 print(string_2)
Output
margorP
Code
140
www.spharktechnologies.com
PYTHON
1 string_1 = "Program"
2 string_2 = string_1[6:0:-2]
3 print(string_2)
Output
mro
Example - 1
Code
PYTHON
1 string_1 = "Program"
141
www.spharktechnologies.com
2 string_2 = string_1[-1]
3 print(string_2)
Output
Example - 2
Code
PYTHON
1 string_1 = "Program"
2 string_2 = string_1[-4:-1]
3 print(string_2)
Output
gra
142
www.spharktechnologies.com
Submit Feedback
143
www.spharktechnologies.com
Functions
Block of reusable code to perform a specific action.
Reusing Code
Code
144
www.spharktechnologies.com
PYTHON
1 def greet():
2 print("Hello")
3
4 name = input()
5 print(name)
Input
Teja
Output
Teja
Defining a Function
function_name
145
www.spharktechnologies.com
Code
PYTHON
1 def greet():
2 print("Hello")
3
4 name = input()
5 print(name)
Input
Teja
146
www.spharktechnologies.com
Output
Teja
Calling a Function
The functional block of code is executed only when the function is called.
Code
147
www.spharktechnologies.com
PYTHON
1 def greet():
2 print("Hello")
3
4 name = input()
5 greet()
6 print(name)
Input
Teja
Output
Hello
Teja
Code
148
www.spharktechnologies.com
PYTHON
1 name = input()
2 greet()
3 print(name)
4
5 def greet():
6 print("Hello")
Input
Teja
Output
Printing a Message
Consider the following scenario, we want to create a function, that prints a custom
message, based on some variable that is defined outside the function. In the below
code snippet, we want to access the value in the variable
149
www.spharktechnologies.com
Code
PYTHON
1 def greet():
2 msg = "Hello " + ?
3 print(msg)
4
5 name = input()
6 greet()
Input
Teja
Desired Output
Hello Teja
150
www.spharktechnologies.com
Code
PYTHON
1 def greet(word):
2 msg = "Hello " + word
3 print(msg)
4
5 name = input()
6 greet(word=name)
Input
151
www.spharktechnologies.com
Teja
Output
Hello Teja
Code
PYTHON
1 def greet(word):
2 msg = "Hello " + word
3
4 name = input()
5 greet(word=name)
6 print(msg)
Input
152
www.spharktechnologies.com
Teja
Output
Returning a Value
return keyword.
153
www.spharktechnologies.com
Code
PYTHON
1 def greet(word):
2 msg = "Hello " + word
3 return msg
4
5 name = input()
6 greeting = greet(word=name)
7 print(greeting)
Input
Teja
Output
Hello Teja
Code
PYTHON
1 def greet(word):
2 msg = "Hello "+word
3 return msg
4 print(msg)
5
6 name = input()
7 greeting = greet(word=name)
8 print(greeting)
Input
Teja
Output
Hello Teja
155
www.spharktechnologies.com
Built-in Functions
print()
int()
str()
len()
Submit Feedback
156
www.spharktechnologies.com
Function Arguments
A function can have more than one argument.
Keyword Arguments
Code
PYTHON
Input
Good Morning
Ram
Output
157
www.spharktechnologies.com
Code
PYTHON
Input
Good Morning
Ram
Output
Positional Arguments
Code
158
www.spharktechnologies.com
PYTHON
Input
Good Morning
Ram
Output
Mistake - 1
Code
PYTHON
Input
159
www.spharktechnologies.com
Good Morning
Ram
Output
Mistake - 2
Code
PYTHON
Input
Good Morning
Ram
Output
Default Values
160
www.spharktechnologies.com
Example - 1
Code
PYTHON
Input
Hello
Teja
Output
Hi Ram
Example - 2
Code
PYTHON
Input
Hello 161
www.spharktechnologies.com
Hello
Teja
Output
Hello Ram
Example - 3
Code
PYTHON
Input
Hello
Teja
Output
Teja Ram
Example - 4
Code
162
www.spharktechnologies.com
PYTHON
Input
Hello
Teja
Output
Hi Teja
Example - 5
Code
PYTHON
Input
Hello
Teja
163
www.spharktechnologies.com
Output
Example - 6
Code
PYTHON
Input
Hello
Teja
Output
Hi Teja
Code
PYTHON
1 def increment(a):
164
www.spharktechnologies.com
2 a += 1
3
4 a = int(input())
5 increment(a)
6 print(a)
Input
Output
Even though variable names are same, they are referring to two different objects.
Changing the value of the variable inside the function will not affect the variable
outside.
Submit Feedback
165
www.spharktechnologies.com
Code
PYTHON
1 def add_item(list_x):
2 list_x += [3]
3
4 list_a = [1,2]
5 add_item(list_a)
6 print(list_a)
166
www.spharktechnologies.com
Output
[1, 2, 3]
Code
PYTHON
1 def add_item(list_x):
2 list_x = list_x + [3]
3
4 list_a = [1,2]
5 add_item(list_a)
6 print(list_a)
Output
[1, 2]
Default args are evaluated only once when the function is defined, not each time the function is called.
Code
167
www.spharktechnologies.com
PYTHON
1 def add_item(list_x=[]):
2 list_x += [3]
3 print(list_x)
4
5 add_item()
6 add_item([1,2])
7 add_item()
Output
[3]
[1, 2, 3]
[3, 3]
Built-in functions
Built-in functions are readily available for reuse.
print()
int()
str()
len()
168
www.spharktechnologies.com
Finding Minimum
min() returns the smallest item in a sequence or smallest of two or more arguments.
PYTHON
1 min(sequence)
2 min(arg1, arg2, arg3 ...)
Example - 1
Code
PYTHON
1 smallest= min(3,5,4)
2 print(smallest)
Output
Example - 2
Code
169
www.spharktechnologies.com
PYTHON
1 smallest = min([1,-2,4,2])
2 print(smallest)
Output
-2
Minimum of Strings
min(str_1, str_2)
P - 80(unicode)
J - 74(unicode)
Code
PYTHON
Output
170
www.spharktechnologies.com
Java
Finding Maximum
max() returns the largest item in a sequence or largest of two or more arguments.
PYTHON
1 max(sequence)
2 max(arg1, arg2, arg3 ...)
Example - 1
Code
PYTHON
1 largest = max(3,5,4)
2 print(largest)
Ouput
171
www.spharktechnologies.com
Example - 2
Code
PYTHON
1 largest = max([1,-2,4,2])
2 print(largest)
Output
Finding Sum
sum(sequence) returns sum of items in a sequence.
Code
PYTHON
1 sum_of_numbers = sum([1,-2,4,2])
2 print(sum_of_numbers)
Output
172
www.spharktechnologies.com
Code
PYTHON
1 list_a = [3, 5, 2, 1, 4, 6]
2 list_x = sorted(list_a)
3 print(list_x)
Output
[1, 2, 3, 4, 5, 6]
173
www.spharktechnologies.com
Stack
Calling a Function
Calling
174
www.spharktechnologies.com
Code
PYTHON
1 def get_largest_sqr(list_x):
2 len_list = len(list_x)
3 for i in range(len_list):
4 x = list_x[i]
5 list_x[i] = x * x
6 largest = max(list_x)
7 return largest
8
9 list_a = [1,-3,2]
10 result = get largest sqr(list a)
175
www.spharktechnologies.com
10 result = get_largest_sqr(list_a)
11 print(result)
Collapse
Output
Code
176
www.spharktechnologies.com
PYTHON
1 def get_sqrd_val(x):
2 return (x * x)
3
4 def get_sum_of_sqrs(list_a):
5 sqrs_sum = 0
6 for i in list_a:
7 sqrs_sum += get_sqrd_val(i)
8 return sqrs_sum
9
10 list_a = [1, 2, 3]
11 sum_of_sqrs = get_sum_of_sqrs(list_a)
12 print(sum_of_sqrs)
Collapse
Output
14
177
www.spharktechnologies.com
Recursion
178
www.spharktechnologies.com
Multiply N Numbers
PYTHON
179
www.spharktechnologies.com
Base Case
Input
Output
Code
180
www.spharktechnologies.com
PYTHON
1 def factorial(n):
2 return n * factorial(n - 1)
3 num = int(input())
4 result = factorial(num)
5 print(result)
Input
Output
Submit Feedback
181
www.spharktechnologies.com
List Methods
Python provides list methods that allow us to work with lists.
append()
extend()
insert()
pop()
clear()
remove()
sort()
index()
Append
Code
PYTHON
1 list_a = []
2 for x in range(1,4):
3 list_a.append(x)
4 print(list_a)
Output
[1, 2, 3]
Extend
182
www.spharktechnologies.com
list_a.extend(list_b) Adds all the elements of a sequence to the end of the list.
Code
PYTHON
1 list_a = [1, 2, 3]
2 list_b = [4, 5, 6]
3 list_a.extend(list_b)
4 print(list_a)
Output
[1, 2, 3, 4, 5, 6]
Insert
Code
PYTHON
1 list_a = [1, 2, 3]
2 list_a.insert(1,4)
3 print(list_a)
Output
[1, 4, 2, 3]
Pop
Code
183
www.spharktechnologies.com
PYTHON
1 list_a = [1, 2, 3]
2 list_a.pop()
3 print(list_a)
Output
[1, 2]
Remove
Code
PYTHON
1 list_a = [1, 3, 2, 3]
2 list_a.remove(3)
3 print(list_a)
Output
[1, 2, 3]
Clear
Code
184
www.spharktechnologies.com
PYTHON
1 list_a = [1, 2, 3]
2 list_a.clear()
3 print(list_a)
Output
[]
Index
list.index(value) Returns the index at the first occurrence of the specified value.
Code
PYTHON
1 list_a = [1, 3, 2, 3]
2 index =list_a.index(3)
3 print(index)
Output
Count
Code
185
www.spharktechnologies.com
PYTHON
1 list_a = [1, 2, 3]
2 count = list_a.count(2)
3 print(count)
Output
Sort
Code
PYTHON
1 list_a = [1, 3, 2]
2 list_a.sort()
3 print(list_a)
Output
[1, 2, 3]
Code
186
www.spharktechnologies.com
PYTHON
1 list_a = [1, 3, 2]
2 list_a.sort()
3 print(list_a)
Output
[1, 2, 3]
Code
PYTHON
1 list_a = [1, 3, 2]
2 sorted(list_a)
3 print(list_a)
Output
[1, 3, 2]
Submit Feedback
187
www.spharktechnologies.com
None
Code
PYTHON
1 var = None
2 print(var)
3 print(type(var))
Output
None
<class 'NoneType'>
Code
PYTHON
1 def increment(a):
2 a += 1
3
4 a = 55
5 result = increment(a)
6 print(result)
Output
None
None
Example - 1
189
www.spharktechnologies.com
Code
PYTHON
1 def increment(a):
2 a += 1
3 return
4
5 a = 55
6 result = increment(a)
7 print(result)
Output
None
Example - 2
Code
PYTHON
1 def increment(a):
2 a += 1
3 return None
4
5 a = 5
6 result = increment(a)
7 print(result)
190
www.spharktechnologies.com
p ( )
Output
None
Example - 3
Code
PYTHON
1 result = print("Hi")
2 print(result)
Output
Hi
None
Tuple
191
www.spharktechnologies.com
Code
PYTHON
1 a = 2
2 tuple_a = (5, "Six", a, 8.2)
Creating a Tuple
Code
PYTHON
1 a = 2
2 tuple_a = (5, "Six", a, 8.2)
3 print(type(tuple_a))
4 print(tuple_a)
Output
<class 'tuple'>
(5 'Six' 2 8 2) 192
www.spharktechnologies.com
Code
PYTHON
1 a = (1,)
2 print(type(a))
3 print(a)
Output
<class 'tuple'>
(1,)
Accessing Tuple elements is also similar to string and list accessing and slicing.
Code
PYTHON
1 a = 2
2 tuple_a = (5, "Six", a, 8.2)
193
www.spharktechnologies.com
3 print(tuple_a[1])
Output
Six
Code
PYTHON
1 tuple_a = (1, 2, 3, 5)
2 tuple_a[3] = 4
3 print(tuple_a)
Output
194
www.spharktechnologies.com
len()
Iterating
Slicing
Extended Slicing
Converting to Tuple
tuple(sequence) Takes a sequence and converts it into tuple.
String to Tuple
Code
PYTHON
1 color = "Red"
2 tuple_a = tuple(color)
3 print(tuple_a)
Output
195
www.spharktechnologies.com
List to Tuple
Code
PYTHON
1 list_a = [1, 2, 3]
2 tuple_a = tuple(list_a)
3 print(tuple_a)
Output
(1, 2, 3)
Sequence to Tuple
Code
PYTHON
1 tuple_a = tuple(range(4))
196
www.spharktechnologies.com
2 print(tuple_a)
Output
(0, 1, 2, 3)
Membership Check
Membership Operators
in
not in
Example - 1
Code
PYTHON
1 tuple_a = (1, 2, 3, 4)
2 is_part = 5 in tuple_a
3 print(is_part)
197
www.spharktechnologies.com
Output
False
Example - 2
Code
PYTHON
1 tuple_a = (1, 2, 3, 4)
2 is_part = 1 not in tuple_a
3 print(is_part)
Output
False
List Membership
Code
198
www.spharktechnologies.com
PYTHON
1 list_a = [1, 2, 3, 4]
2 is_part = 1 in list_a
3 print(is_part)
Output
True
String Membership
Code
PYTHON
1 word = 'Python'
2 is_part = 'th' in word
3 print(is_part)
Output
199
www.spharktechnologies.com
True
Unpacking
Code
PYTHON
Output
R
200
www.spharktechnologies.com
R
e
d
Errors in Unpacking
Code
PYTHON
Output
Code
201
www.spharktechnologies.com
PYTHON
Output
Tuple Packing
Code
PYTHON
1 a = 1, 2, 3
2 print(type(a))
3 print(a)
Output
202
www.spharktechnologies.com
<class 'tuple'>
(1, 2, 3)
Code
PYTHON
1 a = 1,
2 print(type(a))
3 print(a)
Output
<class 'tuple'>
(1,)
Code
PYTHON
1 a, = 1,
2 print(type(a))
3 print(a)
203
www.spharktechnologies.com
Output
<class 'int'>
1
Submit Feedback
204
www.spharktechnologies.com
Sets
Unordered collection of items.
Creating a Set
205
www.spharktechnologies.com
Code
PYTHON
1 a = 2
2 set_a = {5, "Six", a, 8.2}
3 print(type(set_a))
4 print(set_a)
Output
<class 'set'>
{8.2, 2, 'Six', 5}
No Duplicate Items
Code
206
www.spharktechnologies.com
PYTHON
Output
Immutable Items
Code
PYTHON
Output
207
www.spharktechnologies.com
We use
Code
PYTHON
1 set_a = set()
2 print(type(set_a))
3 print(set_a)
Output
<class 'set'>
set()
Converting to Set
set(sequence) takes any sequence as argument and converts to set, avoiding duplicates
208
www.spharktechnologies.com
List to Set
Code
PYTHON
1 set_a = set([1,2,1])
2 print(type(set_a))
3 print(set_a)
Output
<class 'set'>
{1, 2}
String to Set
Code
PYTHON
1 set_a = set("apple")
2 print(set_a)
Output
209
www.spharktechnologies.com
Tuple to Set
Code
PYTHON
Output
{1, 2}
Accessing Items
Indexing
Slicing
Code
210
www.spharktechnologies.com
PYTHON
1 set_a = {1, 2, 3}
2 print(set_a[1])
3 print(set_a[1:3])
Output
Adding Items
set.add(value) adds the item to the set, if the item is not present already.
Code
PYTHON
1 set_a = {1, 3, 6, 2, 9}
2 set_a.add(7)
3 print(set_a)
Output
211
www.spharktechnologies.com
{1, 2, 3, 6, 7, 9}
Code
PYTHON
1 set_a = {1, 3, 9}
2 set_a.update([2, 3])
3 print(set_a)
Output
{2, 1, 3, 9}
Code
212
www.spharktechnologies.com
PYTHON
1 set_a = {1, 3, 9}
2 set_a.discard(3)
3 print(set_a)
Output
{1, 9}
Code
PYTHON
1 set_a = {1, 3, 9}
2 set_a.remove(5)
3 print(set_a)
Output
KeyError: 5
213
www.spharktechnologies.com
Operations on Sets
clear()
len()
Iterating
Membership Check
214
www.spharktechnologies.com
Set Operations
Set objects also support mathematical operations like union, intersection, difference,
and symmetric difference.
Union
Code
PYTHON
1 set_a = {4, 2, 8}
2 set_b = {1, 2}
3 union = set_a | set_b
4 print(union)
Output
{1, 2, 4, 8}
Code
215
www.spharktechnologies.com
PYTHON
1 set_a = {4, 2, 8}
2 list_a = [1, 2]
3 union = set_a.union(list_a)
4 print(union)
Output
{1, 2, 4, 8}
Intersection
Code
PYTHON
1 set_a = {4, 2, 8}
2 set_b = {1, 2}
3 intersection = set_a & set_b
4 print(intersection)
Output
{2}
Code
PYTHON
1 set_a = {4, 2, 8}
2 list a = [1, 2]
216
www.spharktechnologies.com
2 list_a [1, 2]
3 intersection = set_a.intersection(list_a)
4 print(intersection)
Output
{2}
Difference
Difference of two sets is a set containing all the elements in the first set but not
second.
Code
PYTHON
1 set_a = {4, 2, 8}
2 set_b = {1, 2}
3 diff = set_a - set_b
4 print(diff)
217
www.spharktechnologies.com
Output
{8, 4}
Code
PYTHON
1 set_a = {4, 2, 8}
2 tuple_a = (1, 2)
3 diff = set_a.difference(tuple_a)
4 print(diff)
Output
{8, 4}
Symmetric Difference
Symmetric difference of two sets is a set containing all elements which are not
common to both sets.
Code
PYTHON
1 set_a = {4, 2, 8}
2 set_b = {1, 2}
3 symmetric_diff = set_a ^ set_b
4 print(symmetric_diff)
Output
218
www.spharktechnologies.com
{8, 1, 4}
Code
PYTHON
1 set_a = {4, 2, 8}
2 set_b = {1, 2}
3 diff = set_a.symmetric_difference(set_b)
4 print(diff)
Output
{8, 1, 4}
Set Comparisons
Set comparisons are used to validate whether one set fully exists within another
issubset()
issuperset()
isdisjoint()
Subset
219
www.spharktechnologies.com
set2.issubset(set1) Returns True if all elements of second set are in first set. Else,
False
Example - 1
Code
PYTHON
1 set_1 = {'a', 1, 3, 5}
2 set_2 = {'a', 1}
3 is_subset = set_2.issubset(set_1)
4 print(is_subset)
Output
220
www.spharktechnologies.com
True
Example - 2
Code
PYTHON
1 set_1 = {4, 6}
2 set_2 = {2, 6}
3 is_subset = set_2.issubset(set_1)
4 print(is_subset)
Output
False
SuperSet
221
www.spharktechnologies.com
set1.issuperset(set2) Returns True if all elements of second set are in first set.
Else, False
Example - 1
Code
PYTHON
1 set_1 = {'a', 1, 3, 5}
2 set_2 = {'a', 1}
3 is_superset = set_1.issuperset(set_2)
4 print(is_superset)
Output
222
www.spharktechnologies.com
True
Example - 2
Code
PYTHON
1 set_1 = {4, 6}
2 set_2 = {2, 6}
3 is_superset = set_1.issuperset(set_2)
4 print(is_superset)
Output
False
Disjoint Sets
223
www.spharktechnologies.com
Code
PYTHON
1 set_a = {1, 2}
2 set_b = {3, 4}
3 is_disjoint = set_a.isdisjoint(set_b)
4 print(is_disjoint)
Output
True
Submit Feedback
224
www.spharktechnologies.com
225
www.spharktechnologies.com
Code
PYTHON
Output
[8, 6]
Example - 1
Code
PYTHON
Output
Example - 2
Code
PYTHON
Output
227
www.spharktechnologies.com
String Formatting
Code
PYTHON
1 name = input()
2 age = int(input())
3 msg = ("Hi " + name + ". You are "+ str(age) + " years old.")
4 print(msg)
Add Placeholders
Add placeholders
228
www.spharktechnologies.com
PYTHON
{}
Code
PYTHON
1 name = "Raju"
2 age = 10
3 msg = "Hi {}. You are {} years old."
4 print(msg.format(name, age))
Output
Number of Placeholders
Code
229
www.spharktechnologies.com
PYTHON
1 name = "Raju"
2 age = 10
3 msg = "Hi {}. You are {} years old {}."
4 print(msg.format(name, age))
Output
Numbering Placeholders
Code
PYTHON
1 name = input()
2 age = int(input())
3 msg = "Hi {0}. You are {1} years old."
4 print(msg.format(name, age))
Input
230
www.spharktechnologies.com
Raju
10
Output
Code
PYTHON
1 name = input()
2 age = int(input())
3 msg = "Hi {1}. You are {0} years old."
4 print(msg.format(name, age))
Input
231
www.spharktechnologies.com
Raju
10
Output
Naming Placeholder
Code
PYTHON
1 name = input()
2 age = int(input())
3 msg = "Hi {name}. You are {age} years old."
4 print(msg.format(name=name, age=age))
Input
232
www.spharktechnologies.com
Raju
10
Output
Submit Feedback
233
www.spharktechnologies.com
Creating a Dictionary
Code
PYTHON
1 dict_a = {
2 "name": "Teja",
3 "age": 15
4 }
Code
PYTHON
1 dict_a = {
2 "name": "Teja",
3 "age": 15
4 }
Code
PYTHON
234
www.spharktechnologies.com
Output
<class 'dict'>
{'name': 'Teja','age': 15}
Immutable Keys
Code
PYTHON
1 dict_a = {
2 "name": "Teja",
3 "age": 15,
4 "roll_no": 15
5 }
1 dict_a = dict()
2 print(type(dict_a))
3 print(dict_a)
Output
<class 'dict'>
{}
Code - 2
235
www.spharktechnologies.com
PYTHON
1 dict_a = {}
2 print(type(dict_a))
3 print(dict_a)
Output
<class 'dict'>
{}
Accessing Items
Code
PYTHON
1 dict_a = {
2 'name': 'Teja',
3 'age': 15
4 }
5 print(dict_a['name'])
Output
Teja
The
236
www.spharktechnologies.com
Code
PYTHON
1 dict_a = {
2 'name': 'Teja',
3 'age': 15
4 }
5 print(dict_a.get('name'))
Output
Teja
Code
PYTHON
1 dict_a = {
2 'name': 'Teja',
3 'age': 15
4 }
5 print(dict_a.get('city'))
Output
None
KeyError
[] to access the key-value, KeyError is raised in case a key is not found in the dictionary.
Code
PYTHON
2 print(dict_a['city'])
Output
KeyError: 'city'
Quick Tip
If we use the square brackets [] , KeyError is raised in case a key is not found in the
dictionary. On the other hand, the get() method returns None if the key is not found.
Membership Check
Code
PYTHON
1 dict_a = {
2 'name': 'Teja',
3 'age': 15
4 }
5 result = 'name' in dict_a
6 print(result)
Output
True
Operations on Dictionaries
238
www.spharktechnologies.com
Code
PYTHON
Output
Code
PYTHON
1 dict_a = {
2 'name': 'Teja',
3 'age': 15
4 }
5 dict_a['age'] = 24
6 print(dict_a)
Output
239
www.spharktechnologies.com
Code
PYTHON
1 dict_a = {
2 'name': 'Teja',
3 'age': 15
4 }
5 del dict_a['age']
6 print(dict_a)
Output
{'name': 'Teja'}
Dictionary Views
They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the
view reflects these changes.
Dictionary Methods
dict.keys()
returns dictionary Keys
dict.values()
returns dictionary Values
dict.items()
returns dictionary items(key-value) pairs
240
www.spharktechnologies.com
Getting Keys
The
keys() method returns a view object of the type dict_keys that holds a list of all keys.
Code
PYTHON
1 dict_a = {
2 'name': 'Teja',
3 'age': 15
4 }
5 print(dict_a.keys())
Output
dict_keys(['name', 'age'])
Getting Values
The
values() method returns a view object that displays a list of all the values in the dictionary.
Code
PYTHON
1 dict_a = {
2 'name': 'Teja',
3 'age': 15
4 }
5 print(dict_a.values())
Output
241
www.spharktechnologies.com
dict_values(['Teja', 15])
Getting Items
The
items() method returns a view object that displays a list of dictionary's (key, value) tuple pairs.
Code
PYTHON
1 dict_a = {
2 'name': 'Teja',
3 'age': 15
4 }
5 print(dict_a.items())
Output
Example - 1
Code
PYTHON
1 dict_a = {
2 'name': 'Teja',
3 'age': 15
4 }
5 for key in dict_a.keys():
6 print(key)
242
www.spharktechnologies.com
Output
name
age
Example - 2
Code
PYTHON
1 dict_a = {
2 'name': 'Teja',
3 'age': 15
4 }
5 keys_list = list(dict_a.keys())
6 print(keys_list)
Output
['name', 'age']
Example - 3
Code
PYTHON
1 dict_a = {
2 'name': 'Teja',
3 'age': 15
4 }
5 for value in dict_a.values():
6 print(value)
Output
Teja
243
www.spharktechnologies.com
15
Example - 4
Code
PYTHON
1 dict_a = {
2 'name': 'Teja',
3 'age': 15
4 }
5 for key, value in dict_a.items():
6 pair = "{} {}".format(key,value)
7 print(pair)
Output
name Teja
age 15
Code
PYTHON
1 dict_a = {
2 'name': 'Teja',
3 'age': 15
4 }
5 view = dict_a.keys()
6 print(view)
7 dict_a['roll_no'] = 10
8 print(view)
Output
Converting to Dictionary
dict(sequence) takes any number of key-value pairs and converts to dictionary.
Code
PYTHON
1 list_a = [
2 ("name","Teja"),
3 ["age",15],
4 ("roll_no",15)
5 ]
6 dict_a = dict(list_a)
7 print(dict_a)
Output
Code
PYTHON
Output
Type of Keys
245
www.spharktechnologies.com
246
www.spharktechnologies.com
Dictionary Methods
copy()
get()
update()
1 dict_a = {
2 'name': 'Teja',
3 'age': 15
4 }
5 dict_b = dict_a
6 dict_b['age'] = 20
7 print(dict_a)
8 print(id(dict_a))
9 print(id(dict_b))
Output
247
www.spharktechnologies.com
Copy of Dictionary
Code
PYTHON
1 dict_a = {
2 'name': 'Teja',
3 'age': 15
4 }
5 dict_b = dict_a.copy()
6 dict_b['age'] = 20
7 print(dict_a)
8 print(id(dict_a))
9 print(id(dict_b))
Output
Copy of List
Code
PYTHON
Output
['Teja', 15]
139631861316032
248
www.spharktechnologies.com
139631860589504
Operations on Dictionaries
len()
clear()
Membership Check
Code
PYTHON
1 dict_a = {
2 'name': 'Teja',
3 'age': 15
4 }
5 print(len(dict_a)) # length of dict_a
6 if 'name' in dict_a: # Membership Check
7 print("True")
8 dict_a.clear() # clearing dict_a
9 print(dict_a)
Output
2
True
{}
Iterating
Code
PYTHON
1 dict_a = {'name': 'Teja', 'age': 15}
2 for k in dict_a.keys():
3 if k == 'name':
249
www.spharktechnologies.com
3 if k name :
4 del dict_a[k]
5 print(dict_a)
Output
max(*args) max(1,2,3..)
min(*args) min(1,2,3..)
Code
PYTHON
1 def more_args(*args):
250
www.spharktechnologies.com
2 print(args)
3
4 more_args(1, 2, 3, 4)
5 more_args()
Output
(1, 2, 3, 4)
()
Unpacking as Arguments
unpack it with
* while passing.
Code
PYTHON
Output
Hello Teja
251
www.spharktechnologies.com
Code
PYTHON
1 def more_args(**kwargs):
2 print(kwargs)
3
4 more_args(a=1, b=2)
5 more_args()
Output
{'a': 1, 'b': 2}
{}
Iterating
kwargs is a dictionary. We can iterate over them like any other dictionary.
Code
252
www.spharktechnologies.com
PYTHON
1 def more_args(**kwargs):
2 for i, j in kwargs.items():
3 print('{}:{}'.format(i,j))
4
5 more_args(a=1, b=2)
Output
a:1
b:2
Unpacking as Arguments
Code - 1
PYTHON
Output
Hello Teja
Code - 2
253
www.spharktechnologies.com
PYTHON
Output
Submit Feedback
254
www.spharktechnologies.com
Concepts
Built-in Functions
abs()
all()
any()
reversed()
enumerate()
List Methods
copy()
reverse()
1. Built-in Functions
1.1 Abs
Syntax:
abs(number)
The
Example 1:
255
www.spharktechnologies.com
Code
PYTHON
1 num = -4
2 abs_value = abs(num)
3
4 print(abs_value)
Output
Example 2:
Code
PYTHON
1 print(abs(5))
2 print(abs(-2.90))
3 print(abs(3 - 5))
Output
5
2.9
2
1.2 All
Syntax:
all(sequence)
The
all() function returns True if all the items in the sequence are true (or if
the sequence is empty). Otherwise, it returns False .
256
www.spharktechnologies.com
all() function evaluates to false, for which the bool() function returns
False . For example, 0 , None , False , etc.
Example 1:
Code
PYTHON
Output
True
Example 2:
Code
PYTHON
1 set_a = {}
2 is_all_true = all(set_a)
3
4 print(is_all_true)
Output
True
Example 3:
Code
PYTHON
1 is_true_in_list = all([1, 5, 0, 4])
257
www.spharktechnologies.com
Output
False
True
False
all() function returns True if all the keys in the dictionary are true.
Otherwise, it returns False .
Example 4:
Code
PYTHON
1 dict_a = {
2 "name": "Teja",
3 "age": 15
4 }
5
6 is_all_true = all(dict_a)
7 print(is_all_true)
Output
True
Example 5:
Code
PYTHON
1 dict_a = {
2 0: "Hello"
258
www.spharktechnologies.com
2 0: Hello ,
3 1: "World"
4 }
5
6 is_all_true = all(dict_a)
7 print(is_all_true)
Output
False
1.3 Any
Syntax:
any(sequence)
The
any() function returns True if any of the items in the sequence is true.
Otherwise, it returns False .
False .
any() function evaluates to false, for which the bool() function returns
False . For example, 0 , None , False , etc.
Example 1:
Code
PYTHON
Output
259
www.spharktechnologies.com
True
Example 2:
Code
PYTHON
1 set_a = {}
2 is_any_true = any(set_a)
3
4 print(is_any_true)
Output
False
Example 3:
Code
PYTHON
Output
True
False
True
260
www.spharktechnologies.com
any() function returns True if any of the keys in the dictionary is true.
Otherwise, it returns False .
Example 4:
Code
PYTHON
1 dict_a = {
2 0: "Teja",
3 1: 15
4 }
5
6 is_any_true = any(dict_a)
7 print(is_any_true)
Output
True
Example 5:
Code
PYTHON
1 dict_a = {
2 0: "hello",
3 False: "world"
4 }
5
6 is_any_true = any(dict_a)
7 print(is_any_true)
Output
False
261
www.spharktechnologies.com
1.4 Reversed
Syntax:
reversed(sequence)
Here, the
sequence does not include sets and dictionaries as they are unordered
collections of items.
The
Example 1:
Code
PYTHON
1 name = "Teja"
2 reversed_name = reversed(name)
3
4 print(list(reversed_name))
Output
Example 2:
Code
PYTHON
1 tuple_a = (1, 2, 3, 4)
2 list_a = ["A", "B", "C", "D"]
3
4 reversed_tuple = list(reversed(tuple_a))
5 reversed_list = list(reversed(list_a))
6
7 print(reversed_tuple)
8 print(reversed_list)
262
www.spharktechnologies.com
Output
[4, 3, 2, 1]
['D', 'C', 'B', 'A']
1.5 Enumerate
Syntax:
enumerate(sequence, start)
Here,
start (Optional): it indicates the start point of the counter. Its default
value is 0 .
The
Example 1:
Code
PYTHON
1 name = "Teja"
2 enumerate_name = enumerate(name)
3
4 print(list(enumerate_name))
Output
Example 2:
263
www.spharktechnologies.com
Code
PYTHON
1 set_a = {1, 2, 3, 4}
2
3 enumerate_set = list(enumerate(set_a, 10))
4 print(enumerate_set)
Output
Code
PYTHON
Output
(0, 'Jack')
(1, 'John')
(2, 'James')
Code
PYTHON
1 names = ["Jack", "John", "James"]
2
3 for count, each_name in enumerate(names):
4 tuple a = (count, each name)
264
www.spharktechnologies.com
4 tuple_a (count, each_name)
5 print(tuple_a)
Output
(0, 'Jack')
(1, 'John')
(2, 'James')
2. List Methods
2.1 Copy
Syntax:
list.copy()
The
copy() method returns a copy of the specified list. After copying, any
changes made to the original list do not affect the items in the copied list.
Example 1:
Code
PYTHON
1 list_a = [1, 2, 3, 4]
2 list_b = list_a.copy()
3 print(list_b)
Output
265
www.spharktechnologies.com
[1, 2, 3, 4]
Example 2:
Code
PYTHON
Output
list_a and list_b will be referring to the same object. So, when an item in
list_a is updated it affected list_b also.
list_1 using the copy() method, the variables list_1 and list_2 will
refer to different objects. So, when an item in list_1 is updated it does not
affect list_2 .
However, updating mutable objects will affect the values in the copied list
also, as the reference is changed.
Example 3:
Code
PYTHON
li t [" " "b" " "] 266
www.spharktechnologies.com
Output
2.2 Reverse
Syntax:
list.reverse()
The
reverse() method reverses the items of the list. It doesn't return any value
but updates the existing list.
Example 1:
Code
PYTHON
1 list_a = [1, 2, 3, 4]
2 list_a.reverse()
3
4 print(list_a)
Output
[4, 3, 2, 1]
Example 2:
267
www.spharktechnologies.com
Code
PYTHON
Output
Submit Feedback
268
www.spharktechnologies.com
Introduction to OOP
Good Software
269
www.spharktechnologies.com
A good software should keep the users happy, by delivering what they
need.
A good software should also keep the developers happy. Ease of making
changes (softness) keeps developers happy. So is should be:
Easy to fix bugs and add new features within the scope.
Note
270
www.spharktechnologies.com
The techniques and concepts you learn in this topic are developed
over time based on software developers' experiences to make
working code easier.
OOPs
271
www.spharktechnologies.com
Organized Description
In the below description we are grouping the information related to an
object.
273
www.spharktechnologies.com
Object 1 is a car
Object 1 has
Four tyres
Four seats
Four doors
and so on ...
Object 1 can
Sound horn
Move
Accelerate
and so on ...
Object 2 is a dog
Object 2 has
Brown fur
Four legs
Two ears
and so on ...
Object 2 can
Bark
Jump
Run
and so on ...
Collapse
274
www.spharktechnologies.com
Submit Feedback
275
www.spharktechnologies.com
Object 3 is a Mobile
Properties
camera : 13 MP
t G 276
www.spharktechnologies.com
storage : 16 GB
battery life : 21 Hrs
ram : 3 GB
and so on ...
Object 4 is a Mobile
Properties
camera : 64 MP
storage : 128 GB
battery life : 64 Hrs
ram : 6 GB
and so on ...
Collapse
In this case, the objects that we describe have completely the same set of
properties like camera, storage, etc.
Template
For objects that are very similar to each other (objects that have the same set
of actions and properties), we can create a standard Form or Template
that can be used to describe different objects in that category.
Mobile Template
Model :
Camera:
Storage:
Does it have a Face Unlock? Yes | No 277
www.spharktechnologies.com
Filled Template
Bundling Data
278
www.spharktechnologies.com
Defining a Class
class
Special Method
279
www.spharktechnologies.com
Code
PYTHON
1 class Mobile:
2 def __init__(self, model, camera):
3 self.model = model
4 self.camera = camera
1 class Mobile:
2 def __init__(self, model, camera):
3 self.model = model
4 self.camera = camera
5 def make_call(self, number):
6 print("calling..")
280
www.spharktechnologies.com
model and camera are the properties and values are which passed to
the __init__ method.
Action
PYTHON
1 class Mobile:
2 def __init__(self, model, camera):
3 self.model = model
4 self.camera = camera
5 def make_call(self, number):
6 print("calling..")
Using a Class
281
www.spharktechnologies.com
Instance of Class
Code
PYTHON
1 class Mobile:
2 def __init__(self, model, camera):
3 self.model = model
4 self.camera= camera
5
6 mobile_obj = Mobile(
7 "iPhone 12 Pro",
8 "12 MP")
9 print(mobile_obj)
Class Object
282
www.spharktechnologies.com
1 class Mobile:
2 def __init__(self, model, camera):
3 self.model = model
4 self.camera= camera
5
6 mobile_obj = Mobile(
7 "iPhone 12 Pro",
8 "12 MP")
9 print(mobile_obj)
Code
283
www.spharktechnologies.com
PYTHON
1 class Mobile:
2 def __init__(self, model, camera):
3 self.model = model
4 self.camera= camera
5 def make_call(self,number):
6 return "calling..{}".format(number)
Code
PYTHON
1 class Mobile:
2 def __init__(self, model, camera):
3 self.model = model
4 self.camera= camera
5 def make_call(self,number):
6 print("calling..{}".format(number))
7
8 mobile_obj = Mobile("iPhone 12 Pro", "12 MP")
9 mobile_obj.make_call(9876543210)
Output
284
www.spharktechnologies.com
calling..9876543210
Multiple Instances
Code
PYTHON
1 class Mobile:
2 def __init__(self, model, camera):
3 self.model = model
4 self.camera= camera
5 def make_call(self,number):
6 print("calling..{}".format(number))
7
8 mobile_obj1 = Mobile("iPhone 12 Pro", "12 MP")
9 print(id(mobile_obj1))
10 mobile_obj2 = Mobile("Galaxy M51", "64 MP")
11 print(id(mobile_obj2))
Collapse
Output
139685004996560
139685004996368
285
www.spharktechnologies.com
Type of Object
The class from which object is created is considered to be the type of object.
Code
PYTHON
1 class Mobile:
2 def __init__(self, model, camera):
3 self.model = model
4 self.camera = camera
5
6 obj_1 = Mobile("iPhone 12 Pro", "12 MP")
7 print(type(obj_1))
Output
<class '__main__.Mobile'>
Submit Feedback
286
www.spharktechnologies.com
Attributes of an Object
. (dot) character.
Code
PYTHON
1 class Mobile:
2 def __init__(self, model, storage):
3 self.model = model
4 self.storage = storage
5
6
7 obj = Mobile("iPhone 12 Pro", "128GB")
8 print(obj.model)
Output
iPhone 12 Pro
Code
PYTHON
1 class Mobile:
2 def __init__(self, model):
3 self.model = model
4
5 def get_model(self):
6 print(self.model)
7
287
www.spharktechnologies.com
8
9 obj_1 = Mobile("iPhone 12 Pro")
10 obj_1.get_model()
Output
iPhone 12 Pro
Updating Attributes
Code
PYTHON
1 class Mobile:
2 def __init__(self, model):
3 self.model = model
4
5 def update_model(self, model):
6 self.model = model
7
8
9 obj_1 = Mobile("iPhone 12")
10 print(obj_1.model)
11 obj_1.update_model("iPhone 12 Pro")
12 print(obj_1.model)
Collapse
Output
iPhone 12
iPhone 12 Pro
Modeling Class
288
www.spharktechnologies.com
Code
PYTHON
1 class Cart:
2 def __init__(self):
3 self.items = {}
4 self.price_details = {"book": 500, "laptop": 30000}
5
6 def add_item(self, item_name, quantity):
7 self.items[item_name] = quantity
8
9 def remove_item(self, item_name):
10 del self.items[item_name]
11
12 def update_quantity(self, item_name, quantity):
13 self.items[item_name] = quantity
14
15 def get_cart_items(self):
16 cart_items = list(self.items.keys())
17 return cart_items
18
19 def get_total_price(self):
20 total_price = 0
21 for item, quantity in self.items.items():
22 total_price += quantity * self.price_details[item]
23 return total_price
24
25
26 cart_obj = Cart()
27 cart_obj.add_item("book", 3)
28 cart_obj.add_item("laptop", 1)
29 print(cart_obj.get_total_price())
30 cart_obj.remove_item("laptop")
31 print(cart_obj.get_cart_items())
32 cart_obj.update_quantity("book", 2)
33 print(cart_obj.get_total_price())
Collapse
Output
289
www.spharktechnologies.com
31500
['book']
1000
Submit Feedback
290
www.spharktechnologies.com
Shopping Cart
Users can add different items to their shopping cart and checkout.
The total value of the cart should be more than a minimum amount (Rs. 100/-) for the
checkout.
During Offer Sales, all users get a flat discount on their cart and the minimum cart value will
be Rs. 200/-.
Attributes
Instance Attributes
Class Attributes
Instance Attributes
Attributes whose value can differ for each instance of class are modeled as instance attributes.
291
www.spharktechnologies.com
Class Attributes
Attributes whose values stay common for all the objects are modelled as Class Attributes.
Code
PYTHON
1 class Cart:
2 flat_discount = 0
3 min_bill = 100
d f i it ( lf) 292
www.spharktechnologies.com
4 def __init__(self):
5 self.items = {}
6 def add_item(self,..):
7 self.items[item_name] = quantity
8 def display_items(self):
9 print(items)
10 a = Cart()
11 a.display_items()
Collapse
Output
Self
Code
PYTHON
1 class Cart:
2 flat_discount = 0
3 min_bill = 100
4 def __init__(self):
5 self.items = {}
6 def add_item(self,item_name, quantity):
7 self.items[item_name] = quantity
8 def display_items(self):
9 print(self)
10
11 a = Cart()
12 a.display_items()
13 print(a)
Collapse
Output
293
www.spharktechnologies.com
Code
PYTHON
1 class Cart:
2 flat_discount = 0
3 min_bill = 100
4 def __init__(self):
5 self.items = {}
6 def add_item(self, item_name,quantity):
7 self.items[item_name] = quantity
8 def display_items(self):
9 print(self.items)
10 a = Cart()
11 a.add_item("book", 3)
12 a.display_items()
Collapse
Output
{"book": 3}
Code
PYTHON
1 class Cart:
2 flat_discount = 0
3 min_bill = 100
4 def __init__(self):
5 self.items = {}
6 def add_item(self, item_name,quantity):
7 self.items[item_name] = quantity
8 def display_items(self):
9 print(self.items)
10 a = Cart()
11 a.add_item("book", 3)
12 print(a.items)
Collapse
Output
294
www.spharktechnologies.com
{'book': 3}
Code
PYTHON
1 class Cart:
2 flat_discount = 0
3 min_bill = 100
4 def __init__(self):
5 self.items = {}
6 def add_item(self, item_name,quantity):
7 self.items[item_name] = quantity
8 def display_items(self):
9 print(self.items)
10 print(Cart.items)
Output
Example 1
Code
PYTHON
1 class Cart:
2 flat_discount = 0
3 min_bill = 100
4 def __init__(self):
5 self.items = {}
6
7 print(Cart.min_bill)
295
www.spharktechnologies.com
Output
100
Example 2
Code
PYTHON
1 class Cart:
2 flat_discount = 0
3 min_bill = 100
4 def __init__(self):
5 self.items = {}
6 def print_min_bill(self):
7 print(Cart.min_bill)
8
9 a = Cart()
10 a.print_min_bill()
Output
100
Code
PYTHON
1 class Cart:
2 flat_discount = 0
3 min_bill = 100
4 def print_min_bill(self):
5 print(Cart.min_bill)
6 a = Cart()
7 b = Cart()
8 Cart.min_bill = 200
9 print(a.print_min_bill())
( ()) 296
www.spharktechnologies.com
10 print(b.print_min_bill())
Output
200
200
Method
Instance Methods
Class Methods
Static Methods
Instance Methods
Instance methods can access all attributes of the instance and have self as a parameter.
297
www.spharktechnologies.com
Example 1
Code
PYTHON
1 class Cart:
2 def __init__(self):
3 self.items = {}
4 def add_item(self, item_name,quantity):
5 self.items[item_name] = quantity
6 def display_items(self):
7 print(self.items)
8
9 a = Cart()
10 a.add_item("book", 3)
11 a.display_items()
Collapse
Output
{'book': 3}
298
www.spharktechnologies.com
Example 2
Code
PYTHON
1 class Cart:
2 def __init__(self):
3 self.items = {}
4 def add_item(self, item_name,quantity):
5 self.items[item_name] = quantity
6 self.display_items()
7 def display_items(self):
8 print(self.items)
9
10 a = Cart()
11 a.add_item("book", 3)
Collapse
Output
{'book': 3}
Class Methods
Methods which need access to class attributes but not instance attributes are marked as Class
Methods.
For class methods, we send
299
www.spharktechnologies.com
Code
PYTHON
1 class Cart:
2 flat_discount = 0
3 min_bill = 100
4 @classmethod
5 def update_flat_discount(cls,
6 new_flat_discount):
7 cls.flat_discount = new_flat_discount
8
9 Cart.update_flat_discount(25)
10 print(Cart.flat_discount)
Output
25
Code
PYTHON
1 class Cart:
2 flat_discount = 0
3 min_bill = 100
4 @classmethod
5 def update_flat_discount(cls, new_flat_discount):
6 cls.flat_discount = new_flat_discount
7
8 @classmethod
9 def increase_flat_discount(cls, amount):
10 new_flat_discount = cls.flat_discount + amount
11 cls.update_flat_discount(new_flat_discount)
12
13 Cart.increase_flat_discount(50)
14 print(Cart.flat_discount)
Collapse
Output
50
Static Method
We might need some generic methods that don’t need access to either instance or class
attributes. These type of methods are called Static Methods.
Usually, static methods are used to create utility functions which make more sense to be part of
the class.
301
www.spharktechnologies.com
Code
PYTHON
1 class Cart:
2
3 @staticmethod
4 def greet():
5 print("Have a Great Shopping")
6
7 Cart.greet()
Output
302
www.spharktechnologies.com
Can be accessed through object(instance Can be accessed through Can be accessed through
of class) class class
Submit Feedback
303
www.spharktechnologies.com
Inheritance
Products
Lets model e-commerce site having different products like Electronics, Kids Wear, Grocery, etc.
Electronic Item
Grocery Item
304
www.spharktechnologies.com
All these products Electronics, Kids Wear, Grocery etc.. have few common attributes & methods.
305
www.spharktechnologies.com
Also, each product has specific attributes & methods of its own.
Electronic Item & Grocery Item will have all attributes & methods which are common to all
products.
Lets Separate the common attributes & methods as Product
306
www.spharktechnologies.com
Modelling Classes
Reusability
Clear Separation
More Organized
Inheritance
Inheritance is a mechanism by which a class inherits attributes and methods from another class.
ElectronicItem inherit the attributes & methods from Product instead of defining them
again.
307
www.spharktechnologies.com
Super Class
Code
PYTHON
1 class Product:
2 def __init__(self, name, price, deal_price, ratings):
3 self.name = name
4 self.price = price
5 self.deal_price = deal_price
6 self.ratings = ratings
7 self.you_save = price - deal_price
8 def display_product_details(self):
9 print("Product: {}".format(self.name))
10 print("Price: {}".format(self.price))
11 print("Deal Price: {}".format(self.deal_price))
12 print("You Saved: {}".format(self.you_save))
13 print("Ratings: {}".format(self.ratings))
14
15 p = Product("Shoes",500, 250, 3.5)
16 p.display_product_details()
Collapse
Output
Product: Shoes Price: 500 Deal Price: 250 You Saved: 250 Ratings: 3.5
Sub Class
308
www.spharktechnologies.com
The subclass automatically inherits all the attributes & methods from its superclass.
Example 1
Code
PYTHON
1 class Product:
2 def __init__(self, name, price, deal_price, ratings):
3 self.name = name
4 self.price = price
5 self.deal_price = deal_price
6 self.ratings = ratings
7 self.you_save = price - deal_price
8 def display_product_details(self):
9 print("Product: {}".format(self.name))
10 print("Price: {}".format(self.price))
11 print("Deal Price: {}".format(self.deal_price))
12 print("You Saved: {}".format(self.you_save))
13 print("Ratings: {}".format(self.ratings))
14
15 class ElectronicItem(Product):
16 pass
17 class GroceryItem(Product):
18 pass
19
20 e = ElectronicItem("TV",45000, 40000, 3.5)
21 e.display_product_details()
Collapse
Output
Product: TV Price: 45000 Deal Price: 40000 You Saved: 5000 Ratings: 3.5
Example 2
Code
PYTHON
1 class Product:
2 def __init__(self, name, price, deal_price, ratings):
3 self.name = name
4 self.price = price
5 self.deal_price = deal_price
6 self.ratings = ratings
7 self.you_save = price - deal_price
8 def display_product_details(self):
9 print("Product: {}".format(self.name))
10 print("Price: {}".format(self.price))
309
www.spharktechnologies.com
Output
Example 3
Code
PYTHON
1 class Product:
2 def __init__(self, name, price, deal_price, ratings):
3 self.name = name
4 self.price = price
5 self.deal_price = deal_price
6 self.ratings = ratings
7 self.you_save = price - deal_price
8 def display_product_details(self):
9 print("Product: {}".format(self.name))
10 print("Price: {}".format(self.price))
11 print("Deal Price: {}".format(self.deal_price))
12 print("You Saved: {}".format(self.you_save))
13 print("Ratings: {}".format(self.ratings))
14
15 class ElectronicItem(Product):
16 def set_warranty(self, warranty_in_months):
17 self.warranty_in_months = warranty_in_months
18
19 def get_warranty(self):
20 return self.warranty_in_months
21
22 e = ElectronicItem("TV",45000, 40000, 3.5)
23 e.set_warranty(24)
24 print(e.get_warranty())
Collapse
Output
310
www.spharktechnologies.com
24
Code
PYTHON
1 class Product:
2 def __init__(self, name, price, deal_price, ratings):
3 self.name = name
4 self.price = price
5 self.deal_price = deal_price
6 self.ratings = ratings
7 self.you_save = price - deal_price
8 def display_product_details(self):
9 print("Product: {}".format(self.name))
10 print("Price: {}".format(self.price))
11 print("Deal Price: {}".format(self.deal_price))
12 print("You Saved: {}".format(self.you_save))
13 print("Ratings: {}".format(self.ratings))
14
15 class ElectronicItem(Product):
16 def set_warranty(self, warranty_in_months):
17 self.warranty_in_months = warranty_in_months
18
19 def get_warranty(self):
20 return self.warranty_in_months
21
22 p = Product("TV",45000, 40000, 3.5)
23 p.set_warranty(24)
Collapse
Output
311
www.spharktechnologies.com
Code
PYTHON
1 class Product:
2 def __init__(self, name, price, deal_price, ratings):
3 self.name = name
4 self.price = price
5 self.deal_price = deal_price
6 self.ratings = ratings
7 self.you_save = price - deal_price
8 def display_product_details(self):
9 print("Product: {}".format(self.name))
10 print("Price: {}".format(self.price))
11 print("Deal Price: {}".format(self.deal_price))
12 print("You Saved: {}".format(self.you_save))
13 print("Ratings: {}".format(self.ratings))
14
15 class ElectronicItem(Product):
16 def set_warranty(self, warranty_in_months):
17 self.warranty_in_months = warranty_in_months
18
19 def get_warranty(self):
20 return self.warranty_in_months
21
22 e = ElectronicItem("TV",45000, 40000, 3.5)
23 e.set_warranty(24)
24 e.display_product_details()
Collapse
Output
Product: TV Price: 45000 Deal Price: 40000 You Saved: 5000 Ratings: 3.5
We can call methods defined in superclass from the methods in the subclass.
Code
PYTHON
312
www.spharktechnologies.com
PYTHON
1 class Product:
2 def __init__(self, name, price, deal_price, ratings):
3 self.name = name
4 self.price = price
5 self.deal_price = deal_price
6 self.ratings = ratings
7 self.you_save = price - deal_price
8 def display_product_details(self):
9 print("Product: {}".format(self.name))
10 print("Price: {}".format(self.price))
11 print("Deal Price: {}".format(self.deal_price))
12 print("You Saved: {}".format(self.you_save))
13 print("Ratings: {}".format(self.ratings))
14
15 class ElectronicItem(Product):
16 def set_warranty(self, warranty_in_months):
17 self.warranty_in_months = warranty_in_months
18
19 def get_warranty(self):
20 return self.warranty_in_months
21
22 def display_electronic_product_details(self):
23 self.display_product_details()
24 print("Warranty {} months".format(self.warranty_in_months))
25
26 e = ElectronicItem("TV",45000, 40000, 3.5)
27 e.set_warranty(24)
28 e.display_electronic_product_details()
Collapse
Output
Product: TV Price: 45000 Deal Price: 40000 You Saved: 5000 Ratings: 3.5 Warranty 24 months
Submit Feedback
313
www.spharktechnologies.com
Inheritance - Part 2
How would you design and implement placing order with the details of all the
products bought?
Composition
Code
PYTHON
1 class Product:
2
3 def __init__(self, name, price, deal_price, ratings):
4 self.name = name
5 self.price = price
6 self.deal_price = deal_price
7 self.ratings = ratings
8 self.you_save = price - deal_price
9
10 def display_product_details(self):
11 print("Product: {}".format(self.name))
12 print("Price: {}".format(self.price))
13 print("Deal Price: {}".format(self.deal_price))
14 print("You Saved: {}".format(self.you_save))
15 print("Ratings: {}".format(self.ratings))
16
17 def get_deal_price(self):
18 return self.deal_price
19
20 class ElectronicItem(Product):
21 def set_warranty(self, warranty_in_months):
22 self.warranty_in_months = warranty_in_months
23
24 def get_warranty(self):
25 return self.warranty_in_months
26
27 class GroceryItem(Product):
28 pass
29
30 class Order:
31 def __init__(self, delivery_speed, delivery_address):
32 self.items_in_cart = []
314
www.spharktechnologies.com
33 self.delivery_speed = delivery_speed
34 self.delivery_address = delivery_address
35
36 def add_item(self, product, quantity):
37 self.items_in_cart.append((product, quantity))
38
39 def display_order_details(self):
40 for product, quantity in self.items_in_cart:
41 product.display_product_details()
42 print("Quantity: {}".format(quantity))
43
44 def display_total_bill(self):
45 total_bill = 0
46 for product, quantity in self.items_in_cart:
47 price = product.get_deal_price() * quantity
48 total_bill += price
49 print("Total Bill: {}".format(total_bill))
50
51 milk = GroceryItem("Milk",40, 25, 3.5)
52 tv = ElectronicItem("TV",45000, 40000, 3.5)
53 order = Order("Prime Delivery", "Hyderabad")
54 order.add_item(milk, 2)
55 order.add_item(tv, 1)
56 order.display_order_details()
57 order.display_total_bill()
Collapse
Output
Product: Milk
Price: 40
Deal Price: 25
You Saved: 15
Ratings: 3.5
Quantity: 2
Product: TV
Price: 45000
Deal Price: 40000
You Saved: 5000
Ratings: 3.5
Quantity: 1
Total Bill: 40050
Collapse
315
www.spharktechnologies.com
Overriding Methods
Sometimes, we require a method in the instances of a sub class to behave differently from the
method in instance of a superclass.
Code
PYTHON
1 class Product:
2
3 def __init__(self, name, price, deal_price, ratings):
4 self.name = name
5 self.price = price
6 self.deal_price = deal_price
7 self.ratings = ratings
8 self.you_save = price - deal_price
9
10 def display_product_details(self):
11 print("Product: {}".format(self.name))
12 print("Price: {}".format(self.price))
13 print("Deal Price: {}".format(self.deal_price))
14 print("You Saved: {}".format(self.you_save))
15 print("Ratings: {}".format(self.ratings))
16
17 def get_deal_price(self):
18 return self.deal_price
19
20 class ElectronicItem(Product):
21
22 def display_product_details(self):
23 self.display_product_details()
24 print("Warranty {} months".format(self.warranty_in_months))
25
26 def set_warranty(self, warranty_in_months):
27 self.warranty_in_months = warranty_in_months
28
29 def get_warranty(self):
30 return self.warranty_in_months
31
32 e = ElectronicItem("Laptop",45000, 40000,3.5)
33 e.set_warranty(10)
34 e.display_product_details()
Collapse
Output
316
www.spharktechnologies.com
Because
Super
super() allows us to call methods of the superclass (Product) from the subclass.
Instead of writing and methods to access and modify warranty we can override
__init__
Code
PYTHON
1 class Product:
2
3 def __init__(self, name, price, deal_price, ratings):
4 self.name = name
5 self.price = price
6 self.deal_price = deal_price
7 self.ratings = ratings
8 self.you_save = price - deal_price
9
10 def display_product_details(self):
11 print("Product: {}".format(self.name))
12 print("Price: {}".format(self.price))
13 print("Deal Price: {}".format(self.deal_price))
14 print("You Saved: {}".format(self.you_save))
15 print("Ratings: {}".format(self.ratings))
16
17 def get_deal_price(self):
18 return self.deal_price
19
20 class ElectronicItem(Product):
21
22 def display_product_details(self):
317
www.spharktechnologies.com
23 super().display_product_details()
24 print("Warranty {} months".format(self.warranty_in_months))
25
26 def set_warranty(self, warranty_in_months):
27 self.warranty_in_months = warranty_in_months
28
29 def get_warranty(self):
30 return self.warranty_in_months
31
32 e = ElectronicItem("Laptop",45000, 40000,3.5)
33 e.set_warranty(10)
34 e.display_product_details()
Collapse
Output
Product: Laptop
Price: 45000
Deal Price: 40000
You Saved: 5000
Ratings: 3.5
Warranty 10 months
MultiLevel Inheritance
318
www.spharktechnologies.com
PYTHON
1 class Product:
2 pass
3
4 class ElectronicItem(Product):
5 pass
6
7 class Laptop(ElectronicItem):
8 pass
Prefer modeling with inheritance when the classes have an IS-A relationship.
319
www.spharktechnologies.com
320
www.spharktechnologies.com
Prefer modeling with inheritance when the classes have an HAS-A relationship.
Submit Feedback
321
www.spharktechnologies.com
Standard Library
Built-in Functions
1. print()
2. max()
3. min()
Standard Library
Python provides several such useful values (constants), classes and functions.
322
www.spharktechnologies.com
1. collections
2. random
3. datetime
1 import module_name
Math Module
323
www.spharktechnologies.com
math module provides us to access some common math functions and constants.
Code
PYTHON
1 import math
2 print(math.factorial(5))
3 print(math.pi)
Output
324
www.spharktechnologies.com
120
3.141592653589793
Importing module
Code
PYTHON
1 import math as m1
2 print(m1.factorial(5))
Output
120
325
www.spharktechnologies.com
Code
PYTHON
Output
120
Aliasing Imports
Code
PYTHON
Output
326
www.spharktechnologies.com
120
Random module
327
www.spharktechnologies.com
Randint
Code
PYTHON
1 import random
2 random_integer = random.randint(1, 10)
328
www.spharktechnologies.com
3 print(random_integer)
Output
Choice
choice() is a function in random module which returns a random element from the
sequence.
Code
PYTHON
1 import random
2 random_ele = random.choice(["A","B","C"])
3 print(random_ele)
Output
329
www.spharktechnologies.com
To know more about Python Standard Library, go through the authentic python
documentation
- https://docs.python.org/3/library/
Map
map() applies a given function to each item of a sequence (list, tuple etc.) and
returns a sequence of the results.
330
www.spharktechnologies.com
Example - 1
Code
PYTHON
1 def square(n):
2 return n * n
3 numbers = [1, 2, 3, 4]
4 result = map(square, numbers)
5 numbers_square = list(result)
6 print(numbers_square)
Output
331
www.spharktechnologies.com
[1, 4, 9, 16]
Example - 2
Code
PYTHON
Input
1 2 3 4
Output
[1, 2, 3, 4]
332
www.spharktechnologies.com
Filter
filter() method filters the elements of a given sequence based on the result of
given function.
Code
333
www.spharktechnologies.com
PYTHON
1 def is_positive_number(num):
2 return num > 0
3
4 list_a = [1, -2, 3, -4]
5 positive_nums = filter(is_positive_number, list_a)
6 print(list(positive_nums))
Output
[1, 3]
Reduce
reduce() function is defined in the functools module.
334
www.spharktechnologies.com
Code
PYTHON
1 from functools import reduce
2
3 def sum_of_num(a, b):
4 return a+b
5
6 list_a = [1, 2, 3, 4]
7 sum_of_list = reduce(sum_of_num, list_a)
335
www.spharktechnologies.com
8 print(sum_of_list)
Output
10
Submit Feedback
336
www.spharktechnologies.com
Object
Strings, Integers, Floats, Lists, Functions, Module etc. are all objects.
Identity of an Object
Whenever an object is created in Python, it will be given a unique identifier (id).This unique id can be different for
each time you run the program.
337
www.spharktechnologies.com
Every object that you use in a Python Program will be stored in Computer Memory
The unique id will be related to the location where the object is stored in the Computer Memory.
Name of an Object
Namespaces
A namespace is a collection of currently defined names along with information about the object that the name
references.
It ensures that names are unique and won’t lead to any conflict.
338
www.spharktechnologies.com
Namespaces allow us to have the same name referring different things in different namespaces.
Code
PYTHON
1 def greet_1():
2 a = "Hello"
3 print(a)
4 print(id(a))
5
6 def greet_2():
7 a = "Hey"
8 print(a)
9 print(id(a))
10
11 print("Namespace - 1")
12 greet_1()
13 print("Namespace - 2")
14 greet_2()
Collapse
Output
Namespace - 1
Hello
140639382368176
339
www.spharktechnologies.com
Namespace - 2
Hey
140639382570608
Types of namespaces
As Python executes a program, it creates namespaces as necessary and forgets them when they are no longer needed.
1. Built-in
2. Global
3. Local
Built-in Namespace
Created when we start executing a Python program and exists as long as the program is running.
This is the reason that built-in functions like id(), print() etc. are always available to us from any part of the program.
Global Namespace
This namespace includes all names defined directly in a module (outside of all functions).
It is created when the module is loaded, and it lasts until the program ends.
340
www.spharktechnologies.com
Local Namespace
A new local namespace is created when a function is called, which lasts until the function returns.
341
www.spharktechnologies.com
Scope of a Name
The scope of a name is the region of a program in which that name has meaning.
Python searches for a name from the inside out, looking in the
342
www.spharktechnologies.com
Global variables
Example 1
Code
PYTHON
1 x = "Global Variable"
2 print(x)
3
4 def foo():
5 print(x)
6
7 foo()
Output
Global Variable
Global Variable
343
www.spharktechnologies.com
Example 2
Code
PYTHON
1 def foo():
2 print(x)
3
4 x = "Global Variable"
5
6 foo()
Output
Global Variable
Local Variables
This variable name will be part of the Local Namespace which will be created when the function is called and lasts until
the function returns.
Code
PYTHON
1 def foo():
2 x = "Local Variable"
3 print(x)
4
344
www.spharktechnologies.com
4
5 foo()
6 print(x)
Output
Local Variable
NameError: name 'x' is not defined
As,
Local Import
Code
PYTHON
1 def foo():
2 import math
3 print(math.pi)
4
5 foo()
6 print(math.pi)
Output
3.141592653589793
NameError: name 'math' is not defined
Code
PYTHON
1 x = "Global Variable"
2
3 def foo():
4 x = "Local Variable"
5 print(x)
6
7 print(x)
8 foo()
9 print(x)
Output
345
www.spharktechnologies.com
Global Variable
Local Variable
Global Variable
global keyword is used to define a name to refer to the value in Global Namespace.
Code
PYTHON
1 x = "Global Variable"
2
3 def foo():
4 global x
5 x = "Global Change"
6 print(x)
7
8 print(x)
9 foo()
10 print(x)
Output
Global Variable
Global Change
Global Change
Submit Feedback
346
www.spharktechnologies.com
1. Syntax Errors
2. Exceptions
Syntax Errors
Syntax errors are parsing errors which occur when the code is not adhering to Python
Syntax.
Code
PYTHON
1 if True print("Hello")
Output
When there is a syntax error, the program will not execute even if that part of code is not
used.
Code
PYTHON
1 print("Hello")
2
3 def greet():
4 print("World"
347
www.spharktechnologies.com
Output
Notice that in the above code, the syntax error is inside the
Exceptions
Even when a statement or expression is syntactically correct, it may cause an error when
an attempt is made to execute it.
Example Scenario
Example 1
Division Example
Code
348
www.spharktechnologies.com
PYTHON
Output
Example 2
Code
PYTHON
1
2 def divide(a, b):
3 return a / b
4
5 divide("5", "10")
Output
Example 3
Consider the following code, which is used to update the quantity of items in store.
Code
PYTHON
1 class Store:
2 def init (self):
349
www.spharktechnologies.com
2 def __init__(self):
3 self.items = {
4 "milk" : 20, "bread" : 30, }
5
6 def add_item(self, name, quantity):
7 self.items[name] += quantity
8
9 s = Store()
10 s.add_item('biscuits', 10)
Output
KeyError: 'biscuits'
What happens when your code runs into an exception during execution?
End-User Applications
When you develop applications that are directly used by end-users, you need to handle
different possible exceptions in your code so that the application will not crash.
Reusable Modules
When you develop modules that are used by other developers, you should raise exceptions
for different scenarios so that other developers can handle them.
350
www.spharktechnologies.com
Let’s consider we are creating an app that allows users to transfer money between them.
Example 1
Code
PYTHON
1 class BankAccount:
2 def __init__(self, account_number):
3 self.account_number = str(account_number)
4 self.balance = 0
5
6 def get_balance(self):
7 return self.balance
351
www.spharktechnologies.com
8
9 def withdraw(self, amount):
10 if self.balance >= amount:
11 self.balance -= amount
12 else:
13 print("Insufficient Funds")
14
15 def deposit(self, amount):
16 self.balance += amount
17
18
19 def transfer_amount(acc_1, acc_2, amount):
20 acc_1.withdraw(amount)
21 acc_2.deposit(amount)
22
23
24 user_1 = BankAccount("001")
25 user_2 = BankAccount("002")
26 user_1.deposit(250)
27 user_2.deposit(100)
28
29 print("User 1 Balance: {}/-".format(user_1.get_balance()))
30 print("User 2 Balance: {}/-".format(user_2.get_balance()))
31 transfer_amount(user_1, user_2, 50)
32 print("Transferring 50/- from User 1 to User 2")
33 print("User 1 Balance: {}/-".format(user_1.get_balance()))
34 print("User 2 Balance: {}/-".format(user_2.get_balance()))
Collapse
Output
Example 2
352
www.spharktechnologies.com
Code
PYTHON
1 class BankAccount:
2 def __init__(self, account_number):
3 self.account_number = str(account_number)
4 self.balance = 0
5
6 def get_balance(self):
7 return self.balance
8
9 def withdraw(self, amount):
10 if self.balance >= amount:
11 self.balance -= amount
12 else:
13 print("Insufficient Funds")
14
15 def deposit(self, amount):
16 self.balance += amount
17
18
19 def transfer_amount(acc_1, acc_2, amount):
20 acc_1.withdraw(amount)
21 acc_2.deposit(amount)
22
23
24 user_1 = BankAccount("001")
25 user_2 = BankAccount("002")
26 user_1.deposit(25)
27 user_2.deposit(100)
28
353
www.spharktechnologies.com
Collapse
Output
Raising Exceptions
When your code enters an unexpected state, raise an exception to communicate it.
Built-in Exceptions
You can use the built-in exception classes with raise keyword to raise an exception in the
program.
Code
Output
ValueError:Unexpected Value!!
Example 1
355
www.spharktechnologies.com
Code
PYTHON
1 class BankAccount:
2 def __init__(self, account_number):
3 self.account_number = str(account_number)
4 self.balance = 0
5
6 def get_balance(self):
7 return self.balance
8
9 def withdraw(self, amount):
10 if self.balance >= amount:
11 self.balance -= amount
12 else:
13 raise ValueError("Insufficient Funds")
14
15 def deposit(self, amount):
16 self.balance += amount
17
18
19 def transfer_amount(acc_1, acc_2, amount):
20 acc_1.withdraw(amount)
21 acc_2.deposit(amount)
22
23
24 user_1 = BankAccount("001")
25 user_2 = BankAccount("002")
26 user_1.deposit(25)
27 user 2 deposit(100)
356
www.spharktechnologies.com
27 user_2.deposit(100)
28
29 print("User 1 Balance: {}/-".format(user_1.get_balance()))
30 print("User 2 Balance: {}/-".format(user_2.get_balance()))
31 transfer_amount(user_1, user_2, 50)
32 print("Transferring 50/- from User 1 to User 2")
33 print("User 1 Balance: {}/-".format(user_1.get_balance()))
34 print("User 2 Balance: {}/-".format(user_2.get_balance()))
Collapse
Output
Handling Exceptions
Python provides a way to catch the exceptions that were raised so that they can be properly
handled.
Whenever an exception occurs at some line in try block, the execution stops at that line
and jumps to except block.
PYTHON
1 try:
2 # Write code that
3 # might cause exceptions.
4 except:
5 # The code to be run when
6 # there is an exception.
Transfer Amount
Example 1
357
www.spharktechnologies.com
Code
PYTHON
1 class BankAccount:
2 def __init__(self, account_number):
3 self.account_number = str(account_number)
4 self.balance = 0
5
6 def get_balance(self):
7 return self.balance
8
9 def withdraw(self, amount):
10 if self.balance >= amount:
11 self.balance -= amount
12 else:
13 raise ValueError("Insufficient Funds")
14
15 def deposit(self, amount):
16 self.balance += amount
17
18
19 def transfer_amount(acc_1, acc_2, amount):
20 try:
21 acc_1.withdraw(amount)
22 acc_2.deposit(amount)
23 return True
24 except:
25 return False
26
27
28 user_1 = BankAccount("001")
29 user_2 = BankAccount("002")
30 user 1 deposit(25)
358
www.spharktechnologies.com
30 user_1.deposit(25)
31 user_2.deposit(100)
32
33 print("User 1 Balance: {}/-".format(user_1.get_balance()))
34 print("User 2 Balance: {}/-".format(user_2.get_balance()))
35 print(transfer_amount(user_1, user_2, 50))
36 print("Transferring 50/- from User 1 to User 2")
37 print("User 1 Balance: {}/-".format(user_1.get_balance()))
38 print("User 2 Balance: {}/-".format(user_2.get_balance()))
Collapse
Output
Summary
Reusable Modules
While developing reusable modules, we need to raise Exceptions to stop our code from
being used in a bad way.
End-User Applications
We can specifically mention the name of exception to catch all exceptions of that specific
type.
Syntax
PYTHON
1 try:
359
www.spharktechnologies.com
1 try:
2 # Write code that
3 # might cause exceptions.
4 except Exception:
5 # The code to be run when
6 # there is an exception.
Example 1
Code
PYTHON
1 try:
2 a = int(input())
3 b = int(input())
4 c = a/b
5 print(c)
6 except ZeroDivisionError:
7 print("Denominator can't be 0")
8 except:
9 print("Unhandled Exception")
Input
5
0
Output
Denominator can't be 0
Example 2
Code
PYTHON
1 try:
360
www.spharktechnologies.com
2 a = int(input())
3 b = int(input())
4 c = a/b
5 print(c)
6 except ZeroDivisionError:
7 print("Denominator can't be 0")
8 except:
9 print("Unhandled Exception")
Input
12
a
Output
Unhandled Exception
Syntax
PYTHON
1 try:
2 # Write code that
3 # might cause exceptions.
4 except Exception as e:
5 # The code to be run when
6 # there is an exception.
Code
PYTHON
1 class BankAccount:
2 def __init__(self, account_number):
3 self.account_number = str(account_number)
4 self.balance = 0
5
361
www.spharktechnologies.com
5
6 def get_balance(self):
7 return self.balance
8
9 def withdraw(self, amount):
10 if self.balance >= amount:
11 self.balance -= amount
12 else:
13 raise ValueError("Insufficient Funds")
14
15 def deposit(self, amount):
16 self.balance += amount
17
18
19 def transfer_amount(acc_1, acc_2, amount):
20 try:
21 acc_1.withdraw(amount)
22 acc_2.deposit(amount)
23 return True
24 except ValueError as e:
25 print(str(e))
26 print(type(e))
27 print(e.args)
28 return False
29
30 user_1 = BankAccount("001")
31 user_2 = BankAccount("002")
32 user_1.deposit(25)
33 user_2.deposit(100)
34
35 print("User 1 Balance: {}/-".format(user_1.get_balance()))
36 print("User 2 Balance: {}/-".format(user_2.get_balance()))
37 print(transfer_amount(user_1, user_2, 50))
38 print("Transferring 50/- from User 1 to User 2")
39 print("User 1 Balance: {}/-".format(user_1.get_balance()))
40 print("User 2 Balance: {}/-".format(user_2.get_balance()))
Collapse
Output
We can write multiple exception blocks to handle different types of exceptions differently.
Syntax
PYTHON
1 try:
2 # Write code that
3 # might cause exceptions.
4 except Exception1:
5 # The code to be run when
6 # there is an exception.
7 except Exception2:
8 # The code to be run when
9 # there is an exception.
Example 1
Code
PYTHON
1 try:
2 a = int(input())
3 b = int(input())
4 c = a/b
5 print(c)
6 except ZeroDivisionError:
7 print("Denominator can't be 0")
8 except ValueError:
9 print("Input should be an integer")
10 except:
11 print("Something went wrong")
Collapse
Input
363
www.spharktechnologies.com
5
0
Output
Denominator can't be 0
Example 2
Code
PYTHON
1 try:
2 a = int(input())
3 b = int(input())
4 c = a/b
5 print(c)
6 except ZeroDivisionError:
7 print("Denominator can't be 0")
8 except ValueError:
9 print("Input should be an integer")
10 except:
11 print("Something went wrong")
Collapse
Input
12
a
Output
364
www.spharktechnologies.com
Datetime
Python has a built-in datetime module which provides convenient objects to work
with dates and times.
Code
PYTHON
1 import datetime
Datetime classes
date class
time class
datetime class
timedelta class
Representing Date
A date object can be used to represent any valid date (year, month and day).
Code
365
www.spharktechnologies.com
PYTHON
1 import datetime
2
3 date_object = datetime.date(2019, 4, 13)
4 print(date_object)
Output
2019-04-13
Date Object
Code
PYTHON
Output
Today’s Date
Class method
Code
PYTHON
1 import datetime
2
3 date object datetime date today()
366
www.spharktechnologies.com
3 date_object = datetime.date.today()
4 print(date_object)
Output
2021-02-05
Code
PYTHON
Output
2019
4
13
Representing Time
A time object can be used to represent any valid time (hours, minutes and seconds).
Code
PYTHON
1 from datetime import time
367
www.spharktechnologies.com
1 from datetime import time
2
3 time_object = time(11, 34, 56)
4 print(time_object)
Output
11:34:56
Code
PYTHON
Output
11:34:56
11
34
56
Datetime
368
www.spharktechnologies.com
Example - 1
Code
PYTHON
Output
2018
11
10
15
Example - 2
It gives the current date and time
Code
PYTHON
1 import datetime
2
3 datetime_object = datetime.datetime.now()
4 print(datetime_object)
Output
2021-02-05 09:26:08.077473
DateTime object
369
www.spharktechnologies.com
Code
PYTHON
Output
2018-11-28 00:00:00
Formatting Datetime
strftime(format) method to format the datetime into any required format like
mm/dd/yyyy
dd-mm-yyyy
Sunday, Monday,
%A Weekday as full name
...
Hour (24-hour clock) as a zero-padded
%H 00, 01, …, 23
decimal number
Hour (12-hour clock) as a zero-padded
%I 01, 02, …, 12
decimal number
370
www.spharktechnologies.com
%p AM or PM AM, PM
Code
PYTHON
Output
Parsing Datetime
strptime() creates a datetime object from a given string representing date and
time.
Code
PYTHON
1 from datetime import datetime
2
3 date_string = "28 November, 2018"
4 print(date_string)
5
6 date_object = datetime.strptime(date_string, "%d %B, %Y")
371
www.spharktechnologies.com
7 print(date_object)
Output
28 November, 2018
2018-11-28 00:00:00
Example 1
Code
PYTHON
Output
Example 2
Code
PYTHON
1 from datetime import timedelta, datetime
2 delta = timedelta(days=365)
3 current_datetime = datetime.now()
4 print(current_datetime)
5 next_year_datetime = current_datetime + delta
372
www.spharktechnologies.com
6 print(next_year_datetime)
Output
2021-02-05 09:28:30.239095
2022-02-05 09:28:30.239095
Code
PYTHON
1 import datetime
2
3 dt1 = datetime.datetime(2021, 2, 5)
4 dt2 = datetime.datetime(2022, 1, 1)
5 duration = dt2 - dt1
6 print(duration)
7 print(type(duration))
Output
Submit Feedback
373