0% found this document useful (0 votes)
4 views373 pages

Python Notes

The document provides an introduction to programming with Python, explaining key concepts such as software, programming, code, and syntax. It highlights Python's ease of learning, versatility in applications across various fields, and career opportunities for Python developers. Additionally, it covers fundamental programming topics including variables, data types, operations, and common mistakes in Python coding.

Uploaded by

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

Python Notes

The document provides an introduction to programming with Python, explaining key concepts such as software, programming, code, and syntax. It highlights Python's ease of learning, versatility in applications across various fields, and career opportunities for Python developers. Additionally, it covers fundamental programming topics including variables, data types, operations, and common mistakes in Python coding.

Uploaded by

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

www.spharktechnologies.

com

Intro to Programming with Python


Software

Software is a set of instructions to the hardware.

Programming

Programming means writing the instructions to create a software.

Code

The instructions that we write to create software is called 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

Python is a versatile language which has applications in almost every field

Artificial intelligence (AI)

Machine Learning (ML)

Big Data

Smart Devices/Internet of Things (IoT)

Cyber Security

Game Development

Backend Development, etc.


2
www.spharktechnologies.com

Career Opportunities

Python developers have plenty of opportunities across the world

DevOps Engineer

Software Developer

Data Analyst

Data Scientist

Machine Learning (ML) Engineer

AI Scientist, etc.

Hello World Program in Python

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"

Spelling Mistake in print


PYTHON

1 prnt("Hello World!")

Uppercase ‘P’ in Print


PYTHON

1 Print("Hello World!")

Missing quotes
PYTHON

1 print(Hello World!)

4
www.spharktechnologies.com

Missing parentheses
PYTHON

