Introduction
Of
Python
Department of Information and Tehnology(IT)
MIET, Meerut ,(068)
Proposed
Lecture
Unit
Topic
Introduction: The Programming Cycle for Python , Python IDE, Interacting with
Python Programs , Elements of Python, Type Conversion.
I 08
Basics: Expressions, Assignment Statement, Arithmetic Operators, Operator
Precedence, Boolean Expression..
Conditionals: Conditional statement in Python (if-else statement, its working and
execution), Nested-if statement and Elif statement in Python, Expression Evaluation
II & Float Representation. 08
Loops: Purpose and working of loops , While loop including its working, For Loop ,
Nested Loops , Break and Continue.
Proposed
Lecture
Unit
Topic
Function: Parts of A Function , Execution of A Function , Keyword and Default
Arguments ,Scope Rules. Strings : Length of the string and perform
Concatenation and Repeat operations in it. Indexing and Slicing of Strings.
III 08
Python Data Structure : Tuples , Unpacking Sequences , Lists , Mutable
Sequences , List Comprehension , Sets , Dictionaries Higher Order Functions:
Treat functions as first class Objects , Lambda Expressions
.Sieve of Eratosthenes: generate prime numbers with the help of an algorithm
given by the Greek Mathematician named Eratosthenes, whose algorithm is
known as Sieve of Eratosthenes. File I/O : File input and output operations in
Python Programming Exceptions and Assertions Modules : Introduction ,
IV Importing Modules , Abstract Data Types : Abstract data types and ADT 08
interface in Python Programming. Classes : Class definition and other
operations in the classes , Special Methods ( such as _init_, _str_, comparison
methods and Arithmetic methods etc.) , Class Example , Inheritance ,
Inheritance and OOP.
Proposed
Lecture
Unit
Topic
Iterators & Recursion: Recursive Fibonacci , Tower Of Hanoi Search : Simple
Search and Estimating Search Time , Binary Search and Estimating Binary
V 08
Search Time Sorting & Merging: Selection Sort , Merge List , Merge Sort ,
Higher Order Sort
Text books
Text books and References:
1. Allen B. Downey, ``Think Python: How to Think Like a Computer Scientist‘‘, 2nd
5 edition, Updated for Python 3, Shroff/O‘Reilly Publishers, 2016 (
http://greenteapress.com/wp/thinkpython/)
2. Guido van Rossum and Fred L. Drake Jr, ―An Introduction to Python – Revised
and updated for Python 3.2, Network Theory Ltd., 2011.
3. .John V Guttag, ―Introduction to Computation and Programming Using Python‘‘,
Revised and expanded Edition, MIT Press ,
4. Robert Sedgewick, Kevin Wayne, Robert Dondero, ―Introduction to Programming
in Python: An Inter-disciplinary Approach, Pearson India Education Services Pvt.
Ltd., 2016
5.Timothy A. Budd, ―Exploring Python‖, Mc-Graw Hill Education (India) Private Ltd.,,
2015.
6.Kenneth A. Lambert, ―Fundamentals of Python: First Programs‖, CENGAGE
Learning, 2012.
7.Charles Dierbach, ―Introduction to Computer Science using Python: A
Computational ProblemSolving Focus, Wiley India Edition, 2013
8.Paul Gries, Jennifer Campbell and Jason Montojo, ―Practical Programming: An
Introduction to Computer Science using Python 3‖, Second edition, Pragmatic
Programmers, LLC, 2013
Introduction to Data Structure
History
6
Python was developed by Guido Van Rossum at National
Research institute for Mathematics and Computer Science in
Netherlands in 1989 (1990).
Rossum wanted the name of his new language to be short,
unique and mysterious, Inspired by Monty Python’s Flying
circus, a BBC comedy series, he named the language Python.
In 1994, Python 1.0 was released with new features like
Lambda, map, filter an reduce.
Introduction to Python
7
Python is an interpreted, object-oriented, high-level
programming language.
Python became a popular programming language, widely
used in both industry as well academia because of its
simple, concise and extensive support of libraries.
Python is recommended as first programming language for
beginner.
Introduction to Python
8
For example in C In Python
#include<stdio.h> a= 10
void main() b=20
{ print(a+b)
int a, b ;
a = 10;
b= 20;
printf(“The sum:%d”,(a+b));
}
Features of Python
9
1.Simple and easy to learn :- Python is a simple
programming language. When we read python
program, we can feel like reading English
statements. The syntaxes are very simple and only
30+ keywords are available. When compared with
other language , we can write very less number of
lines. Hence more readability and simplicity.
Cont….
10
2.Freeware and open Source:- We can use Python software without any
license and it is freeware. Therefore , anyone can freely use the code to
write new programs.
3.Platform Independent:- Once we write a python program, it can run on
any platform without rewriting once again. Internally PVM is responsible
to convert into machine understandable form.
4. Portability:- Python program are portable. I.e. we can migrate from
one platform to another platform very easily . Python programs will
provide same results on any platform.
Cont……
11
5.Both Procedure Oriented and Object Oriented:- Python
support both procedure oriented and object oriented features.
Hence we can get benefits of both like security and reusability
etc.
6. Interpreted:- there is no need to compile a program before
executing it as it is compiled at run time only. PVM(Python
virtual Machine ) is responsible to execute.
7. Extensive Library:- Python has a rich inbuilt library. Being a
programmer we can use this library directly and we are not
responsible to implement the functionality.
Limitations of Python
12
1.Instead of a compiler , Python executes with the help
of an interpreter, which results into a slight bit
slowdown of the execution process.
2. It is not recommended for mobile applications.
Installing Python in Windows
13
Python is available for almost all operating systems such as Windows,
Mac, Linux/Unix etc. The complete list of different versions of
Python found at http://www.python.org/downloasds. Steps for
installing Python in windows operating system:-
Step1:- Open an Internet browser like Mozilla, Firefox of Google
chrome . Type http://www.Python.org/in the address bar and
press enter.
Step2:-Click on Downloads and you will see the latest version of
python
i.e. Python 3.4 version downloads by clicking .
Cont….
14
Steps3:- After clicking on all Release under Downloads browser through the
page to the bottom. You will see a list of python release.
Steps4:- Click on python 3.4.2 and download it.
Step5:- Open the folder where you have downloaded the python 3.4 version
and double click on it to start the installation.
Step6:- After clicking on it you will see python first windows to set up
python 3.4.2.
Steps7:- Click on next and you will see second window which tells you to
specify the location where you want install python.
Cont….
15
Step8:- Click on finish to complete the installation.
Step9:- To check if Python is installed successfully
just press windows key.
IDENTIFIERS
16
The Python identifiers is used to recognize a variable, class, function,
module or any other object. i.e. a name in Python program is called
identifier.
Rules to define identifiers in python
1. The only allowed characters in python are:-
Alphabet symbols (either lower or upper case)
Digits (0 to 9)
Underscore symbol(_)
By mistake if we are using any other symbol like$ then we will get
syntax error.
Cash= 10 (right)
Ca$h = 20 (Wrong)
Identifiers
17
2. Identifier should not starts with digit
123total(Wrong)
Total123(Right)
3. Identifiers are case sensitive. Of course Python language is
case sensitive language.
total = 10
TOTAL = 999
Print(total) #10
Print(TOTAL) #999
Characteristics of the identifiers
18
1.Alphabet Symbols (either upper case or lower case)
2. If identifier is start with Underscore(_) then it indicate it is
private.
3.Identifiers should not start with Digits.
4. Identifiers are case sensitive.
5. We cannot use reserved words as identifiers.
e.g. def = 10(Wrong)
6. There is no length limit for python identifiers. But not
recommended to use too lengthy identifiers.
7. Dollar ($) symbol is not allowed in python.
Characteristics of the identifiers
19
For example :- Which of the following are valid python
identifiers
1) 123total(Wrong)
2) Total123(Right)
3) Java2share(Right)
4) Ca$h (Wrong)
5) _abc_abc_(Right)
6) def(Wrong)
7) If(Wrong)
Reserved Words
20
In python some words are reserved to represent some meaning of
functionality. Such types of words are called reserved words.
There are 33 reserved words available in python.
True, False , None
And, or, not, is
If, elif, else
While, for, break, continue, return, in, yield
Try, except, finally, raise, assert
Import, from, as, class, def, pass, global, nonlocal, lambda, del,
with
Cont…..
21
Note:-
1. All Reserved words in Python contain only alphabet symbols.
2. Except the following 3 Reserved words, all contain only lower case
alphabet symbols.
e.g. True, False, None.
For example
a = true(Wrong)
b = True(Right)
Write a program to show the reserved keywords
in python
22
>>>import keyword
>>>keyword.kwlist
Output:-
‘False’, ‘True’, ‘None’, ‘and’, ‘as’, ‘assert’, ‘break’, ‘class’,
‘continue’, ‘def’, ‘del’, ‘elif’, ‘else’, ‘except’, ‘finally’, ‘for’,
‘from’, ‘if’, ‘global’, ‘import’, ‘in’, ‘is’, ‘lambda’, ‘nonlocal’,
‘not’, ‘or’, ‘ pass’, ‘raise’, ‘return’, ‘ try’, ‘while’, ‘with’, yield’
Data Types
23
We can mainly categories in two types i.e. mutable and immutable data types.
Mutable means we can change its state or contents and immutable objects cannot.
Mutable Data Types
List
Dictionary
Byte array
Immutable Data Types
Int
Float
Complex
String
Tuple
Set
Bool
Integer data types(Immutable)
24
An integer is a combination of positive and negative
number including (zero) 0.
e.g. a = 10 a=5
Print(a) print(a, type(a))
Print(type(a)) Output:-
Output:- 5, <class ‘int’>
10
<class ‘int’>
We can represent int value in
following ways:-
25
1. Decimal Form (Base-10)
It is the default number system in python
The allowed digits are : 0 to 9
2. Binary Form(Base-2)
The allowed digits are : 0& 1
Literal value should be prefixed with 0b or 0B
3.Octal Form(Base-8)
The allowed digits are : 0 to 7
Literal value should be prefixed with 0o or 0O
4. Hexadecimal Form(Base-16)
26
The allowed digits are: 0to9, a-f (both lower and upper cases are allowed)
Literals value should be prefixed with 0x or 0X
For example:-
P = 100
Q = 0o100
R = 0X10c
S = 0B1010
Print(P) # 100
Print(Q) # 64
Print (R) # 268
Print(S) # 10
Float data type(Immutable)
27
• We can use float data type to represent floating point values
(decimal values)
e.g. f = 1.234
print(type(f))
print (f)
Output :-
<class ‘float’>
1.234
Note:- we can represent int value in decimal, binary, octal,
hexadecimal, form but we can represent float values only by
using decimal form.
Complex data type(immutable)
28
The complex numbers are expressed in the form of (a+bj) ,
where a and b are real numbers and j is an imaginary parts.
For example :-
C= 0B10+8j
Print(C, type(C)
Output:-
(2+8j) <class ‘complex’>
Bool Data type(immutable)
29
We can use this data type to represent Boolean values.
The only allowed values for this data type are:
True and False
Internally Python represents True as 1 and False as 0
e.g. A = 10
B = 20
C = A<B
print(C)
Output:- True
String Data Type(immutable)
30
str represent String data type.
A String is a sequence of characters enclosed within single quotes or double
quotes.
Multi-line string can be denoted using triple quotes, “’ or “’.
For example:-
S=‘Hello@123’ s= “’
Print(s, type(s)) Hello
Output:- Welcome to python programming
Hello@123 <class ‘str’> “’
Output:-
Hello
Welcome to python
programming
The string concatenation(+) operator
31
In both mathematics and programming, we use of ‘+’ operator
to add two numbers. Similarly , ‘+’ operator is used to
concatenate two different string.
For example:-
>>>’wooow’ + ‘ python programming’
‘wooowpython programming’ # Concatenates two different
strings.
Type casting
32
We can convert one type value to another type. This conversion is
called Typecasting or Type coercion.
The following are the various inbuilt functions for type casting.
1. int()
2.float()
3.complex()
4.bool()
5.str()
Implicit Type Conversion
33
Python converts data type into another data type automatically.
In this process, users don’t have to involve in this process.
a=7
print(type(a))
b = 3.0
print(type(b))
c=a+b
print(c)
print(type(c))
d=a*b
print(d)
Introduction to Data Structure
print(type(d))
Explicit Type Casting
34
In this method, Python need user involvement to convert the
variable data type into certain data type in order to the operation
required.
Mainly in type casting can be done with these data type function:
Int() : Int() function take float or string as an argument and
return int type object.
float() : float() function take int or string as an argument and
return float type object.
str() : str() function take float or int as an argument and return
string type object.
Introduction to Data Structure
Conti….
35
a=5
n = float(a)
print(n)
print(type(n))
a = 5.9
n = int(a)
print(n)
print(type(n))
Introduction to Data Structure
Conti….
36
a=5
n = str(a)
print(n)
print(type(n))
a = "5"
n = int(a)
print(n)
print(type(n))
Introduction to Data Structure
List(Mutable)
37
List is an ordered sequence of items.
It is one of the most used data type in python and is very flexible.
It is written under [] bracket.
For example:-
l= [1,2.2,’ws’] l= [1,2.2,’ws’]
Print(l, type(l)) l[2]=10
Output:- print(l, type(l))
[1,2.2,’ws’] <class ‘list’> output:-
[1,2.2,10] <class ‘list’>
Tuple
38
A Tuple is a collection of Python objects separated by
commas. In some ways a tuple is similar to a list in
terms of indexing, nested objects and repetition but a
tuple is immutable unlike lists which are mutable.
# An empty tuple
empty_tuple = ()
print (empty_tuple)
Introduction to Data Structure
Conti…
39
# One way of creation
tup = 'python', 'geeks'
print(tup)
# Another for doing the same
tup = ('python', 'geeks')
print(tup)
Introduction to Data Structure
Concatanation of tuple
40
# Code for concatenating 2 tuples
tuple1 = (0, 1, 2, 3)
tuple2 = (‘learn', ‘python')
# Concatenating above two
print(tuple1 + tuple2)
Nested tuple
41
# Code for creating nested tuples
tuple1 = (0, 1, 2, 3)
tuple2 = ('python', 'geek')
tuple3 = (tuple1, tuple2)
print(tuple3)
Dictionary(Mutable)
42
Dictionary is an unordered collection of key-value pairs.
In, python dictionaries are defined within braces {} with each item being a
pair in the form key:value
Syntax :- d= {1:’value’,2:’key’}
print(type(d))
<class ‘dict’>
For example:- d= {‘course_ name’: ‘Python’, ‘course_duration’:’3
month’}
print(d, type(d))
Output:- {‘course_name’:’Python’, ‘course_duration’: ‘3 month’}
<class ‘dic’>
Set(Immutable)
43
A set is an unordered collection of items.
Every set element is unique (no duplicates) and must be immutable.
Written under {}.
For example
S= {10,20,30,10}
Print(s, type(s))
Output:-
{10,20,30} <class ‘set’>
Operators in Python
44
Operator is a symbol that performs certain operations.
Python provides the following set of operators.
1. Arithmetic Operators
2. Relational operators or Comparison operator
3. Logical operator
4. Bitwise operator
5. Assignment operator
6. Special operator
1.Arithmetic Operator:-
45
Operator Name Example
+ Addition X+Y
- Subtraction X-Y
/ Division X/Y
* Multiplication X*Y
% Modulo operator X%Y
// Floor Division X//Y
** Exponent or Power X**Y
operator
Write a program to perform arithmetic operator
46
a = 10
b=5
print(a+b) 15
print(a-b) 5
print(a*b)50
print(a/b)2.0
print(a**a)100
print(a//b)2
Print(a%3)1
Relational or Comparison Operators
47
Operators Name Example
== Equal to a ==b
!= Not equal to a !=b
> Greater than a>b
>= Greater than equal to a>=b
< Less than a<b
<= Less than equal to a<=b
Write a program to perform relational operators
48
a=10
b=20
print("a > b is ",a>b)False
print("a >= b is ",a>=b)False
print("a <= b is ",a<=b)True
Print(“a==b is “,a==b)False
Print(“a<b is “,a<b)True
Logical Operators
49
Operator Symbol Description Example
And /\ Return True if both X<5 and X<10
statements are true
Or \/ Returns True if one of the X<5 or X<4
statements is true
Not ~ Reverse the results, returns not[x<5 and
False if the return is true x<10]
Logical operators are used as follows
50
1.Boolean type behavior (And, Or, Not)
2.Non- Boolean types behavior (0,1)
Write a program to perform Boolean operators.
X= 10
Y= 20
Print(x==10 and x<y)True
Print(x==10 and x<y and x==y)False
Print(x==10 or x<y or x==y)True
Print(not x!=10)True
Print(1 and 1)True
Print(1 and 0)False
Print(1 or 0) True
Print(not 0) True
Bitwise Operators
51
• We can deal with bits and execute an operation bit-
by-bit.
• These operators are applicable only for int and
Boolean types.
• For example:-
Print(4&5) valid
Print(10.5&5.6)Type error: unsupported operand
type(s) for &: ‘float’ and ‘float’
Table for Bitwise operators
52
Operators Descriptions
l Bitwise OR operator
& Bitwise AND operator
^ Bitwise NOT operator
~ Bitwise NOT operator
<< Bitwise left operator
>> Bitwise right operator
Precedence and Associativity of Operators in Python
53
This is used in an expression with more than one
operator with different precedence to determine
which operation to perform first.
10 + 20 * 30
10 + 20 * 30 is calculated as 10 + (20 * 30) and not
as (10 + 20) * 30
100 + 200 / 10 - 3 * 10 = ?
Conti…..
() Parentheses left-to-right
** Exponent right-to-left
Multiplication/
* / % left-to-right
division/modulus
+ – Addition/subtraction left-to-right
Conditional statement in python
55
if statement: if statement is the most simple
decision-making statement. It is used to decide
whether a certain statement or block of statements
will be executed or not i.e if a certain condition is
true then a block of statement is executed otherwise
not.
Syntax:
if condition:
# Statements to execute if
# condition is true Introduction to Data Structure
Conti….
56
Conti…..
57
# python program to illustrate If statement
i = 10
if (i > 15):
print("10 is less than 15")
print("I am Not in if")
Introduction to Data Structure
Conti….
58
if-else: The if statement alone tells us that if a
condition is true it will execute a block of statements
and if the condition is false it won’t. But what if we
want to do something else if the condition is false.
Here comes the else statement. We can use
the else statement with if statement to execute a block
of code when the condition is false.
Conti…
59
Syntax:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
Conti…
60
Conti….
61
i = 20
if (i < 15):
print("i is smaller than 15")
print("i'm in if Block")
else:
print("i is greater than 15")
print("i'm in else Block")
print("i'm not in if and not in else Block")
Conti….
62
nested-if: A nested if is an if statement that is the
target of another if statement. Nested if statements
mean an if statement inside another if statement. Yes,
Python allows us to nest if statements within if
statements. i.e, we can place an if statement inside
another if statement.
Conti….
63
Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
conti….
64
i = 15
if (i == 15):
if (i < 20):
print("i is smaller than 20")
if (i < 25):
print("i is smaller than 25 too")
else:
print("i is greater than 20")
Conti…
65
elif statements:
Syntax:
i = 20
if (i == 10):
print("i is 10")
elif (i == 15):
print("i is 15")
elif (i == 20):
print("i is 20")
else:
print("i is not present")
Loops
In general, statements are executed sequentially: The
first statement in a function is executed first,
followed by the second, and so on. There may be a
situation when you need to execute a block of code
several number of times.
A loop statement allows us to execute a statement or
group of statements multiple times.
Conti…
67
while loop: Repeats a statement or group of statements
while a given condition is TRUE. It tests the condition
before executing the loop body.
Syntax:
while expression:
statement(s)
Here, statement(s) may be a single statement or a block
of statements. The condition may be any expression,
and true is any non-zero value. The loop iterates while
the condition is true.
Conti…
68
Example:
i=1
while (i < 6):
print(i)
i += 1
number = 2
while (number < 5) :
print("Thank you")
number = number+1
Python For Loops
69
A for loop is used for iterating over a sequence (that
is either a list, a tuple, a dictionary, a set, or a string).
Example:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
for x in "banana":
print(x)
Conti…
70
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
sum = 0
for val in numbers:
sum = sum + val
print("The sum is", sum)
The continue Statement
71
With the continue statement we can stop the current
iteration of the loop, and continue with the next:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue # do not print banana
print(x)
Break statement
72
The break statement is used to terminate the loop or
statement in which it is present.
If the break statement is present in the nested loop,
then it terminates only those loops which
contains break statement.
Syntax:
break
Conti…
73
for val in "string":
if val == "i":
break
print(val)
print("The end")
Introduction to Data Structure
Conti….
74
for letter in 'Python’:
if letter == 'h’:
break
print ('Current Letter :’, letter)
Conti…..
75
var = 10
while var > 0:
print ('Current variable value :', var)
var = var -1
if var == 5:
break
print ("Good bye!”)
The range() Function
76
The range() function returns a sequence of numbers,
starting from 0 by default, and increments by 1 (by
default), and ends at a specified number.
Example:
for x in range(6):
print(x)
Conti…
77
Example:
for x in range(2, 6):
print(x)
print(range(10))
print(list(range(10)))
print(list(range(2, 8)))
print(list(range(2, 20, 3)))
Conti….
78
# Program to iterate through a list using indexing
genre = ['pop', 'rock', 'jazz']
for i in range(len(genre)):
print("I like", genre[i])
Python String
79
In Python, Strings are arrays of bytes representing
Unicode characters.
However, Python does not have a character data type,
a single character is simply a string with a length of
1.
Square brackets can be used to access elements of the
string.
Conti…
80
String1 = 'Welcome to the Geeks World'
print(String1)
String1 = "I’m reading AI"
print(String1)
# For creating multiline string
String1 = '''Geeks
For
Life'''
print("\nCreating a multiline String: ")
print(String1)
String Length
81
To get the length of a string, use the len() function.
Example
a = "Hello, World!"
print(len(a))
Check String
82
To check if a certain phrase or character is present in
a string, we can use the keyword in.
Example
txt = ”Hello AI students!"
print(”students" in txt)
print(”IT" in txt)
Conti…
83
Use it in an if statement
txt = ”Hello AI students"
if ”students" in txt:
print("Yes, ‘student' is present.")
Check if NOT
84
txt = ”Hello AI students!"
print("expensive" not in txt)
#Use of if
txt = "The best things in life are free!"
if "expensive" not in txt:
print("No, 'expensive' is NOT present.")
Accessing characters in Python
85
In Python, individual characters of a String can be
accessed by using the method of Indexing.
Indexing allows negative address references to access
characters from the back of the String.
e.g. -1 refers to the last character, -2 refers to the
second last character, and so on.
NOTE: While accessing an index out of the range will
cause an IndexError. Only Integers are allowed to be
passed as an index, float or other types that will cause
a TypeError.
Conti….
86
Conti….
87
String1 = ”PadhAI”
print("Initial String: ")
print(String1)
print(String1[0])
print(String1[-1])
String Slicing
88
To access a range of characters in the String, the method of
slicing is used.
Slicing in a String is done by using a Slicing operator
(colon).
Example:
String1 = ”Hello AI students"
print("Initial String: ")
print(String1)
print(String1[3:12])
print(String1[3:-2])
Conti…
89
#Slice From the Start
b = "Hello, World!"
print(b[:5])
#Slice To the End
b = "Hello, World!"
print(b[2:])
Negative Indexing
90
Example
b = "Hello, World!"
print(b[-5:-2])
Deleting/Updating from a String
91
In Python, Updation or deletion of characters from a
String is not allowed.
Although deletion of the entire String is possible with
the use of a built-in del keyword.
This is because Strings are immutable, hence
elements of a String cannot be changed once it has
been assigned.
Conti…
92
Example:
String1 = "Hello AI students"
print(String1)
String1[2] = 'p'
print(String1)
Error
Traceback (most recent call last):
File “/home/360bb1830c83a918fc78aa8979195653.py”, line
10, in
String1[2] = ‘p’
TypeError: ‘str’ object does not support item assignment
Updating Entire String
93
String1 = "Hello AI students"
print("Initial String: ")
print(String1)
String1 = " woooow"
print(String1)
Deletion of a character
94
String1 = "Hello, I'm a Geek"
print("Initial String: ")
print(String1)
del String1[2]
print(String1)
Error
Traceback (most recent call last):
File “/home/499e96a61e19944e7e45b7a6e1276742.py”, line
10, in
del String1[2]
TypeError: ‘str’ object doesn’t support item deletion
Deleting Entire String
95
Deletion of the entire string is possible with the use
of del keyword.
Further, if we try to print the string, this will produce
an error because String is deleted and is unavailable
to be printed.
Example:
String1 = "Hello AI students"
print(String1)
del String1
print(String1)
Formatting of Strings
96
Strings in Python can be formatted with the use of
format() method which is a very versatile and
powerful tool for formatting Strings.
Format method in String contains curly braces {} as
placeholders which can hold arguments according to
position or keyword to specify the order.
Conti…
97
String1 = "{} {} {}".format(‘Hello', ‘AI', ‘students')
print(String1)
String1 = "{1} {0} {2}".format(‘hello', ‘AI',
‘students')
print(String1)
String1 = "{l} {f} {g}".format(g=‘Hello', f=‘AI',
l=‘students')
print(String1)
Conti……
98
#Upper case
a = "Hello, World!"
print(a.upper())
#Lower Case
a = "Hello, World!"
print(a.lower())
Conti…
99
#Remove Whitespace
Example
The strip() method removes any whitespace from the
beginning or the end:
a = " Hello, World! "
print(a.strip())
Conti….
100
#Replace String
The replace() method replaces a string with another
string:
a = "Hello, World!"
print(a.replace("H", "J"))
Conti….
101
#String Concatenation
a = "Hello"
b = "World"
c=a+b
print(c)
Python Functions
102
A function is a block of code which only runs when it
is called.
You can pass data, known as parameters, into a
function.
A function can return data as a result.
Conti…
103
Creating a Function
In Python a function is defined using the def keyword:
Example:
def my_function():
print("Hello from a function")
#Calling a Function
my_function()
Conti…
104
#Arguments
Information can be passed into functions as
arguments.
Arguments are specified after the function name,
inside the parentheses. You can add as many
arguments as you want, just separate them with a
comma.
Conti….
105
Example
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Conti….
106
Example
This function expects 2 arguments, and gets 2
arguments:
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil", "Refsnes")
Conti….
107
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil")
Arbitrary Arguments, *args
108
If you do not know how many arguments that will be
passed into your function, add a * before the parameter
name in the function definition.
Example
If the number of arguments is unknown, add a * before
the parameter name:
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
Conti….
109
def myFun(*argv):
for arg in argv:
print(arg)
myFun('Hello', 'Welcome', 'to', ‘MIET')
Keyword Arguments
110
You can also send arguments with
the key = value syntax.
This way the order of the arguments does not matter.
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias",
child3 = "Linus")
Default Parameter Value
111
If we call the function without argument, it uses the default
value.
Example:
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Passing a List as an Argument
112
You can send any data types of argument to a function
(string, number, list, dictionary etc.), and it will be
treated as the same data type inside the function.
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
Conti….
113
#Return Values
Example
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Conti…
114
def square_value(num):
return num**2
print(square_value(2))
print(square_value(-4))
Python Scope
115
Local Scope: A variable created inside a function belongs
to the local scope of that function, and can only be used
inside that function.
Example
A variable created inside a function is available inside that
function:
def myfunc():
x = 300
print(x)
myfunc()
Conti….
116
Global Scope: A variable created in the main body of the
Python code is a global variable and belongs to the global scope.
Global variables are available from within any scope, global and
local.
Example:
x = 20
def my_function():
print(x)
My_function()
Print(x)
Naming Variables
117
If you operate with the same variable name inside and outside
of a function, Python will treat them as two separate variables,
one available in the global scope (outside the function) and
one available in the local scope (inside the function):
x = 20
def my_function():
x = 30
print(x)
my_function()
print(x)
Global Keyword
118
If you need to create a global variable, but are stuck in the
local scope, you can use the global keyword.
The global keyword makes the variable global.
Example
If you use the global keyword, the variable belongs to the
global scope:
def my_func():
global x
x = 200
myfunc()
print(x)
Conti…
119
Also, use the global keyword if you want to make a change to a global
variable inside a function.
To change the value of a global variable inside a function, refer to the
variable by using the global keyword:
x = 300
def my_func():
global x
x = 200
my_func()
print(x)
Python Lambda Functions
120
Python Lambda Functions are anonymous function
means that the function is without a name. As we
already know that the def keyword is used to define a
normal function in Python. Similarly,
the lambda keyword is used to define an anonymous
function in Python.
Python Lambda Function Syntax:
lambda arguments: expression
Conti….
121
This function can have any number of arguments but
only one expression, which is evaluated and returned.
One is free to use lambda functions wherever
function objects are required.
You need to keep in your knowledge that lambda
functions are syntactically restricted to a single
expression.
Conti….
122
x = lambda a : a + 10
print(x(5))
# Multiply argument a with argument b and return the
result:
x = lambda a, b : a * b
print(x(5, 6))
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
Python Data Structures
123
Data Structures are a way of organizing data so that
it can be accessed more efficiently depending upon
the situation.
Python helps to learn the fundamental of these data
structures in a simpler way as compared to other
programming languages.
We will discuss all the in-built data structures like list
tuples, dictionaries, etc.
List
124
Python list are just like the arrays, declared in other
languages which is an ordered collection of data. It is
very flexible as the items in a list do not need to be of
the same type.
The costly operation is inserting or deleting the
element from the beginning of the List as all the
elements are needed to be shifted.
Conti…
125
Lists are used to store multiple items in a single
variable.
Lists are created using square brackets:
Example:
List = [1, 2, 3, "GFG", 2.3]
print(List)
Print(type(List))
Conti…
126
List Items:
List items are ordered, changeable, and allow
duplicate values.
List items are indexed, the first item has index [0],
the second item has index [1] etc.
Conti…
127
Ordered:
When we say that lists are ordered, it means that the
items have a defined order, and that order will not
change.
If you add new items to a list, the new items will be
placed at the end of the list.
Conti….
128
Changeable:
The list is changeable, meaning that we can change,
add, and remove items in a list after it has been
created.
Allow Duplicates:
Since lists are indexed, lists can have items with the
same value:
Conti…
129
My_list=["apple", "banana", "cherry", "apple", "cherry"
]
print(my_list)
#list length:
Print(len(my_list))
List Items - Data Types
130
List items can be of any data type
Example
String, int and boolean data types:
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
Conti….
131
A list can contain different data types:
Example:
list2 = ["abc", 34, True, 40, "male"]
Print(list2)
#type()
Example
Print(type(list2))
<class 'list'>
Conti…
132
The list() Constructor
It is also possible to use the list() constructor when
creating a new list.
Example
Using the list() constructor to make a List:
my_list = list(("apple", "banana", "cherry"))
print(my_list)
Conti…
133
Access Items:
List items are indexed and you can access them by
referring to the index number:
Example
Print the second item of the list:
Note: The first item has index 0.
My_list = ["apple", "banana", "cherry"]
Conti….
134
Negative Indexing:
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last
item etc.
Example
Print the last item of the list:
my_list = ["apple", "banana", "cherry"]
Conti…
135
Range of Indexes:
You can specify a range of indexes by specifying where to
start and where to end the range.
When specifying a range, the return value will be a new list
with the specified items.
my_list=
["apple", "banana", "cherry", "orange", "kiwi", "melon", "man
go"]
print(my_list[2:5])
Note: The search will start at index 2 (included) and end at
index 5 (not included).
Conti…
136
By leaving out the start value, the range will start at
the first item:
Example
This example returns the items from the beginning to,
but NOT including, "kiwi":
my_list =
["apple", "banana", "cherry", "orange", "kiwi", "melo
n", "mango"]
Print(my_list[:5]
Conti….
137
By leaving out the end value, the range will go on to the
end of the list:
Example
This example returns the items from "cherry" to the
end:
my_list =
["apple", "banana", "cherry", "orange", "kiwi", "melon",
"mango"]
Print(my_list[2:]
Conti…
138
Range of Negative Indexes
Specify negative indexes if you want to start the
search from the end of the list:
Example
my_list =
["apple", "banana", "cherry", "orange", "kiwi", "melo
n", "mango"]
print(my_list[-4:-1])
Conti…
139
Check if Item Exists
To determine if a specified item is present in a list use
the in keyword:
Example
Check if "apple" is present in the list:
my_list = ["apple", "banana", "cherry"]
if "apple" in my_list:
print("Yes, 'apple' is in the fruits list")
Change Item Value
140
To change the value of a specific item, refer to the
index number:
Example
Change the second item:
list1 = ["apple", "banana", "cherry"]
list1[1] = ”mango"
print(list1)
Change a Range of Item Values
141
To change the value of items within a specific range,
define a list with the new values, and refer to the range of
index numbers where you want to insert the new values:
Example
Change the values "banana" and "cherry" with the values
”mango" and "watermelon":
list1 =
["apple", "banana", "cherry", "orange", "kiwi", "mango"]
list1[1:3] = [”mango", "watermelon"]
print(list1)
Conti…
142
NOTE:If you insert more items than you replace, the
new items will be inserted where you specified, and
the remaining items will move accordingly
Example
Change the second value by replacing it
with two new values:
list2 = ["apple", "banana", "cherry"]
list2[1:2] = [”mango", "watermelon"]
print(list2)
Conti….
143
If you insert less items than you replace, the new
items will be inserted where you specified, and the
remaining items will move accordingly
Example
Change the second and third value by replacing it
with one value:
list3 = ["apple", "banana", "cherry"]
list3[1:3] = ["watermelon"]
print(list3)
Insert Items
144
To insert a new list item, without replacing any of the
existing values, we can use the insert() method.
The insert() method inserts an item at the specified
index:
Insert "watermelon" as the third item:
list4 = ["apple", "banana", "cherry"]
list4.insert(2, "watermelon")
print(list4)
Note: As a result of the example above, the list will
now contain 4 items.
Append Items
145
To add an item to the end of the list, use
the append() method:
Example
Using the append() method to append an item:
list5 = ["apple", "banana", "cherry"]
list5.append("orange")
print(list5)
Extend List
146
To append elements from another list to the current
list, use the extend() method.
Example
Add the elements of tropical to thislist:
list6 = ["apple", "banana", "cherry"]
list7 = ["mango", "pineapple", "papaya"]
list6.extend(list7)
print(list6)
Remove Specified Item in list
147
The remove() method removes the specified item.
Example
Remove "banana":
list8 = ["apple", "banana", "cherry"]
list8.remove("banana")
print(list8)
Remove Specified Index
148
The pop() method removes the specified index.
Example
Remove the second item:
list9 = ["apple", "banana", "cherry"]
list9.pop(1)
print(list9)
Conti…
149
list10 = ["apple", "banana", "cherry"]
list10.pop()
print(list10) ?
#The del keyword also removes the specified index:
Remove the first item:
del list10[0]
print(list10)
Conti…
150
The del keyword can also delete the list completely.
Example
Delete the entire list:
list11 = ["apple", "banana", "cherry"]
del list11
Clear the List
151
The clear() method empties the list.
The list still remains, but it has no content.
Example
Clear the list content:
list12 = ["apple", "banana", "cherry"]
list12.clear()
print(list12)
Loop Through a List:
152
You can loop through the list items by using
a for loop:
Example
Print all items in the list, one by one:
list1 = ["apple", "banana", "cherry"]
for x in list1:
print(x)
Loop Through the Index Numbers
153
You can also loop through the list items by referring
to their index number.
Use the range() and len() functions to create a
suitable iterable.
list2 = ["apple", "banana", "cherry"]
for i in range(len(list2)):
print(list2[i])
Using a While Loop
154
DO YOURSELF
List Comprehension
155
List comprehension offers a shorter syntax when you
want to create a new list based on the values of an
existing list.
Example:
Based on a list of fruits, you want a new list,
containing only the fruits with the letter "a" in the
name.
Without list comprehension you will have to write
a for statement with a conditional test inside:
Conti….
156
fruits =
["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
Conti….
157
With list comprehension you can do all that with only one line
of code:
Syntax
newlist = [expression for item in iterable if condition == True]
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)
Conti…
158
Iterable
The iterable can be any iterable object, like a list,
tuple, set etc.
Example
You can use the range() function to create an iterable:
newlist = [x for x in range(10)]
#Accept only numbers lower than 5
newlist = [x for x in range(10) if x < 5]
Expression
159
The expression is the current item in the iteration, but
it is also the outcome, which you can manipulate
before it ends up like a list item in the new list.
Example
Set the values in the new list to upper case:
newlist = [x.upper() for x in fruits]
#You can set the outcome to whatever you like:
newlist = ['hello' for x in fruits]
Conti….
160
The expression can also contain conditions, not like a filter,
but as a way to manipulate the outcome:
Example
Return "orange" instead of "banana":
newlist = [x if x != "banana" else "orange" for x in fruits]
Sort Lists
161
Sort List Alphanumerically
List objects have a sort() method that will sort the list
alphanumerically, ascending, by default:
fruits = ["orange", "mango", "kiwi", "pineapple", "banana"]
fruits.sort()
print(fruits)
Conti….
162
Sort the list numerically:
number = [100, 50, 65, 82, 23]
number.sort()
print(number)
Sort Descending
163
To sort descending, use the keyword argument reverse = True
Sort the list descending:
fruits = ["orange", "mango", "kiwi", "pineapple", "banana"]
fruits.sort(reverse = True)
print(fruits)
number = [100, 50, 65, 82, 23]
number.sort(reverse = True)
print(number)
Customize Sort Function
164
You can also customize your own function by using the keyword
argument key = function.
The function will return a number that will be used to sort the list
(the lowest number first):
Example
Sort the list based on how close the number is to 50:
def my_func(n):
return abs(n - 50)
list1 = [100, 50, 65, 82, 23]
list1.sort(key = my_func)
print(list1)
Case Insensitive Sort
165
By default the sort() method is case sensitive, resulting in all
capital letters being sorted before lower case letters:
Example
Case sensitive sorting can give an unexpected result:
list2 = ["banana", "Orange", "Kiwi", "cherry"]
list2.sort()
print(list2)
Conti….
166
Luckily we can use built-in functions as key
functions when sorting a list.
So if you want a case-insensitive sort function, use
str.lower as a key function
Example
Perform a case-insensitive sort of the list:
list3 = ["banana", "Orange", "Kiwi", "cherry"]
list3.sort(key = str.lower)
print(list3)
Reverse Order
167
What if you want to reverse the order of a list,
regardless of the alphabet?
The reverse() method reverses the current sorting
order of the elements.
Example
Reverse the order of the list items:
list5 = ["banana", "Orange", "Kiwi", "cherry"]
list5.reverse()
print(list5)
Copy a List
168
You cannot copy a list simply by typing list2 = list1,
because: list2 will only be a reference to list1, and
changes made in list1 will automatically also be made
in list2.
There are ways to make a copy, one way is to use the
built-in List method copy().
list6 = ["apple", "banana", "cherry"]
list7 = list6.copy()
print(list7)
Conti….
169
Another way to make a copy is to use the built-in
method list().
Example
Make a copy of a list with the list() method:
list8 = ["apple", "banana", "cherry"]
list9 = list(list8)
print(list9)
Python Collections (Arrays)
170
There are four collection data types in the Python
programming language:
List is a collection which is ordered and changeable.
Allows duplicate members.
Tuple is a collection which is ordered and
unchangeable. Allows duplicate members.
Set is a collection which is unordered, unchangeable,
and unindexed. No duplicate members.
Dictionary is a collection which is ordered and
changeable. No duplicate members.
Tuple
171
Tuples are used to store multiple items in a single
variable.
Tuple is one of 4 built-in data types in Python used to
store collections of data, the other 3 are List, Set, and
Dictionary, all with different qualities and usage.
A tuple is a collection which is ordered
and unchangeable.
Tuples are written with round brackets.
Conti…
172
Example:
tuple1 = ("apple", "banana", "cherry")
print(tuple1)
Tuple Items
173
Tuple items are ordered, unchangeable, and allow
duplicate values.
Tuple items are indexed, the first item has index [0],
the second item has index [1] etc.
Property of tuple:
174
Ordered
When we say that tuples are ordered, it means that the
items have a defined order, and that order will not change.
Unchangeable
Tuples are unchangeable, meaning that we cannot change,
add or remove items after the tuple has been created.
Allow Duplicates
Since tuples are indexed, they can have items with the
same value:
Conti…
175
Tuple Length
To determine how many items a tuple has, use
the len() function:
Example
Print the number of items in the tuple:
tuple2 = ("apple", "banana", "cherry")
print(len(tuple2))
Conti…
176
Create Tuple With One Item
To create a tuple with only one item, you have to add a comma
after the item, otherwise Python will not recognize it as a tuple.
Example
One item tuple, remember the comma:
tuple3 = ("apple",)
print(type(tuple3))
#NOT a tuple
tuple4 = ("apple")
print(type(tuple4))
Conti…
177
Tuple Items - Data Types
Tuple items can be of any data type:
String, int and boolean data types:
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
A tuple can contain different data types:
A tuple with strings, integers and boolean values:
tuple1 = ("abc", 34, True, 40, "male")
The tuple() Constructor
178
It is also possible to use the tuple() constructor to
make a tuple.
Example
Using the tuple() method to make a tuple:
tuple5 = tuple(("apple", "banana", "cherry"))
print(tuple5)
Access Tuple Items
179
You can access tuple items by referring to the index
number, inside square brackets:
Example
Print the second item in the tuple:
tuple6 = ("apple", "banana", "cherry")
print(tuple6[1])
Note: The first item has index 0.
Negative Indexing
180
Negative indexing means start from the end.
-1 refers to the last item, -2 refers to the second last
item etc.
Example: Print the last item of the tuple:
tuple7 = ("apple", "banana", "cherry")
print(tuple7[-1])
Range of Indexes
181
You can specify a range of indexes by specifying
where to start and where to end the range.
When specifying a range, the return value will be a
new tuple with the specified items.
Example: Return the third, fourth, and fifth item:
tuple8 =
("apple", "banana", "cherry", "orange", "kiwi", "melon
", "mango")
print(tuple8[2:5])
Note: The search will start at index 2 (included) and
end at index 5 (not included).
Conti…
182
tuple9 =
("apple", "banana", "cherry", "orange", "kiwi", "melo
n", "mango")
print(tuple9[:4])
print(tuple9[2:])
Range of Negative Indexes
183
Specify negative indexes if you want to start the
search from the end of the tuple:
Example
This example returns the items from index -4
(included) to index -1 (excluded)
tuple10 =
("apple", "banana", "cherry", "orange", "kiwi", "melo
n", "mango")
print(tuple10[-4:-1])
Check if Item Exists
184
To determine if a specified item is present in a tuple
use the in keyword:
Example: Check if "apple" is present in the tuple:
tuple11 = ("apple", "banana", "cherry")
if "apple" in tuple11:
print("Yes, 'apple' is in the fruits tuple")
Update Tuples
185
Change Tuple Values
Once a tuple is created, you cannot change its values.
Tuples are unchangeable, or immutable as it also is
called.
But there is a workaround. You can convert the tuple
into a list, change the list, and convert the list back
into a tuple.
Conti….
186
Example
Convert the tuple into a list to be able to change it:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
Add Items
187
Since tuples are immutable, they do not have a build-
in append() method, but there are other ways to add
items to a tuple.
1. Convert into a list: Just like the workaround
for changing a tuple, you can convert it into a list, add
your item(s), and convert it back into a tuple.
2. Add tuple to a tuple. You are allowed to add
tuples to tuples, so if you want to add one item, (or
many), create a new tuple with the item(s), and add it
to the existing tuple:
Conti…
188
Example1
tuple12 = ("apple", "banana", "cherry")
y = list(tuple12)
y.append("orange")
tuple12 = tuple(y)
Example2
tuple12 = ("apple", "banana", "cherry")
y = ("orange",)
tuple12 += y
print(tuple12)
Remove Items
189
Tuples are unchangeable, so you cannot remove items
from it, but you can use the same workaround as we
used for changing and adding tuple items:
Example
Convert the tuple into a list, remove "apple", and
convert it back into a tuple:
tuple13 = ("apple", "banana", "cherry")
y = list(tuple13)
y.remove("apple")
tuple13 = tuple(y)
Conti…
190
You can delete the tuple completely:
The del keyword can delete the tuple completely:
Example
tuple13 = ("apple", "banana", "cherry")
del tuple13
print(tuple13) #this will raise an error because the
tuple no longer exists
Unpacking a Tuple
191
When we create a tuple, we normally assign values to it. This
is called "packing" a tuple. But, in Python, we are also
allowed to extract the values back into variables. This is
called "unpacking”.
fruits = ("apple", "banana", "cherry") # Packing a tuple
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green) # unpacking of tuple
print(yellow)
print(red)
Using Asterisk*
192
If the number of variables is less than the number of values, you
can add an * to the variable name and the values will be
assigned to the variable as a list
Assign the rest of the values as a list called "red”
Example
fruits = ("apple", "banana", "cherry", "strawberry”, ”melon”)
(green, yellow, *red) = fruits
print(green)
print(yellow)
print(red)
Conti…
193
What will be the output of following code ?
fruits = ("apple", "mango", "papaya", "pineapple", "cherry")
(green, *tropic, red) = fruits
print(green) ?
print(tropic) ?
print(red) ?
Loop Tuples
194
Loop Through a Tuple
You can loop through the tuple items by using a for loop.
Example
Iterate through the items and print the values:
tuple14 = ("apple", "banana", "cherry")
for x in tuple14:
print(x)
Loop Through the Index Numbers
195
You can also loop through the tuple items by
referring to their index number.
Use the range() and len() functions to create a
suitable iterable.
Example
Print all items by referring to their index number:
tuple14 = ("apple", "banana", "cherry")
for i in range(len(tuple14)):
print(tuple14[i])
Using a While Loop
196
Do yourself
Join Tuples
197
Join Two Tuples
To join two or more tuples you can use the + operator.
Join two tuples:
Example
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
Multiply Tuples
198
If you want to multiply the content of a tuple a given
number of times, you can use the * operator.
Multiply the fruits tuple by 2.
Example
fruits = ("apple", "banana", "cherry")
tuple15 = fruits * 2
print(tuple15)
Set
199
Sets are used to store multiple items in a single
variable.
Set is one of 4 built-in data types in Python used to
store collections of data, the other 3 are List, Tuple,
and Dictionary, all with different qualities and usage.
A set is a collection which
is unordered, unchangeable*, and unindexed.
Conti…
200
Sets are written with curly brackets.
Example
set1 = {"apple", "banana", "cherry"}
print(set1)
Note: Sets are unordered, so you cannot be sure in
which order the items will appear.
Property od set
201
Unordered
Unordered means that the items in a set do not have a
defined order.
Set items can appear in a different order every time you use
them, and cannot be referred to by index or key.
Unchangeable
Set items are unchangeable, meaning that we cannot
change the items after the set has been created.
Once a set is created, you cannot change its items, but you
can remove items and add new items.
Duplicates Not Allowed
Conti…
202
Duplicate values will be ignored:
Example
set2 = {"apple", "banana", "cherry", "apple"}
print(set2)
Conti…
203
Get the Length of a Set
To determine how many items a set has, use
the len() function.
Get the number of items in a set
Example
set3 = {"apple", "banana", "cherry"}
print(len(set3))
Conti…
204
Set Items - Data Types
Set items can be of any data type
String, int and boolean data types:
set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
A set with strings, integers and boolean values:
set1 = {"abc", 34, True, 40, "male"}
Conti…
205
The set() Constructor
It is also possible to use the set() constructor to make
a set.
Using the set() constructor to make a set:
set3 = set(("apple", "banana", "cherry"))
print(set3)
Access Items
206
You cannot access items in a set by referring to an index or a
key.
But you can loop through the set items using a for loop, or
ask if a specified value is present in a set, by using
the in keyword.
Example
Loop through the set, and print the values:
set2 = {"apple", "banana", "cherry"}
for x in set2:
print(x)
Conti…
207
Check if "banana" is present in the set:
set4 = {"apple", "banana", "cherry"}
print("banana" in set4)
Change Items
Once a set is created, you cannot change its items, but
you can add new items.
Conti…
208
Add Items
To add one item to a set use the add() method.
set3 = {"apple", "banana", "cherry"}
set3.add("orange")
print(set3)
Add Sets
209
To add items from another set into the current set, use
the update() method.
set5 = {"apple", "banana", "cherry"}
set6 = {"pineapple", "mango", "papaya"}
set5.update(set6)
print(set5)
Remove Set Items
210
To remove an item in a set, use the remove(), or
the discard() method.
Remove "banana" by using the remove() method:
set7 = {"apple", "banana", "cherry"}
set7.remove("banana")
print(set7)
Conti…
211
Remove "banana" by using the discard() method:
set7 = {"apple", "banana", "cherry"}
set7.discard("banana")
print(set7)
Remove the last item by using the pop() method:
set8 = {"apple", "banana", "cherry"}
x = set8.pop()
print(x)
print(set8)
Conti…
212
The clear() method empties the set:
set10 = {"apple", "banana", "cherry"}
set10.clear()
print(set10)
The del keyword will delete the set completely:
set10 = {"apple", "banana", "cherry"}
del set10
print(set10)
Conti…
213
Loop Items
You can loop through the set items by using
a for loop
Loop through the set, and print the values
set11 = {"apple", "banana", "cherry"}
for x in set11:
print(x)
Join Two Sets
214
There are several ways to join two or more sets in Python.
You can use the union() method that returns a new set
containing all items from both sets, or the update() method
that inserts all the items from one set into another:
The union() method returns a new set with all items from
both sets:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
Conti…
215
The update() method inserts the items in set2 into
set1:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)
Dictionary
216
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable
and do not allow duplicates.
Example
Create and print a dictionary:
dict= {"brand": "Ford","model": "Mustang","year": 1964}
print(dict)
print(type(dict))
Dictionary Items
217
Dictionary items are ordered, changeable, and does not
allow duplicates.
Dictionary items are presented in key: value pairs, and
can be referred to by using the key name.
Example:
Print the "brand" value of the dictionary:
dict
= {"brand": "Ford","model": "Mustang","year": 1964}
print(dict["brand"])
Property of dictionary:
218
Ordered.
Changeable.
Duplicates are not allowed.
thisdict
= {"brand": "Ford","model": "Mustang","year": 1964,"yea
r": 2020}
print(thisdict)
Conti…
219
Dictionary Length
To determine how many items a dictionary has, use
the len() function:
print(len(thisdict))
Conti…
220
Dictionary Items - Data Types
The values in dictionary items can be of any data type:
Example:
thisdict
= {"brand": "Ford","electric": False, "year": 1964,"color
s": ["red", "white", "blue"] }
type()
From Python's perspective, dictionaries are defined as
objects with the data type 'dict':
Conti…
221
Accessing Items
You can access the items of a dictionary by referring to its
key name, inside square brackets:
thisdict
= {"brand": "Ford","model": "Mustang","year": 1964}
x = thisdict["model"]
OR
x = thisdict.get("model")
Conti…
222
Get Keys
The keys() method will return a list of all the keys in the
dictionary.
Syntax: x = thisdict.keys()
car = {"brand": "Ford","model": "Mustang","year": 1964}
x = car.keys()
print(x)
car["color"] = "white"
print(x)
Conti…
223
Get Values
The values() method will return a list of all the values
in the dictionary.
Syntax: x = thisdict.values()
car =
{"brand": "Ford","model": "Mustang","year": 1964}
x = car.values()
print(x)
car["year"] = 2020
print(x)
Conti….
224
car =
{"brand": "Ford","model": "Mustang","year": 1964}
x = car.values()
print(x)
car["color"] = "red"
print(x)
Conti…
225
Check if Key Exists
To determine if a specified key is present in a dictionary use
the in keyword:
Example:
thisdict = {"brand": "Ford","model": "Mustang","year": 1964}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict
dictionary")
Conti….
226
Change Values
You can change the value of a specific item by referring to
its key name:
Example:
thisdict= {"brand": "Ford","model": "Mustang","year": 196
4}
thisdict["year"] = 2018
Conti…
227
Update Dictionary
The update() method will update the dictionary with the items
from the given argument.
The argument must be a dictionary, or an iterable object with
key: value pairs.
Example:
thisdict = {"brand": "Ford","model": "Mustang","year": 1964}
thisdict.update({"year": 2020})
Conti…
228
Adding Items
Adding an item to the dictionary is done by using a new
index key and assigning a value to it:
Example:
thisdict
= {"brand": "Ford","model": "Mustang","year": 1964}
thisdict["color"] = "red"
print(thisdict)
Conti…
229
Removing Items
There are several methods to remove items from a dictionary:
The pop() method removes the item with the specified key
name:
Example:
Thisdict = { "brand": "Ford","model": "Mustang","year":1964}
thisdict.pop("model")
print(thisdict)
Conti…
230
The del keyword removes the item with the specified key
name:
thisdict
= {"brand": "Ford","model": "Mustang","year": 1964}
del thisdict["model"]
print(thisdict)
The del keyword can also delete the dictionary
completely:
del thisdict
print(thisdict)
Conti…
231
The clear() method empties the dictionary:
Thisdict =
{"brand": "Ford","model": "Mustang","year": 1964}
thisdict.clear()
print(thisdict)
Conti….
232
Loop Through a Dictionary
You can loop through a dictionary by using a for loop.
When looping through a dictionary, the return value
are the keys of the dictionary, but there are methods to
return the values as well.
Example:
Print all key names in the dictionary, one by one:
for x in thisdict:
print(x)
Conti…
233
Print all values in the dictionary, one by one:
for x in thisdict:
print(thisdict[x])
You can also use the values() method to return values of a
dictionary:
for x in thisdict.values():
print(x)
Conti….
234
You can use the keys() method to return the keys of a
dictionary:
for x in thisdict.keys():
print(x)
You can use the keys() method to return the keys of a
dictionary:
for x in thisdict.keys():
print(x)
Conti…
235
Copy a Dictionary
You cannot copy a dictionary simply by typing dict2 = dict1,
because: dict2 will only be a reference to dict1, and changes
made in dict1 will automatically also be made in dict2.
There are ways to make a copy, one way is to use the built-in
Dictionary method copy().
thisdict = {"brand": "Ford","model": "Mustang","year": 1964}
mydict = thisdict.copy()
print(mydict)
Conti…
236
Make a copy of a dictionary with the dict() function:
thisdict
= {"brand": "Ford","model": "Mustang","year": 1964}
mydict = dict(thisdict)
print(mydict)
Conti…
237
Nested Dictionaries
A dictionary can contain dictionaries, this is called
nested dictionaries.
Create a dictionary that contain three dictionaries:
myfamily = {"child1" :
{"name" : "Emil","year" : 2004},"child2" :
{ "name" : "Tobias", "year" : 2007},"child3" :
{"name" : "Linus","year" : 2011}}
Conti…
238
Another way to create the nested dictionary:
child1 = {"name" : "Emil","year" : 2004}
child2 = {"name" : "Tobias","year" : 2007}
child3 = {"name" : "Linus","year" : 2011}
family = {"child1" : child1, "child2" : child2, "child3":
child3}
Dictionary methods:
clear() Removes all the elements from the dictionary
239
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys
and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key
value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
update() Updates the dictionary with the specified key-
value pairs
values() Returns a list of all the values in the dictionary
240
UNIT 5
Iteration
241
Python Iterators
An iterator is an object that contains a countable
number of values.
An iterator is an object that can be iterated upon,
meaning that you can traverse through all the values.
Technically, in Python, an iterator is an object which
implements the iterator protocol, which consist of the
methods __iter__() and __next__().
Iterator vs Iterable
242
Lists, tuples, dictionaries, and sets are all iterable objects.
They are iterable containers which you can get an iterator
from.
All these objects have a iter() method which is used to get
an iterator:
Example:
mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)
print(next(myit))
print(next(myit))
print(next(myit))
Conti….
243
Strings are also iterable objects, containing a sequence of
characters:
Example:
mystr = "banana"
myit = iter(mystr)
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
Conti….
244
Looping Through an Iterator
We can also use a for loop to iterate through an
iterable object:
Example:
mytuple = ("apple", "banana", "cherry")
for x in mytuple:
print(x)
#Iterate the characters of a string:
mystr = "banana"
for x in mystr:
Recusion in python
245
Python also accepts function recursion, which means
a defined function can call itself.
Recursion is a common mathematical and
programming concept. It means that a function calls
itself. This has the benefit of meaning that you can
loop through data to reach a result.
Conti….
246
Example 1:
def recursion1(n):
if(n>0):
result = n+recursion1(n-1)
print(result)
else:
result = 0
return result
print("\nRecursion Example Results")
recursion1(6)
Conti…
247
Example 2:
def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = int(input(“enter the number”))
print(factorial(num))
Advantages of Recursion
248
Recursive functions make the code look clean and
elegant.
A complex task can be broken down into simpler sub-
problems using recursion.
Sequence generation is easier with recursion than
using some nested iteration.
Disadvantages of Recursion
249
Sometimes the logic behind recursion is hard to
follow through.
Recursive calls are expensive (inefficient) as they
take up a lot of memory and time.
Fibonacci series:
250
n = int(input(“enter number”))
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
for i in range(n)
Print(recur_fibo(i))
Tower of Hanoi
251
def TowerOfHanoi(n , source, destination, auxiliary):
if n==1:
print ("Move disk 1 from source",source,"to destination",destinat
return
TowerOfHanoi(n-1, source, auxiliary, destination)
print ("Move disk",n,"from source",source,"to destination",destinat
TowerOfHanoi(n-1, auxiliary, destination, source)
n=3
TowerOfHanoi(n,'A','B','C')
Linear Search (Simple Search):
252
In linear search, we access each element one by one
sequentially and see whether it is desired element or
not. A search will be unsuccessful if all the elements
are accessed, and the desired element is not found.
Linear search program:
253
a={}
for i in range(0,8):
a[i]=eval(input("Enterno."))
no=eval(input("Enter no. tosearch:"))
for i in range(0,8):
if a[i] == no:
flag = 1
break
if flag == 1:
print("no.isavailableinlist")
else:
Binary search:
254
Binary search is a techniques of searching data in sorted list.
This technique Searches the data in minimum possible
comparisons. The logic behind this technique is given below:
First find the middle elements of the array compare the
mid((first + last)/2) element with an item (either left or right)
If it is less than desired element, then search only the first half of
the array.
If it is greater than the desired element search in the second half
of the array.
Repeat the same steps until search is compete.
Binary search program:
255
def binary_search(arr, x):
low = 0
high = len(arr) - 1
mid = 0
while low <= high:
mid = (high + low) // 2
if arr[mid] < x:
low = mid + 1
elif arr[mid] > x:
high = mid - 1
else:
Conti….
256
arr = [ 2, 3, 4, 10, 40 ]
x = 10
result = binary_search(arr, x)
if result != -1:
print("Element is present at index”, str(result))
else:
print("Element is not present in array")
Selection sort
257
In this algorithm, we select the smallest element from
an unsorted array in each pass and swap with the
beginning of the unsorted array.
This process will continue until all the elements are
placed at right place.
It is simple and an in-place comparison sorting
algorithm.
Hence the time complexity of merge sort algorithm is
O(n2).
Selection sort:
258
length = len(array)
for i in range(length-1):
minIndex = i
for j in range(i+1, length):
if array[j]<array[minIndex]:
minIndex = j
array[i], array[minIndex] = array[minIndex], array[i]
return array
array = [21,6,9,33,3]
print("The sorted array is: ", selection_sort(array))
Join / Merge lists ( two or more)
259
Join / Merge two lists in python using + operator:
Example:
list_1 = ["This" , "is", "a", "sample", "program"]
list_2 = [10, 2, 45, 3, 5, 7, 8, 10]
final_list = list_1 + list_2
print(final_list)
Conti….
260
Join / Merge two lists in python using list.extend():
Example:
list_1 = ["This" , "is", "a", "sample", "program"]
list_2 = [10, 2, 45, 3, 5, 7, 8, 10]
list_1.extend(list_2)
print(list_1)
Conti…..
261
Join / Merge two lists in python using for loop:
Example:
list_1 = ["This" , "is", "a", "sample", "program"]
list_2 = [10, 2, 45, 3, 5, 7, 8, 10]
for elem in list_2:
list_1.append(elem)
print(list_1)
Conti….
262
Join / Merge multiple lists using + operator:
Example:
list_1 = ["This" , "is", "a", "sample", "program"]
list_2 = [10, 2, 45, 3, 5, 7, 8, 10]
list_3 = [11, 12, 13]
merged_list = list_1 + list_2 + list_3
print(merged_list)
Merge sort:
263
Merge sort is one of the most prominent divide-and-
conquer sorting algorithms in the modern era.
It can be used to sort the values in any traversable
data structure such as a list.
Merge sort works by splitting the input list into two
halves, repeating the process on those halves, and
finally merging the two sorted halves together.
Conti….
264
def mergeSort(myList):
if len(myList) > 1:
mid = len(myList) // 2
left = myList[:mid]
right = myList[mid:]
mergeSort(left)
mergeSort(right)
i=0
j=0
k=0
Conti….
265
while i < len(left) and j < len(right):
if left[i] <= right[j]:
myList[k] = left[i]
i += 1
else:
myList[k] = right[j]
j += 1
k += 1
Conti….
266
while i < len(left):
myList[k] = left[i]
i += 1
k += 1
while j < len(right):
myList[k]=right[j]
j += 1
k += 1
myList = [54,26,93,17,77,31,44,55,20]
mergeSort(myList)
print(myList)
267
UNIT 4
Program to print all prime numbers in a given
range:
268
lower = 900
upper = 1000
for num in range(lower, upper + 1):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)
Sieve of Eratothenes:
269
The sieve of Eratosthenes is one of the most efficient ways to
find all primes smaller than n when n is smaller than 10
million or so.
Given a number n, print all primes smaller than or equal to n.
It is also given that n is a small number.
Example:
input : n =10
Output : 2 3 5 7
Input : n = 20
Output: 2 3 5 7 11 13 17 19
Conti….
270
Let us take an example when n = 50. So we need to
print all prime numbers smaller than or equal to 50.
Step 1: We create a list of all numbers from 2 to 50.
Conti…
271
Step 2: According to the algorithm we will mark all
the numbers which are divisible by 2 and are greater
than or equal to the square of it.
Conti…
272
Step 3: Now we move to our next unmarked number
3 and mark all the numbers which are multiples of 3
and are greater than or equal to the square of it.
Conti…
273
Step 4: We move to our next unmarked number 5 and
mark all multiples of 5 and are greater than or equal
to the square of it.
Conti…
274
Step 5: We move to our next unmarked number 7 and
mark all multiples of 7 and are greater than or equal
to the square of it.
Our final table look like this
Python File I/O
275
Python too supports file handling and allows users to
handle files i.e., to read and write files, along with
many other file handling options, to operate on files.
File handling is an important part of any web
application.
Python has several functions for creating, reading,
updating, and deleting files.
File handling:
276
The key function for working with files in Python is
the open() function.
The open() function takes two parameters; filename,
and mode.
There are four different methods (modes) for opening a
file:
Syntax:
f = open(”hello.txt") OR f = open(”hello.txt", "rt")
Because "r" for read, and "t" for text are the default values,
you do not need to specify them.
Conti….
277
Assume we have the following file, located in the
same folder as Python:
To open the file, use the built-in open() function.
The open() function returns a file object, which has
a read() method for reading the content of the file:
f = open(”hello.txt", "r")
print(f.read())
f = open("D:\\myfiles\welcome.txt", "r")
print(f.read())
print(f.read(5))
Conti….
278
Read Lines: You can return one line by using
the readline() method:
Example:
f = open(”hello.txt", "r")
print(f.readline())
By calling readline() two times, you can read the two
first lines:
f = open(”hello.txt", "r")
print(f.readline())
print(f.readline())
Conti…
279
By looping through the lines of the file, you can read
the whole file, line by line:
f = open("demofile.txt", "r")
for x in f:
print(x)
Conti…
280
Close Files:
It is a good practice to always close the file when you
are done with it.
f = open(”hello.txt", "r")
print(f.readline())
f.close()
Conti…
281
Write to an Existing File:
To write to an existing file, you must add a parameter to
the open() function:
"a" - Append - will append to the end of the file
"w" - Write - will overwrite any existing content
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
f = open("demofile2.txt", "r")
print(f.read())