1 print("Hello World!"

Printing Without Quotes

If we want to print the numerical result of 2 + 5, we do not add quotes.

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

Calculations with python

Addition

Addition is denoted by

+ sign. It gives the sum of two numbers.

Code
PYTHON

1 print(2 + 5)
2 print(1 + 1.5)

Output

6
www.spharktechnologies.com

7
2.5

Subtraction

Subtraction is denoted by

- sign. It gives the difference between two numbers.

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

Variables and Data Types


Variables

Variables are like containers for storing values.


Values in the variables can be changed.

Values

Consider that variables are like containers for storing information.


In context of programming, this information is often referred to as value.

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

A String is a stream of characters enclosed within quotes.


Stream of Characters

Capital Letters ( A – Z )

Small Letters ( a – z )

Digits ( 0 – 9 )

Special Characters (~ ! @ # $ % ^ . ?,)

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

...-3, -2, -1, 0, 1, 2, 3,...

Float

10
www.spharktechnologies.com

Any number with a decimal point

24.3, 345.210, -321.86

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.

As per the Python Syntax,

True and False are considered as Boolean values. Notice that both start with a capital letter.

Assigning Value to Variable

The following is the syntax for assigning an integer value

10 to a variable age
PYTHON

1 age = 10

Here the equals to


11
www.spharktechnologies.com

= sign is called as Assignment Operator as it is used to assign values to variables.

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

Printing Value in a Variable

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

Python executes the code line-by-line.

14
www.spharktechnologies.com

Code
PYTHON

1 print(age)
2 age = 10

Output

NameError: name 'age' is not defined

Variable

age is not created by the time we tried to print.

Spacing in Python

Having spaces at the beginning of line causes errors.

Code
PYTHON

1 a = 10 * 5
2 b = 5 * 0.5
3 b = a + b

15
www.spharktechnologies.com

Output

File "main.py", line 3


b = a + b
^
IndentationError: unexpected indent

Variable Assignment

Values in the variables can be changed.

Code
PYTHON

1 a = 1
2 print(a)
3 a = 2
4 print(a)

Output

1
2

16
www.spharktechnologies.com

Examples of Variable Assignment

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

An expression is a valid combination of values, variables and operators.

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

Inputs and Outputs Basics

Take Input From User

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

Working with Strings

String Concatenation

Joining strings together is called string concatenation.

Code
PYTHON

1 a = "Hello" + " " + "World"


2 print(a)

Output

Hello World

19
www.spharktechnologies.com

Concatenation Errors

String Concatenation is possible only with strings.

Code
PYTHON

1 a = "*" + 10
2 print(a)

Output

File "main.py", line 1


a = "*" + 10
^
TypeError:
can only concatenate str (not "int") to str

String Repetition

* operator is used for repeating strings any number of times as required.

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

len() returns the number of characters in a given 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

Attempting to use an index that is too large will result in an error:

Code
PYTHON

1 username = "Ravi"
2 print(username[4])

Output

IndexError: string index out of range

Submit Feedback

22
www.spharktechnologies.com

Type Conversion

String Slicing

Obtaining a part of a string is called string slicing.

Code
PYTHON

1 variable_name[start_index:end_index]

Start from the start_index and stops at end_index

end_index is not included in the slice.

Code
PYTHON

1 message = "Hi Ravi"


2 part = message[3:7]
3 print(part)

Output

Ravi

Slicing to End

If end index is not specified, slicing stops at the end of the string.

Code
PYTHON

1 message = "Hi Ravi"


2 part = message[3:]
3 print(part)

Output

23
www.spharktechnologies.com

Ravi

Slicing from Start

If start index is not specified, slicing starts from the index 0.

Code
PYTHON

1 message = "Hi Ravi"


2 part = message[:2]
3 print(part)

Output

Hi

Checking Data Type

Check the datatype of the variable or value using

type()

Printing Data 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

Float to String and so on.

String to Integer

int() converts valid data of any type to integer

Code
PYTHON

1 a = "5"
2 a = int(a)
3 print(type(a))
4 print(a)

Output

<class 'int'>
5

Invalid Integer Conversion

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

invalid literal for int() with base 10: '5.0'

Adding Two Numbers

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

str() converts data of any type to a 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

1. int() -> Converts to integer data type


2. float() -> Converts to float data type
3. str() -> Converts to string data type
4. bool() -> Converts to boolean data type

27
www.spharktechnologies.com

Relational Operators
Relational Operators are used to compare values.
Gives

True or False as the result of a comparison.

These are different relational operators

Operator Name

> Is greater than

< Is less than

== Is equal to

<= Is less than or equal to

>= Is greater than or equal to

!= Is not equal to

Code
PYTHON

1 print(5 < 10)


2 print(2 > 1)

Output

True
True

28
www.spharktechnologies.com

Possible Mistakes

Mistake - 1

Code
PYTHON

1 print(3 = 3)

Output

SyntaxError: expression cannot contain assignment, perhaps you meant

Mistake - 2

Code
PYTHON

1 print(2 < = 3)

Output

SyntaxError: invalid syntax

Space between relational operators

== , >= , <= , != is not valid in Python.

Comparing Numbers

29
www.spharktechnologies.com

Code
PYTHON

1 print(2 <= 3)
2 print(2.53 >= 2.55)

Output

True
False

Comparing Integers and Floats

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

Python is case sensitive.


It means

X (Capital letter) and x (small letter) are not the same in Python.

Strings and Equality Operator


Code
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

True or False as the result.

Following are the logical operators

and
or
not

Logical AND Operator

Gives

True if both the booleans are true else, it gives False

Code
PYTHON

1 print(True and True)

Output

True

Examples of Logical AND

Code
PYTHON

1 print((2 < 3) and (1 < 2))


33
www.spharktechnologies.com

Step by Step Explanation

(2 < 3) and (1 < 2)


True and (1 < 2)
True and True

Output

True

Logical OR Operator

Gives

True if any one of the booleans is true else, it gives False

Code
PYTHON

1 print(False or False)

Output

False

Examples of Logical OR

Code

34
www.spharktechnologies.com

PYTHON

1 print((2 < 3) or (2 < 1))

Step by Step Explanation

(2 < 3) or (2 < 1)
True or (2 < 1)
True or False

Output

True

Logical NOT Operator

Gives the opposite value of the given boolean.

Code
PYTHON

1 print(not(False))

Output

True

Examples of Logical NOT

35
www.spharktechnologies.com

Code
PYTHON

1 print(not(2 < 3))

Step by Step Explanation

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

A sequence of instructions are called block of code.


Python executes code in a sequence.

Condition

An expression that results in either

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

Block of code which executes only if a condition is

True is called Conditional Block.

Indentation

Space(s) in front of the conditional block is called indentation.


Indentation(spacing) is used to identify Conditional Block.
Standard practice is to use four spaces for 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

IndentationError: unexpected indent

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

Possible Mistakes in If-Else

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

SyntaxError: invalid syntax

Warning

Note: No code is allowed in between if conditional block and else statement.

41
www.spharktechnologies.com

Cheat Sheet

More Arithmetic Operators

Modulus

To find the remainder, we use Modulus operator

a%b

Code
PYTHON

1 print(6 % 3)

Output

Exponent

To calculate a power b, we use Exponent Operator

**

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 Conditional Statements

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

Nested Condition in Else Block

We can also write nested conditions in Else Statement.

In the below example Block 2 is a nested conditional block.

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.

The elif statement is optional.

Multiple Elif Statements

We can add any number of

elif statements after if conditional block.

47
www.spharktechnologies.com

Execution of Elif Statement

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

Optional Else Statement

Else statement is not compulsory after

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

Cannot write an elif statement after

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

Allows us to execute a block of code several times as long as the condition is

True .

While Loop Example

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

NameError: name 'counter' is not defined

2. Incorrect Termination Condition

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

The above code runs into an infinite loop.

While block will keep repeating as the value in condition variable is

True .

3. Not Updating Counter Variable

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

As the value of counter is not updating.

54
www.spharktechnologies.com

Cheat Sheet

For Loop

for statement iterates over each item of a sequence.

Examples of sequences:

Sequence of Characters (string)

Sequence of numbers, etc.

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

Generates a sequence of integers starting from 0.


Syntax:

range(n) Stops before n (n is not included).

Code

PYTHON
1 for number in range(3):
2 i t( b ) 56
www.spharktechnologies.com

2 print(number)

Output

0
1
2

Range with Start and End

Generates a sequence of numbers starting from

start
Syntax: range(start, end) Stops before end (end is not included).

Code
PYTHON

1 for number in range(5, 8):


2 print(number)

Output

5
57
www.spharktechnologies.com

6
7

Submit Feedback

58
www.spharktechnologies.com

59
www.spharktechnologies.com

Approach for Hollow pattern | Cheat Sheet

Approach for Hollow pattern problem

In this cheat sheet, let's see how to print the Hollow right-angled triangle pattern

Below is the pattern of the Hollow right-angled triangle

*
* *
* *
* *
* *
* *
* * * * * * *

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 ('* ').

While writing the code,

you need to print * as '* '(star followed by space).

you need to print 2 spaces(' ') in place of a single space.

61
www.spharktechnologies.com

The above image is the 7x7 pattern of the hollow right-angled triangle

The first row has 6 spaces and has one star.

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.

The last row has 7 stars.

Here in this problem

space is denoted as the ' ' ( Double Spaces)

star set denoted as the '* ' (Star is followed by space)

Let's now discuss line by line

Pattern Line Number Number of Spaces

* First line 6 Double spaces 1st star

** Second line 5 Double spaces 1st star-set('* ') 2nd 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

* * * * * * * Seventh line 0 Double spaces 7 star-sets('* ')

62
www.spharktechnologies.com

Now, let's see how to print the above pattern using a python program.

We can divide the above pattern logic into 3 parts

Part 1: we have spaces and star('*') in first line

Part 2: we have spaces, star, hollow spaces, star (middle lines)

Part 3: we have star set('* ') in the last line

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

18 print(left_spaces + '* ' + hollow_spaces + '*')

Collapse

Now let's see the explanation of the for loop execution, step by step:

Part - 1 (first line):

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.

spaces = ' ' * (N-1) = 6 // Here N value is 7

Output is

1 *

Part - 2 (logic to print the Second line to Sixth line):

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

spaces = ' ' * (N-i-1) = 5


hollow_spaces = (' ' * ( i - 1)) = 0

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.

spaces = ' ' * (N-i-1) = 4


hollow_spaces = (' ' * ( i - 1)) = 1

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.

spaces = ' ' * (N-i-1) = 3


hollow_spaces = (' ' * ( i - 1)) = 2

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

order to get 2 no.of spaces, we must subtract 1 and


i value from the N value.

spaces = ' ' * (N-i-1) = 2


hollow_spaces = (' ' * ( i - 1)) = 3

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.

spaces = ' ' * (N-i-1) = 1


hollow_spaces = (' ' * ( i - 1)) = 4

67
www.spharktechnologies.com

Output is

*
* *
* *
* *
* *
* *

Part - 3 (Seventh line):

i=6

stars = '* ' * N

Output is

*
* *
* *
* *
* *
* * 68
www.spharktechnologies.com

* *
* * * * * * *

Submit Feedback

69
www.spharktechnologies.com

Cheat Sheet

Extended Slicing and String Methods

Extended Slicing

Syntax:

variable[start_index:end_index:step]

Step determines the increment between each index for slicing.

Code
PYTHON

1 a = "Waterfall"
2 part = a[1:6:3]
3 print(part)

Output

ar

70
www.spharktechnologies.com

Methods

Python has a set of built-in reusable utilities.


They simplify the most commonly performed operations are:

String Methods

isdigit()

strip()

lower()

upper()

startswith()

endswith()

replace() and more...

Isdigit

Syntax:

str_var.isdigit()

Gives

True if all the characters are digits. Otherwise, False

Code
PYTHON

1 is_digit = "4748".isdigit()
2 print(is_digit)

Output

True

Strip
71
www.spharktechnologies.com

Syntax:

str_var.strip()

Removes all the leading and trailing spaces from a string.

Code
PYTHON

1 mobile = " 9876543210 "


2 mobile = mobile.strip()
3 print(mobile)

Output

9876543210

Strip - Specific characters

Syntax:

str_var.strip(chars)

We can also specify characters that need to be removed.

Code
PYTHON

1 name = "Ravi."
2 name = name.strip(".")
3 print(name)

Output

Ravi

72
www.spharktechnologies.com

Strip - Multiple Characters

Removes all spaces, comma(,) and full stop(.) that lead or trail the string.

Code
PYTHON

1 name = ", .. ,, ravi ,, .. ."


2 name = name.strip(" ,.")
3 print(name)

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

1 sentence = "teh cat and teh dog"


2 sentence = sentence.replace("teh","the")
3 print(sentence)

Output

the cat and the dog

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

More String Methods

Concepts

Classification Methods

isalpha()

isdecimal()

islower()

isupper()

isalnum()

Case Conversion Methods

capitalize()

title()

swapcase()

Counting and Searching Methods

count()

index()

rindex()

find()

rfind()

1. Classification Methods

77
www.spharktechnologies.com

These methods are used to check the characteristics of individual


characters in a string.

1.1 Isalpha

Syntax:

str_var.isalpha()

Gives

True if all the characters are alphabets. Otherwise, False

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

True if all the characters are decimals. Otherwise, False

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

True if all letters in the string are in lowercase. Otherwise, False

Example 1:

Code
PYTHON

1 is_lower = "hello ravi!".islower()


2 print(is_lower)

Output

True

Example 2:

Code
PYTHON

1 is_lower = "Hello Ravi!".islower()


2 print(is_lower)

Output

False

80
www.spharktechnologies.com

1.4 Isupper

Syntax:

str_var.isupper()

Gives

True if all letters in the string are in uppercase. Otherwise, False

Example 1:

Code
PYTHON

1 is_upper = "HELLO RAVI!".isupper()


2 print(is_upper)

Output

True

Example 2:

Code
PYTHON

1 is_upper = "hELLO rAVI!".isupper()


2 print(is_upper)

Output

False

1.5 Isalnum
81
www.spharktechnologies.com

Syntax:

str_var.isalnum()

Gives

True if the string is alphanumeric (a letter or a number). Otherwise,


False

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. Case Conversion Methods

These methods are used to change the case of a string.

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

1 capitalized = "the Planet Earth".capitalize()


2 print(capitalized)

Output

83
www.spharktechnologies.com

The planet earth

2.2 Title

Syntax:

str_var.title()

Gives a new string after converting the first letter of every word to
uppercase.

If a word contains a number or a special character, the first letter after


that is converted to uppercase.

Example 1:

Code
PYTHON

1 title_case = "the planet earth".title()


2 print(title_case)

Output

The Planet Earth

Example 2:

Code
PYTHON

1 title_case = "my_name#is john1doe and i love pytho


2 print(title_case)

Output

84
www.spharktechnologies.com

My_Name#Is John1Doe And I Love Python

2.3 Swapcase

Syntax:

str_var.swapcase()

Gives a new string after converting the uppercase letters to lowercase


and vice-versa.

Code
PYTHON

1 swapped = "mY nAME IS rAVI".swapcase()


2 print(swapped)

Output

My Name is Ravi

3. Counting and Searching Methods

These methods are used to count the occurrences of a substring in a


string and to find the position of a substring in a string.

3.1 Count

Syntax:
85
www.spharktechnologies.com

str_var.count(str, start_index, end_index)

Here, the

start_index and the end_index are optional.

The

count() method gives the number of times the specified string


str appears in the string. It searches the complete string as default.

If

start_index and end_index are provided, it searches between


these indices. The end_index is not included.

Example 1:

Code
PYTHON

1 text = "Hello, world!"


2 letter_count = text.count("l")
3 print(letter_count)

Output

Example 2:

Code
PYTHON

1 text = "Hello, world!"


2 letter_count = text.count("l", 2, 10)
3 print(letter_count)

Output

86
www.spharktechnologies.com

3.2 Index

Syntax:

str_var.index(str, start_index, end_index)

Here, the

start_index and the end_index are optional.

The

index() method gives the index at the first occurrence of the


specified string str .

It results in an error if the specified string

str is not found.

The

index() method searches the complete string as default. If


start_index and end_index are provided, it searches between
these indices. The end_index is not included.

Example 1:

Code
PYTHON

1 text = "I have a spare key, if I lose my key"


2 word_index = text.index("key")
3 print(word_index)

Output

15

87
www.spharktechnologies.com

Example 2:

Code
PYTHON

1 text = "coo coo"


2 word_index = text.index("co", 3, 6)
3 print(word_index)

Output

Example 3:

Code
PYTHON

1 text = "coo coo"


2 word_index = text.index("ha")
3 print(word_index)

Output

ValueError: substring not found

3.3 rIndex

Syntax:

str_var.rindex(str, start_index, end_index)

Here, the

start_index and the end_index are optional.

88
www.spharktechnologies.com

The

rindex() method gives the index at the last occurrence of the


specified string str .

It results in an error if the specified string

str is not found.

The

rindex() method searches the complete string as default. If


start_index and end_index are provided, it searches between
these indices. The end_index is not included.

Example 1:

Code
PYTHON

1 text = "I have a spare key, if I lose my key"


2 word_index = text.rindex("key")
3 print(word_index)

Output

33

Example 2:

Code
PYTHON

1 text = "coo coo coo"


2 word_index = text.rindex("co", 3, 10)
3 print(word_index)

Output

89
www.spharktechnologies.com

Example 3:

Code
PYTHON

1 text = "coo coo"


2 word_index = text.rindex("ha")
3 print(word_index)

Output

ValueError: substring not found

3.4 Find

Syntax:

str_var.find(str, start_index, end_index)

Here, the

start_index and the end_index are optional.

The

find() method gives the index at the first occurrence of the specified
string str .

If the specified string

str is not found, it returns -1 .

The

find() method searches the complete string as default. If


start_index and end_index are provided, it searches between
these indices. The end_index is not included.

It works similarly to the

90
www.spharktechnologies.com

index() method. The only difference is that the index() method


results in an error if the specified string is not found, while find()
does not.

Example 1:

Code
PYTHON

1 text = "I have a spare key, if I lose my key"


2 word_index = text.find("key")
3 print(word_index)

Output

15

Example 2:

Code
PYTHON

1 text = "coo coo"


2 word_index = text.find("co", 3, 6)
3 print(word_index)

Output

Example 3:

Code
PYTHON

1 text = "coo coo"


2 d i d t t fi d("h ") 91
www.spharktechnologies.com

2 word_index = text.find("ha")
3 print(word_index)

Output

-1

3.5 rFind

Syntax:

str_var.rfind(str, start_index, end_index)

Here, the

start_index and the end_index are optional.

The

rfind() method gives the index at the last occurrence of the


specified string str .

If the specified string

str is not found, it returns -1 .

The

rfind() method searches the complete string as default. If


start_index and end_index are provided, it searches between
these indices. The end_index is not included.

It works similarly to the

rindex() method. The only difference is that the rindex() method


results in an error if the specified string is not found, while rfind()
does not.

Example 1:

Code
PYTHON

92
www.spharktechnologies.com

1 text = "I have a spare key, if I lose my key"


2 word_index = text.rfind("key")
3 print(word_index)

Output

33

Example 2:

Code
PYTHON

1 text = "coo coo coo"


2 word_index = text.rfind("co", 3, 10)
3 print(word_index)

Output

Example 3:

Code
PYTHON

1 text = "coo coo"


2 word_index = text.rfind("ha")
3 print(word_index)

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

Nested Repeating Block

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

1 print(" Inner: " + str(j))

Output

Outer: 0
Inner: 0
Inner: 1
Outer: 1
Inner: 0
96
www.spharktechnologies.com

Inner: 1
END

Examples - Nested Loops

Example - 1: While loop inside a For loop

Example - 2: While loop inside a while loop

97
www.spharktechnologies.com

Loop Control Statements


Control statements alter the sequential execution of a program.

Examples

if-elif-else

while, for

break, continue

Break

Break statement makes the program exit a loop early.

Using Break

98
www.spharktechnologies.com

Generally, break is used to exit a loop when a condition is satisfied.

In the below example, when the variable

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

Break in Nested Loop

Break in inner loop stops the execution of the inner loop.

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

In the below example, when the variable

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

Pass statement is used as a syntactic placeholder. When it is executed, nothing


happens.

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.

Every character has a unique Unicode value.

Ord

To find the Unicode value of a character, we use the

ord()

ord(character) gives unicode value of the character.

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()

chr(unicode) gives character with the unicode value.

Code
PYTHON

1 char = chr(75)
2 print(char)

Output

Unicode Ranges

48 - 57 -> Number Digits (0 - 9)

65 - 90 -> Capital Letters (A - Z)

97 - 122 -> Small Letters (a - z)

Rest -> Special Characters, Other Languages

Printing Characters

The below code will print the characters from

A to Z

Code
PYTHON

1 for unicode_value in range(65,91):


2 print(chr(unicode_value))

104
www.spharktechnologies.com

Output

A
B
C
D
E
F
G
H
I
J
Expand

Comparing Strings

In Python, strings are compared considering unicode.

Code
PYTHON

1 print("A" < "B")

Output

True

As unicode value of

A is 65 and B is 66, which internally compares 65 < 66 . So the output should be True

Character by Character Comparison

In Python, String Comparison is done character by character.

Code
105
www.spharktechnologies.com

PYTHON

1 print("BAD" >= "BAT")

Output

False

Code
PYTHON

1 print("98" < "984")

Output

True

Best Practices

Naming Variables Rule #1

Use only the below characters

Capital Letters ( A – Z )
Small Letters ( a – z )
Digits ( 0 – 9 )

Underscore(_)

Examples:
age, total_bill

Naming Variables Rule #2


106
www.spharktechnologies.com

Below characters cannot be used

Blanks ( )
Commas ( , )
Special Characters
( ~ ! @ # $ % ^ . ?, etc. )

Naming Variables Rule #3

Variable name must begin with

Capital Letters ( A – Z )
Small Letters ( a – z )
Underscore( _ )

Naming Variables Rule #4

Cannot use Keywords, which are reserved for special meaning

int
str
print etc.,

Keywords
Words which are reserved for special meaning

Code
PYTHON

1 help("keywords")

Output

Here is a list of the Python keywords. Enter any keyword to

False break for


None class from
True continue global
__peg_parser__ def if
107
www.spharktechnologies.com

and del import


as elif in
assert else is
async except lambda
await finally nonlocal

None

Collapse

Case Styles

Camel case: totalBill

Pascal case: TotalBill

Snake case: total_bill

Snake case is preferred for naming the variables in Python.

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.

In Python, there are four built-in data structures

List

Tuple

Set

Dictionary

List

List is the most versatile python data structure.


Holds an ordered sequence of items.

Creating a List

Created by enclosing elements within [square] brackets.


Each item is separated by a comma.

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]

Creating a List of Lists

Code
PYTHON

1 a = 2
2 list_a = [5, "Six", a, 8.2]
3 list_b = [1, list_a]
4 print(list_b)

Output

[1, [5, 'Six', 2, 8.2]]

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

Accessing List Items

To access elements of a list, we use Indexing.

Code
PYTHON

1 a = 2
2 list_a = [5, "Six", a, 8.2]
3 print(list_a[1])

Output

Six

Iterating Over a List

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,

+ operator concatenates lists.

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

[1, 2, 3, 'a', 'b', 'c']

Adding Items to List

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

* Operator repeats lists.


112
www.spharktechnologies.com

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

Obtaining a part of a list is called List Slicing.

Code
PYTHON

1 list_a = [5, "Six", 2, 8.2]


2 list_b = list_a[:2]
3 print(list_b)

Output

[5, 'Six']

113
www.spharktechnologies.com

Extended Slicing

Similar to string extended slicing, we can extract alternate items using step.

Code
PYTHON

1 list_a = ["R", "B", "G", "O", "W"]


2 list_b = list_a[0:5:3]
3 print(list_b)

Output

['R', 'O']

Converting to List

list(sequence) takes a sequence and converts it into list.

Code
PYTHON

1 color = "Red"
2 list_a = list(color)
3 print(list_a)

Output

['R', 'e', 'd']

Code

PYTHON
114
www.spharktechnologies.com
PYTHON

1 list_a = list(range(4))
2 print(list_a)

Output

[0, 1, 2, 3]

Lists are Mutable

Lists can be modified.

Items at any position can be updated.

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]

Strings are Immutable

Strings are Immutable (Can’t be modified).

Code

PYTHON
115
www.spharktechnologies.com
PYTHON

1 message = "sea you soon"


2 message[2] = "e"
3 print(message)

Output

TypeError: 'str' object does not support item assignment

Submit Feedback

116
www.spharktechnologies.com

Cheat Sheet

Working with Lists


Object

In general, anything that can be assigned to a variable in Python is referred to as an object.

Strings, Integers, Floats, Lists etc. are all objects.

Examples

"A"

1.25

[1,2,3]

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.

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

We can use the

id() to find the id of a object.

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

When assigned an existing list both the variables

list_a and list_b will be referring to the same object.


118
www.spharktechnologies.com

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

When assigned an existing list both the variables

list_a and list_b will be referring to the same object.

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

The assignment will update the reference to new object.

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

The assignment will update the reference to a new object.

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

Lists and Strings

Splitting

str_var.split(separator)

Splits a string into a list at every specified separator.


If no separator is specified, default separator is whitespace.

Code
PYTHON

1 nums = "1 2 3 4"


2 num_list = nums.split()
3 print(num_list)

Output

['1', '2', '3', '4']

Multiple WhiteSpaces
126
www.spharktechnologies.com

Multiple whitespaces are considered as single when splitting.

Code
PYTHON

1 nums = "1 2 3 4 "


2 num_list = nums.split()
3 print(num_list)

Output

['1', '2', '3', '4']

New line

\n and tab space \t are also whitespace.

Code
PYTHON

1 nums = "1\n2\t3 4"


2 num_list = nums.split()
3 print(num_list)

127
www.spharktechnologies.com

Output

['1', '2', '3', '4']

Using Separator

Breaks up a string at the specified separator.

Example -1

Code
PYTHON

1 nums = "1,2,3,4"
2 num_list = nums.split(',')
3 print(num_list)

Output

['1', '2', '3', '4']

128
www.spharktechnologies.com

Example -2

Code
PYTHON

1 nums = "1,2,,3,4,"
2 num_list = nums.split(',')
3 print(num_list)

Output

['1', '2', '', '3', '4', '']

Space as Separator
Code
PYTHON

1 nums = "1 2 3 4 "


2 num_list = nums.split(" ")
3 print(num_list)

Output
129
www.spharktechnologies.com

['1', '', '2', '3', '4', '']

String as Separator

Example - 1

Code
PYTHON

1 string_a = "Python is a programming language"


2 list_a = string_a.split('a')
3 print(list_a)

Output

['Python is ', ' progr', 'mming l', 'ngu', 'ge']

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

['', '-by-', ' execution of code']

Joining

str.join(sequence)

Takes all the items in a sequence of strings and joins them into one string.

Code
PYTHON

1 list_a = ['Python is ', ' progr', 'mming l', 'ngu', 'ge']


2 string_a = "a".join(list_a)
3 print(string_a)

Output

131
www.spharktechnologies.com

Python is a programming language

Joining Non String Values

Sequence should not contain any non-string values.

Code
PYTHON

1 list_a = list(range(4))
2 string_a = ",".join(list_a)
3 print(string_a)

Output

TypeError: sequence item 0: expected str instance, int found

Negative Indexing
Using a negative index returns the nth item from the end of list.

132
www.spharktechnologies.com

Last item in the list can be accessed with index

-1

Reversing a List

-1 for step will reverse the order of items in the 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]

Accessing List Items

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

Slicing With Negative Index

You can also specify negative indices while slicing a List.

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]

Out of Bounds Index

While slicing, Index can go out of bounds.

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 Size


variable[start:end:negative_step]

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

start > end

Negative Step Size Examples

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

Negative step requires the start to be greater than end.

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 for step will reverse the order of items in the list.


PYTHON

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

-1 for step will reverse the order of the characters.

Code
PYTHON

1 string_1 = "Program"
2 string_2 = string_1[::-1]
3 print(string_2)

Output

margorP

Negative Step Size - Strings

Code

140
www.spharktechnologies.com

PYTHON

1 string_1 = "Program"
2 string_2 = string_1[6:0:-2]
3 print(string_2)

Output

mro

Indexing & Slicing - Strings

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

Using an existing code without writing it every time we need.

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 is uniquely identified by the

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

Defining & Calling a Function

A function should be defined before it is called.

Code

148
www.spharktechnologies.com

PYTHON

1 name = input()
2 greet()
3 print(name)
4
5 def greet():
6 print("Hello")

Input

Teja

Output

NameError: name 'greet' is not defined

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

name at line 2 in place of the ? .

Code
PYTHON

1 def greet():
2 msg = "Hello " + ?
3 print(msg)
4
5 name = input()
6 greet()

Input

Teja

Desired Output

Hello Teja

We use the concept of Function Arguments for these types of scenarios.

150
www.spharktechnologies.com

Function With Arguments

We can pass values to a function using an Argument.

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

Variables Inside a Function

A variable created inside a function can only be used in it.

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

NameError: name 'msg' is not defined

Returning a Value

To return a value from the function use

return keyword.

153
www.spharktechnologies.com

Exits from the function when return statement is executed.

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 written after


154
www.spharktechnologies.com

return statement will not be executed.

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

We are already using functions which are pre-defined in Python.


Built-in functions are readily available for reuse

print()

int()

str()

len()

Submit Feedback

156
www.spharktechnologies.com

Function Arguments
A function can have more than one argument.

Keyword Arguments

Passing values by their names.

Code
PYTHON

1 def greet(arg_1, arg_2):


2 print(arg_1 + " " + arg_2)
3
4 greeting = input()
5 name = input()
6 greet(arg_1=greeting,arg_2=name)

Input

Good Morning
Ram

Output

157
www.spharktechnologies.com

Good Morning Ram

Possible Mistakes - Keyword Arguments

Code
PYTHON

1 def greet(arg_1, arg_2):


2 print(arg_1 + " " + arg_2)
3
4 greeting = input()
5 name = input()
6 greet(arg_2=name)

Input

Good Morning
Ram

Output

TypeError: greet() missing 1 required positional argument: '

Positional Arguments

Values can be passed without using argument names.

These values get assigned according to their position.

Order of the arguments matters here.

Code

158
www.spharktechnologies.com

PYTHON

1 def greet(arg_1, arg_2):


2 print(arg_1 + " " + arg_2)
3
4 greeting = input()
5 name = input()
6 greet(greeting,name)

Input

Good Morning
Ram

Output

Good Morning Ram

Possible Mistakes - Positional Arguments

Mistake - 1

Code
PYTHON

1 def greet(arg_1, arg_2):


2 print(arg_1 + " " + arg_2)
3
4 greeting = input()
5 name = input()
6 greet(greeting)

Input

159
www.spharktechnologies.com

Good Morning
Ram

Output

TypeError: greet() missing 1 required positional argument: '

Mistake - 2

Code
PYTHON

1 def greet(arg_1, arg_2):


2 print(arg_1 + " " + arg_2)
3
4 greeting = input()
5 name = input()
6 greet()

Input

Good Morning
Ram

Output

TypeError: greet() missing 2 required positional arguments

Default Values

160
www.spharktechnologies.com

Example - 1

Code
PYTHON

1 def greet(arg_1="Hi", arg_2="Ram"):


2 print(arg_1 + " " + arg_2)
3
4 greeting = input()
5 name = input()
6 greet()

Input

Hello
Teja

Output

Hi Ram

Example - 2

Code
PYTHON

1 def greet(arg_1="Hi", arg_2="Ram"):


2 print(arg_1 + " " + arg_2)
3
4 greeting = input()
5 name = input()
6 greet(greeting)

Input

Hello 161
www.spharktechnologies.com

Hello
Teja

Output

Hello Ram

Example - 3

Code
PYTHON

1 def greet(arg_1="Hi", arg_2="Ram"):


2 print(arg_1 + " " + arg_2)
3
4 greeting = input()
5 name = input()
6 greet(name)

Input

Hello
Teja

Output

Teja Ram

Example - 4

Code

162
www.spharktechnologies.com

PYTHON

1 def greet(arg_1="Hi", arg_2="Ram"):


2 print(arg_1 + " " + arg_2)
3
4 greeting = input()
5 name = input()
6 greet(arg_2=name)

Input

Hello
Teja

Output

Hi Teja

Example - 5

Code
PYTHON

1 def greet(arg_1="Hi", arg_2):


2 print(arg_1 + " " + arg_2)
3
4 greeting = input()
5 name = input()
6 greet(arg_2=name)

Input

Hello
Teja

163
www.spharktechnologies.com

Output

SyntaxError:non-default argument follows default argument

Non-default arguments cannot follow default arguments.

Example - 6

Code
PYTHON

1 def greet(arg_2, arg_1="Hi"):


2 print(arg_1 + " " + arg_2)
3
4 greeting = input()
5 name = input()
6 greet(arg_2=name)

Input

Hello
Teja

Output

Hi Teja

Passing Immutable Objects

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

Passing Mutable Objects


The same object in the memory is referred by both

list_a and list_x

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.

We are already using functions which are pre-defined in Python

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)

Strings are compared character by character using unicode values.

P - 80(unicode)

J - 74(unicode)

Code
PYTHON

1 smallest = min("Python", "Java")


2 print(smallest)

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

Ordering List Items


sorted(sequence) returns a new sequence with all the items in the given sequence ordered in increasing order.

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]

Ordering List Items - Reverse


sorted(sequence, reverse=True) returns a new sequence with all the items in the given sequence ordered in decreasing order.

173
www.spharktechnologies.com

Function Call Stack & Recursion

Stack

Stack is a data structure that stores items in an Last-In/First-Out manner.

Calling a Function

Calling

function_1() inside function_2()

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

In the above code calling functions are

len() and max() inside get_largest_sqr()

Sum of Squares of List Items

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

Function Call Stack


Function Call Stack keeps track of function calls in progress

177
www.spharktechnologies.com

Recursion

178
www.spharktechnologies.com

A function calling itself is called a Recursion

Let's understand recursion with a simple example of multiplying N numbers

Multiply N Numbers
PYTHON

1 def factorial(n): # Recursive Function


2 if n == 1: # Base Case
3 return 1
4 return n * factorial(n - 1) # Recursion
5 num = int(input())
6 result = factorial(num)
7 print(result)

179
www.spharktechnologies.com

Base Case

A recursive function terminates when base condition is met

Input

Output

Without Base case

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

RecursionError: maximum recursion depth exceeded

Submit Feedback

181
www.spharktechnologies.com

List Methods
Python provides list methods that allow us to work with lists.

Let’s learn few among them

append()

extend()

insert()

pop()

clear()

remove()

sort()

index()

Append

list.append(value) Adds an element to the end of the list.

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

list.insert(index,value) Element is inserted to the list at specified index.

Code
PYTHON

1 list_a = [1, 2, 3]
2 list_a.insert(1,4)
3 print(list_a)

Output

[1, 4, 2, 3]

Pop

list.pop() Removes last element.

Code
183
www.spharktechnologies.com

PYTHON

1 list_a = [1, 2, 3]
2 list_a.pop()
3 print(list_a)

Output

[1, 2]

Remove

list.remove(value) Removes the first matching element from the list.

Code
PYTHON

1 list_a = [1, 3, 2, 3]
2 list_a.remove(3)
3 print(list_a)

Output

[1, 2, 3]

Clear

list.clear() Removes all the items from the list.

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

list.count(value) Returns the number of elements with the specified value.

Code

185
www.spharktechnologies.com

PYTHON

1 list_a = [1, 2, 3]
2 count = list_a.count(2)
3 print(count)

Output

Sort

list.sort() Sorts the list.

Code
PYTHON

1 list_a = [1, 3, 2]
2 list_a.sort()
3 print(list_a)

Output

[1, 2, 3]

Sort & Sorted

sort() Modifies the list

Code

186
www.spharktechnologies.com

PYTHON

1 list_a = [1, 3, 2]
2 list_a.sort()
3 print(list_a)

Output

[1, 2, 3]

sorted() Creates a new sorted list

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

Tuples and Sequences

None

None is an object which is a datatype of its own (NoneType).

Used to define no value or nothing.

Code
PYTHON

1 var = None
2 print(var)
3 print(type(var))

Output

None
<class 'NoneType'>

Function Without Return


188
www.spharktechnologies.com

Functions assigned to a variable, when function does not have a

return statement, the variable will get the value None

Code
PYTHON

1 def increment(a):
2 a += 1
3
4 a = 55
5 result = increment(a)
6 print(result)

Output

None

Function That Returns Nothing

When a function returns no value, the default value will be

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

Holds an ordered sequence of items.

Tuple is immutable object, where as list is a mutable object.

Code
PYTHON

1 a = 2
2 tuple_a = (5, "Six", a, 8.2)

Creating a Tuple

Created by enclosing elements within (round) brackets.

Each item is separated by a comma.

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

(5, Six , 2, 8.2)

Tuple with a Single Item

Code
PYTHON

1 a = (1,)
2 print(type(a))
3 print(a)

Output

<class 'tuple'>
(1,)

Accessing Tuple Elements

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

Tuples are Immutable

Tuples does not support modification.

Code
PYTHON

1 tuple_a = (1, 2, 3, 5)
2 tuple_a[3] = 4
3 print(tuple_a)

Output

TypeError: 'tuple' object does not support item assignment

194
www.spharktechnologies.com

Operations can be done on Tuples

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

('R', 'e', 'd')

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

Check if given data element is part of a sequence or not.

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

Packing & Unpacking

Unpacking

Values of any sequence can be directly assigned to variables.

Number of variables in the left should match the length of sequence.

Code
PYTHON

1 tuple_a = ('R', 'e', 'd')


2 (s_1, s_2, s_3) = tuple_a
3 print(s_1)
4 print(s_2)
5 print(s_3)

Output

R
200
www.spharktechnologies.com
R
e
d

Errors in Unpacking

Code
PYTHON

1 tuple_a = ('R', 'e', 'd')


2 s_1, s_2 = tuple_a
3 print(s_1)
4 print(s_2)

Output

ValueError: too many values to unpack (expected 2)

Code

201
www.spharktechnologies.com

PYTHON

1 tuple_a = ('R', 'e', 'd')


2 s_1, s_2, s_3, s_4 = tuple_a
3 print(s_1)

Output

ValueError: not enough values to unpack (expected 4, got 3)

Tuple Packing

() brackets are optional while creating tuples.

In Tuple Packing, Values separated by commas will be packed into a tuple.

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.

Every set element is

Unique (no duplicates)


Must be immutable

Creating a Set

Created by enclosing elements within {curly} brackets.

205
www.spharktechnologies.com

Each item is separated by a comma.

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}

Need not be in the same order as defined.

No Duplicate Items

Sets contain unique elements

Code

206
www.spharktechnologies.com

PYTHON

1 set_a = {"a", "b", "c", "a"}


2 print(set_a)

Output

{'b', 'a', 'c'}

Immutable Items

Set items must be immutable.


As List is mutable, Set cannot have list as an item.

Code
PYTHON

1 set_a = {"a", ["c", "a"]}


2 print(set_a)

Output

207
www.spharktechnologies.com

TypeError: unhashable type: 'list'

Creating Empty Set

We use

set() to create an empty set.

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

{'l', 'p', 'e', 'a'}

Tuple to Set

Code
PYTHON

1 set_a = set((1, 2, 1))


2 print(set_a)

Output

{1, 2}

Accessing Items

As sets are unordered, we cannot access or change an item of a set using

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

TypeError: 'set' object is not subscriptable

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}

Adding Multiple Items


set.update(sequence) adds multiple items to the set, and duplicates are avoided.

Code
PYTHON

1 set_a = {1, 3, 9}
2 set_a.update([2, 3])
3 print(set_a)

Output

{2, 1, 3, 9}

Removing Specific Item


set.discard(value) takes a single value and removes if present.

Code

212
www.spharktechnologies.com

PYTHON

1 set_a = {1, 3, 9}
2 set_a.discard(3)
3 print(set_a)

Output

{1, 9}

set_a.remove(value) takes a value and remove if it present or raise an error.

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

You can perform the following 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

Union of two sets is a set containing all elements of both sets.

set_a | set_b or set_a.union(sequence)

union() converts sequence to a set, and performs the 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

Intersection of two sets is a set containing common elements of both sets.

set_a & set_b or set_a.intersection(sequence)

intersection() converts sequence to a set, and perform the 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.

set_a - set_b or set_a.difference(sequence)

difference() converts sequence to a set.

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.

set_a ^ set_b or set_a.symmetric_difference(sequence)

symmetric_difference() converts sequence to a set.

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

set1.isdisjoint(set2) Returns True when they have no common elements. Else,


False

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

Nested Lists & String Formatting


A list as an item of another list.

Accessing Nested List

225
www.spharktechnologies.com

Code
PYTHON

1 list_a = [5, "Six", [8, 6], 8.2]


2 print(list_a[2])

Output

[8, 6]

Accessing Items of Nested List


226
www.spharktechnologies.com

Example - 1

Code
PYTHON

1 list_a = [5, "Six", [8, 6], 8.2]


2 print(list_a[2][0])

Output

Example - 2

Code
PYTHON

1 list_a = ["Five", "Six"]


2 print(list_a[0][1])

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)

String formatting simplifies this concatenation.

It increases the readability of code and type conversion is not required.

Add Placeholders

Add placeholders

{} where the string needs to be formatted.

228
www.spharktechnologies.com

PYTHON

1 msg = "Hi {}. You are {} years old."


2 msg.format(val_1, val_2,..)

Inserts values inside the string’s placeholder

{}

Code
PYTHON

1 name = "Raju"
2 age = 10
3 msg = "Hi {}. You are {} years old."
4 print(msg.format(name, age))

Output

Hi Raju. You are 10 years old.

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

IndexError: Replacement index 2 out of range for positional

Numbering Placeholders

Numbering placeholders, will fill values according to the position of arguments.

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

Hi Raju. You are 10 years old.

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

Hi 10. You are Raju years old.

Naming Placeholder

Naming placeholders will fill values according to the keyword arguments.

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

Hi Raju. You are 10 years old.

Submit Feedback

233
www.spharktechnologies.com

Creating a Dictionary

Created by enclosing items within {curly} brackets

Each item in dictionary has a key - value pair separated by a comma.

Code
PYTHON

1 dict_a = {
2 "name": "Teja",
3 "age": 15
4 }

Key - Value Pairs

Code
PYTHON

1 dict_a = {
2 "name": "Teja",
3 "age": 15
4 }

In the above dictionary, the

keys are name and age


values are Teja and 15

Collection of Key-Value Pairs

Code
PYTHON

1 dict_a = { "name": "Teja",


2 "age": 15 }
3 print(type(dict_a))
4 print(dict_a)

234
www.spharktechnologies.com

Output

<class 'dict'>
{'name': 'Teja','age': 15}

Immutable Keys

Keys must be of immutable type and must be unique.

Values can be of any data type and can repeat.

Code
PYTHON

1 dict_a = {
2 "name": "Teja",
3 "age": 15,
4 "roll_no": 15
5 }

Creating Empty Dictionary


Code - 1
PYTHON

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

To access the items in dictionary, we use square bracket

[ ] along with the key to obtain its value.

Code
PYTHON

1 dict_a = {
2 'name': 'Teja',
3 'age': 15
4 }
5 print(dict_a['name'])

Output

Teja

Accessing Items - Get

The

get() method returns None if the key is not found.

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

When we use the square brackets

[] to access the key-value, KeyError is raised in case a key is not found in the dictionary.

Code
PYTHON

1 dict_a = {'name': 'Teja','age': 15 }


237
www.spharktechnologies.com

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

Checks if the given key exists.

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

We can update a dictionary by

238
www.spharktechnologies.com

Adding a key-value pair


Modifying existing items
Deleting existing items

Adding a Key-Value Pair

Code
PYTHON

1 dict_a = {'name': 'Teja','age': 15 }


2 dict_a['city'] = 'Goa'
3 print(dict_a)

Output

{'name': 'Teja', 'age': 15, 'city': 'Goa'}

Modifying an Existing Item

As dictionaries are mutable, we can modify the values of the keys.

Code
PYTHON

1 dict_a = {
2 'name': 'Teja',
3 'age': 15
4 }
5 dict_a['age'] = 24
6 print(dict_a)

Output

{'name': 'Teja', 'age': 24}

239
www.spharktechnologies.com

Deleting an Existing Item

We can also use the

del keyword to remove individual items or the entire dictionary itself.

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

The objects returned by

keys() , values() & items() are View Objects .

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

dict_items([('name', 'Teja'), ('age', 15)])

Iterate over Dictionary Views

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

Dictionary View Objects


keys() , values() & items() are called Dictionary Views as they provide a dynamic view on the
dictionary’s items.

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

dict keys(['name', 'age'])


244
www.spharktechnologies.com
_ y ([ , g ])
dict_keys(['name', 'age', 'roll_no'])

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

{'name': 'Teja', 'age': 15, 'roll_no': 15}

Code
PYTHON

1 list_a = ["name", "Teja", 15]


2 dict_a = dict(list_a)
3 print(dict_a)

Output

ValueError: dictionary update sequence element #0 has length

Type of Keys
245
www.spharktechnologies.com

A dictionary key must be of a type that is immutable.

246
www.spharktechnologies.com

Working with Dictionaries

Dictionary Methods

Python provides dictionary methods that allow us to work with dictionaries.

copy()

get()

update()

fromkeys() and more..

Let’s learn few among them

Referring Same Dictionary Object


Code
PYTHON

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

{'name':'Teja', 'age': 20}


140170705626624
140170705626624

247
www.spharktechnologies.com

Copy of Dictionary

dict.copy() returns copy of a 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

{'name':'Teja', 'age': 15}


140664418952704
140664418952896

Copy of List

Code
PYTHON

1 list_a = ['Teja', 15]


2 list_b = list_a.copy()
3 list_b.extend([20])
4 print(list_a)
5 print(id(list_a))
6 print(id(list_b))

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

Cannot add/remove dictionary keys while iterating the dictionary.

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

RuntimeError: dictionary changed size during iteration

Arbitrary Function Arguments

Passing Multiple Values

We can define a function to receive any number of arguments.

We have already seen such functions

max(*args) max(1,2,3..)

min(*args) min(1,2,3..)

Variable Length Arguments

Variable length arguments are packed as tuple.

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

If we already have the data required to pass to a function as a sequence, we can

unpack it with

* while passing.

Code
PYTHON

1 def greet(arg1="Hi", arg2="Ram"):


2 print(arg1 + " " + arg2)
3
4 data = ["Hello", "Teja"]
5 greet(*data)

Output

Hello Teja

Multiple Keyword Arguments

We can define a function to receive any number of keyword arguments.

251
www.spharktechnologies.com

Variable length kwargs are packed as dictionary.

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

1 def greet(arg1="Hi", arg2="Ram"):


2 print(arg1 + " " + arg2)
3
4 data = {'arg1':'Hello', 'arg2':'Teja'}
5 greet(**data)

Output

Hello Teja

Code - 2

253
www.spharktechnologies.com

PYTHON

1 def greet(arg1="Hi", arg2="Ram"):


2 print(arg1 + " " + arg2)
3
4 data = {'msg':'Hello', 'name':'Teja'}
5 greet(**data)

Output

TypeError: greet() got an unexpected keyword argument 'msg'

Submit Feedback

254
www.spharktechnologies.com

More Built-in Functions

Concepts

Built-in Functions

abs()

all()

any()

reversed()

enumerate()

List Methods

copy()

reverse()

1. Built-in Functions

1.1 Abs

Syntax:

abs(number)

The

abs() function gives the absolute value (positive representation) of a


number. For example, the absolute value of -3 is 3 .

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

For each item in a sequence, the

all() function evaluates to false, for which the bool() function returns
False . For example, 0 , None , False , etc.

Example 1:

Code
PYTHON

1 list_a = [True, True]


2 is_all_true = all(list_a)
3
4 print(is_all_true)

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

2 is_true_in_set = all({True, "Teja", 7})


3 is_true_in_tuple = all(("", "hello", "world"))
4
5 print(is_true_in_list)
6 print(is_true_in_set)
7 print(is_true_in_tuple)

Output

False
True
False

In the case of dictionaries, the

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 .

If the sequence is empty, it returns

False .

For each item in a sequence, the

any() function evaluates to false, for which the bool() function returns
False . For example, 0 , None , False , etc.

Example 1:

Code
PYTHON

1 list_a = [True, False]


2 is_any_true = any(list_a)
3
4 print(is_any_true)

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

1 is_true_in_list = any([0, 0, 2, 0])


2 is_true_in_set = any({"", None, 0})
3 is_true_in_tuple = any(("hello", "world"))
4
5 print(is_true_in_list)
6 print(is_true_in_set)
7 print(is_true_in_tuple)

Output

True
False
True

In the case of dictionaries, the

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

reversed() function returns the reverse of a sequence.

Example 1:

Code
PYTHON

1 name = "Teja"
2 reversed_name = reversed(name)
3
4 print(list(reversed_name))

Output

['a', 'j', 'e', 'T']

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,

sequence : is any sequence like a string, list, set, etc.

start (Optional): it indicates the start point of the counter. Its default
value is 0 .

The

enumerate() function adds a counter to each item in a sequence and


returns a sequence containing tuples.

Example 1:

Code
PYTHON

1 name = "Teja"
2 enumerate_name = enumerate(name)
3
4 print(list(enumerate_name))

Output

[(0, 'T'), (1, 'e'), (2, 'j'), (3, 'a')]

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

[(10, 1), (11, 2), (12, 3), (13, 4)]

Looping Over an Enumerate

We can use the

for loop to iterate over an enumerate.

Code
PYTHON

1 names = ["Jack", "John", "James"]


2
3 for each_name in enumerate(names):
4 print(each_name)

Output

(0, 'Jack')
(1, 'John')
(2, 'James')

We can unpack each tuple returned by the enumerate.

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

1 list_a = ["a", "b", "c"]


2 list_b = list_a
3 list_a[0] = "z"
4 print(list_b)
5
6
7 list_1 = ["a", "b", "c"]
8 list_2 = list_1.copy()
9 list_1[0] = "z"
10 print(list_2)

Output

['z', 'b', 'c']


['a', 'b', 'c']

In the above code, both the variables

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.

Whereas, when we copy

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

1 list_a = ["a", "b", "c"]


2 list_b = [1, 2, 3, list_a]
3
4 list_c = list_b.copy()
5 list_a[0] = "z"
6
7 print(list_c)

Output

[1, 2, 3, ['z', 'b', 'c']]

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

1 list_a = ["apple", "mango", "banana"]


2 list_a.reverse()
3
4 print(list_a)

Output

['banana', 'mango', 'apple']

Submit Feedback

268
www.spharktechnologies.com

Introduction to OOP

Good Software

Before jumping into Object Oriented Programming, let’s understand the


word Software.

Software is an easily changeable tool/product that performs a specific task.

The ease of changing or making changes to the software is referred as its


softness.

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 understand and make changes.

Easy to fix bugs and add new features within the scope.

Object-Oriented Programming System (OOPS) is a way of approaching,


designing, developing software that is easy to change.

Note

Keep in mind that building software differs from solving the


coding questions (that you are doing in practice).

A fundamental difference is that you move on to the next problem


once you solve a coding problem. But with software, once you
build it, you are often required to add new features and fix bugs
that need you to make changes to the code written by you or
your colleagues. So unlike the coding questions, with software,
you have to keep working with the same code for a long time.

Therefore, ease of understanding (code-readability) and ease of


making changes (code-maintainability) to the code become
crucial in software development.

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

Object-Oriented Programming is a way of approaching, designing and


developing software, so that the components of the software and the
interactions between them resembles real-life objects and their interactions.

Proper usage of OOPS concepts helps us build well-organized systems that


are easy to use and extend.

Describing Real-Life Objects

In Object Oriented Programming, we model software after real-life objects.


To be good at modeling software after real-life objects, we should be able to
properly describe them.

Let us try describing these real-life objects

271
www.spharktechnologies.com

The following description is a bad way of describing, as the information


of an object scattered and unorganized.

Object 1 is a car and it has four tyres.


Object 2 is a dog and it has four legs.
Object 1 has four doors.
Object 1 can make sound
272
www.spharktechnologies.com
Object 1 can make sound.
Object 2, barks.
Object 1 is in blue color.
Object 2 is in brown color.

Organized Description
In the below description we are grouping the information related to an
object.

Object 1 is a car and it has four tyres.


Object 1 has four doors.
Object 1 can make sound.
Object 1 is in blue color.

Object 2 is a dog and it has four legs.


Object 2, barks.
Object 2 is in brown color

In the below approach, we further organize the information into

What the object is?

What the object has?

273
www.spharktechnologies.com

What the object can do?

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

The above description shows a simple framework where we describe object


by specifying the properties that the object has and actions that the object
can do.

Organized Description should be

A clear separation of objects.

A clear grouping of what object has and what it does.

Submit Feedback

275
www.spharktechnologies.com

Describing Similar Objects


Sometimes, the objects that we are describing are so similar that only values
of the properties differ.

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

Does it have a Face Unlock? Yes | No

Filled Template

Model : iPhone 12 Pro


Camera: 64MP
Storage: 128GB
Does it have a Face Unlock? Yes

Bundling Data

While modeling real-life objects with object oriented programming, we


ensure to bundle related information together to clearly separate
information of different objects.

Bundling of related properties and actions together is called Encapsulation.

Classes can be used to bundle related properties and actions.

278
www.spharktechnologies.com

Defining a Class

To create a class, use the keyword

class

Special Method
279
www.spharktechnologies.com

In Python, a special method

__init__ is used to assign values to properties.

Code
PYTHON

1 class Mobile:
2 def __init__(self, model, camera):
3 self.model = model
4 self.camera = camera

Properties & Values


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..")

In the above example,

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..")

In the above example, the below function is an action


PYTHON

1 def make_call(self, number):


2 print("calling..")

In OOP terminology, properties are referred as attributes actions are


referred as methods

Using a Class

281
www.spharktechnologies.com

To use the defined class, we have to instantiate it.


A class is like a blueprint, while its instance is based on that class with actual
values.

Instance of Class

Syntax for creating an instance of class looks similar to function call.

An instance of class is Object.

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

An object is simply a collection of attributes and methods that act on those


data.
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)

Method Arguments & Return Values

Similar to functions, Methods also support positional, keyword & default


arguments and also return values.

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)

Instance Methods of Class

For instance method, we need to first write

self in the function definition and then the other arguments.

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

Classes and Objects

Attributes of an Object

Attributes can be set or accessed using

. (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

Accessing in Other Methods

We can also access and update properties in other methods.

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

It is recommended to update attributes through methods.

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

Let’s model the scenario of shopping cart of ecommerce site.

288
www.spharktechnologies.com

The features a cart should have

can add an item

can remove an item from cart

update quantity of an item

to show list of items in cart

to show total price for the items in the cart

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

Attributes & Methods

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

Broadly, attributes can be categorized as

Instance Attributes

Class Attributes

Instance Attributes

Attributes whose value can differ for each instance of class are modeled as instance attributes.

Ex: Items in Cart

291
www.spharktechnologies.com

Class Attributes

Attributes whose values stay common for all the objects are modelled as Class Attributes.

Ex: Minimum Cart Bill,


Flat Discount

Accessing Instance 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

NameError: name 'items' is not defined

Instance attributes can only be accessed using instance of class.

Self

self passed to method contains the object, which is an instance of class.

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

<__main__.Cart object at 0x7f6f83c9dfd0> <__main__.Cart object at 0x7f6f83c9dfd0>

293
www.spharktechnologies.com

Accessing Using 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.items)
10 a = Cart()
11 a.add_item("book", 3)
12 a.display_items()
Collapse

Output

{"book": 3}

Accessing Using Object

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}

Accessing Using Class

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

AttributeError: type object 'Cart' has no attribute 'items'

Accessing Class Attributes

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

Updating Class Attribute

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

Broadly, methods can be categorized as

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

cls as a parameter indicating we are passing the class.

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

@classmethod decorator marks the method below it as a class method.

We will learn more about decorators in upcoming sessions.

Accessing Class Method


300
www.spharktechnologies.com

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.

@staticmethod decorator marks the method below it as a static method.

We will learn more about decorators in upcoming sessions.

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

Have a Great Shopping

Overview of Instance, Class & Static Methods

Instance Methods Class Methods Static Methods

self as parameter cls as parameter No cls or self as parameters

Need decorator Need decorator


No decorator required
@classmethod @staticmethod

302
www.spharktechnologies.com

Instance Methods Class Methods Static Methods

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

Following are few attributes & methods for an Electronic product.

Grocery Item

Similarly, attribute & methods for a Grocery item.

304
www.spharktechnologies.com

Common Attributes & Methods

All these products Electronics, Kids Wear, Grocery etc.. have few common attributes & methods.

305
www.spharktechnologies.com

Specific Attributes & Methods

Also, each product has specific attributes & methods of its own.

Electronic & Grocery Items

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

Advantages of Modelling Classes as above

Reusability

Clear Separation

More Organized

Inheritance

Inheritance is a mechanism by which a class inherits attributes and methods from another class.

With Inheritance, we can have

ElectronicItem inherit the attributes & methods from Product instead of defining them
again.

Product is Super/Base/Parent Class and ElectronicItem is Sub/Derived/Child Class.

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

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 = GroceryItem("milk", 25, 20, 3)
21 e.display_product_details()
Collapse

Output

Product: milk Price: 25 Deal Price: 20 You Saved: 5 Ratings: 3

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

In the above example, calling

set_warranty will create an attribute warranty_in_months .

Super Class & Sub Class

Superclass cannot access the methods and attributes of the subclass.

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

AttributeError: 'Product' object has no attribute 'set_warranty'

Sub Class Method

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

Calling Super Class Method

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

Modelling instances of one class as attributes of another class is called 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

In the above example, we are modelling Product as attribute of Order

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

RecursionError: maximum recursion depth exceeded

Because

self.display_product_details() in ElectronicItem class does not call the method in the


superclass.

Super

Accessing Super Class’s Method

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__

Let's add warranty of ElectronicItem.

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

We can also inherit from a subclass. This is called MultiLevel Inheritance.

We can continue such inheritance to any depth in Python.

318
www.spharktechnologies.com

PYTHON

1 class Product:
2 pass
3
4 class ElectronicItem(Product):
5 pass
6
7 class Laptop(ElectronicItem):
8 pass

Inheritance & Composition

When to use Inheritance?

Prefer modeling with inheritance when the classes have an IS-A relationship.

319
www.spharktechnologies.com

When to use Composition?

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

Built-in functions are Readily available for reuse.

Some of the built Functions are

1. print()

2. max()

3. min()

4. len() and many more..

Standard Library

Python provides several such useful values (constants), classes and functions.

This collection of predefined utilities is referred as the Python Standard Library

All these functionalities are organized into different modules.

In Python context, any file containing a Python code is called a module

322
www.spharktechnologies.com

These modules are further organized into folders known as packages

Different modules are:

1. collections

2. random

3. datetime

4. math and many more..

Working with Standard Library

To use a functionality defined in a module we need to import that module in our


program.
PYTHON

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

Importing a module and giving it a new name (aliasing)

Code
PYTHON

1 import math as m1
2 print(m1.factorial(5))

Output

120

Importing from a Module

We can import just a specific definition from a module.

325
www.spharktechnologies.com

Code
PYTHON

1 from math import factorial


2 print(factorial(5))

Output

120

Aliasing Imports

We can also import a specific definition from a module and alias it

Code
PYTHON

1 from math import factorial as fact


2 print(fact(5))

Output

326
www.spharktechnologies.com

120

Random module

Randomness is useful in whenever uncertainty is required.

For example: Rolling a dice, flipping a coin, etc.,

random module provides us utilities to create randomness.

327
www.spharktechnologies.com

Randint

randint() is a function in random module which returns a random integer in the


given interval.

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, Filter and Reduce


We worked with different sequences (list, tuples, etc.)

To simplify working with sequences we can use

map() , filter() and reduce() functions.

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

1 numbers = list(map(int, input().split()))


2 print(numbers)

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.

The function should return True/False

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

Scope & Namespaces

Object

In general, anything that can be assigned to a variable in Python is referred to as an 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

Name or Identifier is simply a name given to 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.

Different namespaces are:

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

Modules can have various

functions and classes .

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

local , global , and finally the built-in namespaces.

Global variables

In Python, a variable defined outside of all functions is known as a global variable.

This variable name will be part of Global Namespace.

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

In Python, a variable defined inside a function is a local variable.

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,

x is not declared before assignment, python throws an error.

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

Local Variables & Global Variables

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

Modifying Global Variables

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

Errors & Exceptions

There are two major kinds of errors:

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

SyntaxError: invalid syntax

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

SyntaxError: unexpected EOF while parsing

Notice that in the above code, the syntax error is inside the

greet function, which is not used in rest of the code.

Exceptions

Even when a statement or expression is syntactically correct, it may cause an error when
an attempt is made to execute it.

Errors detected during execution are called exceptions.

Example Scenario

We wrote a program to download a Video over the Internet.

Internet is disconnected during the download

We do not have space left on the device to download the video

Example 1

Division Example

Input given by the user is not within expected values.

Code

348
www.spharktechnologies.com

PYTHON

1 def divide(a, b):


2 return a / b
3
4 divide(5, 0)

Output

ZeroDivisionError: division by zero

Example 2

Input given by the user is not within expected values.

Code
PYTHON

1
2 def divide(a, b):
3 return a / b
4
5 divide("5", "10")

Output

TypeError: unsupported operand type(s) for /: 'str' and 'str'

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'

Working With Exceptions

What happens when your code runs into an exception during execution?

The application/program crashes.

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.

Money Transfer App Scenario

350
www.spharktechnologies.com

Let’s consider we are creating an app that allows users to transfer money between them.

Bank Account Class

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

User 1 Balance: 250/-


User 2 Balance: 100/-
Transferring 50/- from User 1 to User 2
User 1 Balance: 200/-
User 2 Balance: 150/-

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

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

User 1 Balance: 25/-


User 2 Balance: 100/-
Insufficient Funds
Transferring 50/- from User 1 to User 2
User 1 Balance: 25/-
User 2 Balance: 150/-

Raising Exceptions

When your code enters an unexpected state, raise an exception to communicate it.

Built-in Exceptions

Different exception classes which are raised in different scenarios.


354
www.spharktechnologies.com

You can use the built-in exception classes with raise keyword to raise an exception in the
program.

Code

We can pass message as argument .


PYTHON

1 raise ValueError("Unexpected Value!!")

Output

ValueError:Unexpected Value!!

Bank Account Class

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

User 1 Balance: 25/-


User 2 Balance: 100/-

ValueError: Insufficient Funds

Handling Exceptions

Python provides a way to catch the exceptions that were raised so that they can be properly
handled.

Exceptions can be handled with try-except block.

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

User 1 Balance: 25/-


User 2 Balance: 100/-
False
Transferring 50/- from User 1 to User 2
User 1 Balance: 25/-
User 2 Balance: 100/-

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

While developing end-user applications, we need to handle Exceptions so that application


will not crash when used.

Handling Specific Exceptions

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

Input given by the user is not within expected values.

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

We can also access the handled exception in an object.

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

User 1 Balance: 25/-


User 2 Balance: 100/-
Insufficient Funds
<class 'ValueError'>
('Insufficient Funds',)
False
Transferring 50/- from User 1 to User 2
User 1 Balance: 25/-
U 2 B l 100/ 362
www.spharktechnologies.com

User 2 Balance: 100/-

Handling Multiple Exceptions

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

Input should be an integer

364
www.spharktechnologies.com

Working With Dates & Times

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

Commonly used classes in the datetime module are:

date class

time class

datetime class

timedelta class

Working with 'date' 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

1 from datetime import date


2 date_obj = date(2022, 2, 31)
3 print(date_obj)

Output

ValueError: day is out of range for month

Today’s Date

Class method

today() returns a date object with today’s date.

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

Attributes of Date Object

Code
PYTHON

1 from datetime import date


2
3 date_object = date(2019, 4, 13)
4 print(date_object.year)
5 print(date_object.month)
6 print(date_object.day)

Output

2019
4
13

Working with ‘time’ Class

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

Attributes of Time Object

Code
PYTHON

1 from datetime import time


2
3 time_object = time(11, 34, 56)
4 print(time_object)
5 print(time_object.hour)
6 print(time_object.minute)
7 print(time_object.second)

Output

11:34:56
11
34
56

Working with ‘datetime’ Class

Datetime

The datetime class represents a valid date and time together.

368
www.spharktechnologies.com

Example - 1

Code
PYTHON

1 from datetime import datetime


2
3 date_time_obj = datetime(2018, 11, 28, 10, 15, 26)
4 print(date_time_obj.year)
5 print(date_time_obj.month)
6 print(date_time_obj.hour)
7 print(date_time_obj.minute)

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

1 from datetime import datetime


2 date_time_obj = datetime(2018, 11, 28)
3 print(date_time_obj)

Output

2018-11-28 00:00:00

Formatting Datetime

The datetime classes have

strftime(format) method to format the datetime into any required format like

mm/dd/yyyy

dd-mm-yyyy

Format Specifier Meaning Example

Year without century as a zero-padded


%y 19, 20, ...
decimal number

%Y Year with century as a decimal number 2019, 2020, ...

%b Month as abbreviated name Jan, Feb, ...

%B Month as full name January, February

%m Month as a zero-padded decimal number 01, 02, …, 12

Day of the month as a zero-padded decimal


%d 01, 02, …, 31
number

%a Weekday as abbreviated name Sun, Mon, ...

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

Format Specifier Meaning Example

%p AM or PM AM, PM

%M Minute as a zero-padded decimal number 00, 01, …, 59

%S Second as a zero-padded decimal number 00, 01, …, 59

Code
PYTHON

1 from datetime import datetime


2
3 now = datetime.now()
4 formatted_datetime_1 = now.strftime("%d %b %Y %I:%M:%S %p")
5 print(formatted_datetime_1)
6
7 formatted_datetime_2 = now.strftime("%d/%m/%Y, %H:%M:%S")
8 print(formatted_datetime_2)

Output

05 Feb 2021 09:26:50 AM


05/02/2021, 09:26:50

Parsing Datetime

The class method

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

Working with ‘timedelta’ Class

Timedelta object represents duration.

Example 1

Code
PYTHON

1 from datetime import timedelta


2
3 delta = timedelta(days=365, hours=4)
4 print(delta)

Output

365 days, 4:00:00

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

Calculating Time Difference

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

330 days, 0:00:00


<class 'datetime.timedelta'>

Submit Feedback

373

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy