Python 1699345202
Python 1699345202
Python
Volume 1 of Learning Professional Python is a resource for students who
want to learn Python even if they don’t have any programming knowledge
and for teachers who want a comprehensive introduction to Python to use
with their students. This book helps the students achieve their dream job
in the IT Industry and teaches the students in an easy, understandable
manner while strengthening coding skills.
Usharani Bhimavarapu
and Jude D. Hemanth
Cover Image Credit: Shutterstock.com
First edition published 2024
by CRC Press
2385 NW Executive Center Drive, Suite 320, Boca Raton, FL 33431
and by CRC Press
4 Park Square, Milton Park, Abingdon, Oxon, OX14 4RN
CRC Press is an imprint of Taylor & Francis Group, LLC
© 2024 Usharani Bhimavarapu and Jude D. Hemanth
Reasonable efforts have been made to publish reliable data and
information, but the author and publisher cannot assume responsibility
for the validity of all materials or the consequences of their use. The
authors and publishers have attempted to trace the copyright holders of
all material reproduced in this publication and apologize to copyright
holders if permission to publish in this form has not been obtained. If
any copyright material has not been acknowledged please write and let us
know so we may rectify in any future reprint.
Except as permitted under U.S. Copyright Law, no part of this book may be
reprinted, reproduced, transmitted, or utilized in any form by any electronic,
mechanical, or other means, now known or hereafter invented, including
photocopying, microfilming, and recording, or in any information storage
or retrieval system, without written permission from the publishers.
For permission to photocopy or use material electronically from this
work, access www.copyright.com or contact the Copyright Clearance
Center, Inc. (CCC), 222 Rosewood Drive, Danvers, MA 01923,
978–750–8400. For works that are not available on CCC please contact
[email protected]
Trademark notice: Product or corporate names may be trademarks or
registered trademarks and are used only for identification and explanation
without intent to infringe.
Library of Congress Cataloging‑in‑Publication Data
Names: Bhimavarapu, Usharani, author. | Hemanth, D. Jude, author.
Title: Learning professional Python / Usharani Bhimavarapu, D. Jude Hemanth.
Description: First edition. | Boca Raton : CRC Press, 2024. | Includes
bibliographical references and index.
Identifiers: LCCN 2023007977 | ISBN 9781032539256 (volume 1 ; hbk) |
ISBN 9781032534237 (volume 1 ; pbk) | ISBN 9781003414322
(volume 1 ; ebk) | ISBN 9781032611761 (volume 2 ; hbk) | ISBN
9781032611709 (volume 2 ; pbk) | ISBN 9781003462392 (volume 2 ; ebk)
Subjects: LCSH: Python (Computer program language) | Computer
programming.
Classification: LCC QA76.73.P98 B485 2024 | DDC 005.13/3—dc23/eng/
20230508
LC record available at https://lccn.loc.gov/2023007977
ISBN: 978-1-032-53925-6 (hbk)
ISBN: 978-1-032-53423-7 (pbk)
ISBN: 978-1-003-41432-2 (ebk)
DOI: 10.1201/9781003414322
Typeset in Minion
by Apex CoVantage, LLC
Contents
Preface, xi
Author Biographies, xiii
v
vi ◾ Contents
Chapter 4 ◾ Strings75
4.1 STRING CREATION 75
4.2 ACCESSING VALUES TO A STRING 76
4.3 MODIFY EXISTING STRING 78
4.4 ESCAPE CHARACTERS 79
4.5 STRING SPECIAL CHARACTERS 80
4.6 STRING FORMATTING OPERATOR 81
4.7 TRIPLE QUOTES 84
4.8 UNICODE STRINGS 84
4.9 BUILT-IN STRING METHODS 84
4.10 DELETING STRING 87
EXERCISE 88
Chapter 5 ◾ Lists91
5.1 INTRODUCTION 91
5.2 CHARACTERISTICS OF LISTS 92
5.3 DECISION-MAKING IN LISTS 93
5.3.1 Range 94
5.4 ACCESSING VALUES IN THE LIST 95
5.5 UPDATING LIST 99
5.6 DELETE LIST ELEMENTS 100
5.7 SORTING 100
5.8 COPYING 101
5.9 OPERATORS ON LISTS 102
5.10 INDEXING, SLICING 104
viii ◾ Contents
Chapter 6 ◾ Tuple127
6.1 TUPLE CREATION 127
6.2 ACCESSING VALUES IN TUPLES 129
6.3 UPDATING TUPLES 132
6.4 DELETE TUPLE ELEMENTS 133
6.5 OPERATIONS ON TUPLES 134
6.6 UNPACKING OF TUPLES 138
6.7 INDEXING, SLICING ON TUPLES 140
EXERCISE 142
Chapter 7 ◾ Sets143
7.1 INTRODUCTION 143
7.2 ACCESS SET ELEMENTS 145
7.3 ADDING ELEMENTS TO THE SET 145
7.4 REMOVE AN ELEMENT FROM THE SET 146
7.5 DELETE THE SET 146
7.6 PYTHON SET OPERATIONS 147
7.7 SET MEMBERSHIP OPERATORS 148
7.8 SET PREDEFINED METHODS 149
7.9 FROZEN SET 152
7.10 FROZEN SET OPERATIONS 153
7.11 FROZEN SET PREDEFINED OPERATIONS 153
EXERCISE 156
Chapter 8 ◾ Dictionary157
8.1 ACCESSING THE ELEMENTS OF THE DICTIONARY 163
8.2 COPYING THE DICTIONARY 165
Contents ◾ ix
Chapter 10 ◾ Functions189
10.1 DEFINING A FUNCTION 189
10.2 PASS BY REFERENCE 192
10.3 FUNCTION ARGUMENTS 193
10.3.1 Required Arguments 194
10.3.2 Keyword Arguments 194
10.3.3 Default Arguments 197
10.3.4 Variable Length Arguments 198
10.4 ANONYMOUS FUNCTIONS 199
10.5 RETURN STATEMENT 200
10.6 FUNCTION VARIABLE SCOPE 202
10.7 PASSING LIST TO FUNCTION 206
10.8 RETURNING LIST FROM THE FUNCTION 208
10.9 RECURSION 209
EXERCISE 211
INDEX, 255
Preface
xi
xii ◾ Preface
xiii
xiv ◾ Author Biographies
Python Basics
DOI: 10.1201/9781003414322-1 1
2 ◾ Learning Professional Python
Syntax
print (object, sep=separator, end=end, file= file,
flush=flush)
The end and sep are the keyword arguments, and these parameters are
used to format the output of the print () function. The programmers can
enter more than one object separated by separator. An empty print () out-
puts an empty line to the screen.
Your first python program:
this is to test
Python Basics ◾ 5
print(this is to test)
Output
File “<ipython-input-86-c0dae74495e9>”, line 1
print(this is to test)
^
SyntaxError: invalid syntax
print () can operate with all types of data provided by Python. The data
type data strings, numbers, characters, objects, logical values can be suc-
cessfully passed to print ().
Program
print(“this is to test”)
print(“this is the second line in python program”)
Output
this is to test
this is the second line in python program
The preceding program invokes the print () twice. The print () begins
its output from a fresh new line each time it starts its execution. The
output of the code is produced in the same order in which they have
been placed in the source file. The first line in the preceding program
produces the output [this is to test], and the second line produces the
output [this is the second line in python program]. The empty print ()
with without any arguments produces the empty line, that is, just a new
empty line.
Program
print(“this is to test”)
print()
print(“this is the second line in python program”)
6 ◾ Learning Professional Python
Output
this is to test
this is the second line in python program
Program
print(“this”,“is”,“to”,“test”,end=“@”)
Output
this is to test@
Program
print(“this is”,“ to test”,sep=“---”,end=“#”)
print(“this is an experiment”)
Output
this is--- to test#this is an experiment
The string assigned to the end keyword argument can be any length.
The sep arguments value may be an empty string. In the previous exam-
ple, the separator is specified as –. The first and the second argument is
separated by the separator. In the preceding program the separator is –.
So the output is [this is – to test]. In the first the print statement, the end
argument specified is “#”. So after printing the first print statement, the #
symbol is placed, the first line output is [this is – to test#].
Program
print(“this”,“is”,“to”,“test”,end=“\n\n\n”)
print(“this is an experiment”)
Python Basics ◾ 7
Output
this is to test
this is an experiment
def test():
a=1
print(a)
a=test_one+\
test_two+\
test_three
Statements continued with [], {}, () do not need to use the line continu-
ation character, for example:
a= {1,2,3,4,
5,6,7}
8 ◾ Learning Professional Python
S=”test”
S=’test’
S=””” This is to test a multiple lines and sentence “””
‘‘‘this is the
test the
multiline comment ’’’’,
Program
print(“test#1”)
print(“test#2”)
#print(“test#3)
Python Basics ◾ 9
Output
test#1
test#2
In the preceding program, the first and the second print statement con-
sists of the # statement in between the quotes, so this # symbol behaves like
a symbol, and the interpreter prints that symbol. But at line 3 the # symbol
is in front of print statement. In this case # symbol works as comment.
Program
#this is
to test comment
print(“python comment”)
Output
File “<ipython-input-28-b77848f8c85d>”, line 2
to test comment
^
SyntaxError: invalid syntax
x=‘test’;print(x)
Output
test
10 ◾ Learning Professional Python
Syntax
variable name=value
E.g.: i=100
t=100
sname=‘rani’
In the previous example, t and the sname are the variable names and
100 and ‘rani’ are the variable values.
Note: The programmer can assign a new value to the already existing
variable by using either the assignment operator or the shortcut operator.
Program
Test=1
print(test)
Output
--------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-23-f210fd97eab0> in <module>()
1 Test=1
----> 2 print(test)
NameError: name ‘test’ is not defined
Name error has occurred because the variable name is Test but in print
the variable name is test.
Program
i=100
i=50 + 500
print(i)
12 ◾ Learning Professional Python
Output
550
Program
a=’5’
b=“5”
print(a+b)
Output
55
In the preceding program, the value of a is character literal 5 but not the
numeric value. The value of b is string literal 5. The third line performs the
computation a+b. Here + works as the concatenation operator.
Output
c= 5.830951894845301
a=b=c=1
Python Basics ◾ 13
a, b, c=1,2,3
1. To assign to a variable
E.g., test=None
2. To compare with another variable
if(test==None):
if test is None:
1. Global
2. Local
• int
• long
• float
• complex
14 ◾ Learning Professional Python
1. Implicit conversion
2. Explicit conversion
Output
135.34
133.0
(20 + 1j)
Output
--------------------------------------------------------------
TypeErrorTraceback
(most recent call last)
Python Basics ◾ 15
<ipython-input-65-d2c36b20b8bd> in <module>()
1 x=“test”
2 y=10
----> 3 print(x+y)
TypeError: can only concatenate str (not “int”) to str
Program
x=“1010”
print(“string=”,x)
print(“conversion to int=”,int(x,2))
print(“conversion to float=”,float(x))
print(“conversion to complex=”,complex(x))
x=10
print(“converting to hexadecimal=”,hex(x))
print(“converting to octal=”,oct(x))
print(“conversion to Ascii=”,chr(x))
x=‘test’
print(“conversion to tuple=”,tuple(x))
print(“conversion to set=”,set(x))
16 ◾ Learning Professional Python
Output
string= 1010
conversion to int= 10
conversion to float= 1010.0
conversion to complex= (1010 + 0j)
converting to hexadecimal= 0xa
converting to octal= 0o12
conversion to Ascii=
conversion to tuple= (‘t’, ‘e’, ‘s’, ‘t’)
conversion to set= {‘s’, ‘t’, ‘e’}
1.21 LITERALS
Literals are nothing but some fixed values in code. Python has various
types of literals – number (e.g., 111 or – 1), float literal (e.g., 2.5 or – 2.5),
string literal (e.g., ‘test’ or “test”), Boolean literal (True/False), None literal.
Note: Python omits zero when it is the only digit in front or after
the decimal point.
In Python the number 1 is an integer literal and 1.0 is the float literal.
The programmer has to input the value 1.0 as 1. and 0.1 as .1. To avoid
writing many zeros in, Python uses the scientific notation E or e. For
Python Basics ◾ 17
example, 10000000 can be represented as 1E7 or 1e7. The value before the e
is the base, and the value after the e is the exponent. For example, the float
literal 0.000000001 can be represented as 1e-9 or 1E-9.
Program
print(0o13)#octal representation
print(0x13)#hexadecimal representation
Output
11
19
EXERCISE
1. Write the first line of code in the python program using the sep= “$”
and
end= “ . . . ” keywords.
print (“this”, “is”, “to”, ‘test”)
print (“python language”)
2. Write the first line of code in the python program using the sep=
“***” and end= “----” keywords.
print (“this”, “is”, “to”, “test”)
print (“python language”)
3. Write the first line of code in the python program using the sep= “*”
and end= “\n” keywords and second line of code using the sep= “#”
and end= “---”.
print (“this”, “is”, “to”, “test”)
print (“python language”)
18 ◾ Learning Professional Python
Python Operators
1. Unary Operator
2. Binary Operator
3. Ternary Operator
+, -,
DOI: 10.1201/9781003414322-2 19
20 ◾ Learning Professional Python
a,b = 10, 20
print(a if a> b else b)
Output
20
1. Arithmetic Operators
2. Relational Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
Program
Note: When using **, if both operands are integers, then the result
is an integer.
Note: When using **, if one of the operands is float, then the result
is a float.
Note: When using //, if both operands are integers, then the result
is an integer.
Note: When using //, if one of the operands is float, then the result
is a float.
Program
Program
Program
Program
Output
testing
print(“test”*3)
print(3*“sample”)
print (3*”1”)#outputs 111 but not 3
Output
testtesttest
samplesamplesample
111
Syntax:
eval(expression[,globals[,locals]])
E.g.: eval(“123 + 123”)
246
E.g.: eval(“sum[10,10,10])”,{})
30
E.g.: x=100,y=100
eval(“x+y”)
200
In the given example both x and y are global
variables.
E.g.: eval(“x+50”,{},{“x”:50})
100
Note: The default return type of the input () function is the string.
E.g.: i=input ()
Program
print(“enter 2 integers”)
a=int(input())
b=int(input())
print(a+b)
Output
enter 2 integers
10
30
40
Program
a=int(input(“enter integer:”))
b=int(input(“enter integer:”))
c=a+b
print(“sum=”,c)
Output
enter integer:1
enter integer:3
sum= 4
30 ◾ Learning Professional Python
Program
a=input()
print(a+3)
Output
5
--------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-22-3ae605921ae5> in <module>()
1 a=input()
----> 2 print(a+3)
TypeError: can only concatenate str (not “int”) to str
In the preceding program it’s a type error because the input returns
string data type. Python does not concatenate the string and the integer.
So the previous program throws the type error.
Program
a=input()
print(type(a))
Output
4
<class ‘str’>
In the preceding program, the entered value is 10. Though the value 10
is an integer, the default return type value of the input () function is the
string, so the output of the print function is the str (string).
Program
a=float(input(“enter float value”))
b=float(input(“enter float value”))
c=a+b
print(“sum of floats=”,c)
Python Operators ◾ 31
Output
enter float value1.5
enter float value3.8
sum of floats= 5.3
Program
n=int(input(“enter integer”))
print(n*“1”)
Output
enter integer4
1111
Program
#Ascii value
x=input(“enter character:”)
print(“Ascii of ”,x,“is”,ord(x))
Output
enter character:a
Ascii of a is 97
Program
print(“%5.3e”% (123.456789))
print(“%10.3e”% (123.456789))
print(“%15.3e”% (123.456789))
print(“%-15.3e”% (123.456789))
print(“%5.3E”% (123.456789))
32 ◾ Learning Professional Python
print(“%o”% (15))
print(“%5.3o”% (15))
print(“%x”% (15))
print(“%X”% (15))
print(“%10x”% (15))
print(“%10.3x”% (15))
print(“%x%%”% (15))
print(“%d”% (123456789))
print(“%d,”% (123456789))
print(“{0:4,d}”.format(123456789))
print(“{0:06d}”.format(123))
print(“{0:4,.5f}”.format(123456789.123456789))
Output:
1.235e+02
1.235e+02
1.235e+02
1.235e+02
1.235E+02
17
017
f
F
f
00f
f%
123456789
123456789,
123,456,789
000123
123,456,789.12346
Program
print(“this book costs {0:f} only”.format(150.99))
print(“this book costs {0:8f} only”.format(150.99))
print(“this book costs {0:.2f} only”.format(150.99))
print(“this book costs {0:.3f} only”.format(150.99))
print(“this book costs {0:.0f} only”.format(150.99))
print(“this book costs {0:e} only”.format(150.99))
Python Operators ◾ 33
Output
this book costs 150.990000 only
this book costs 150.990000 only
this book costs 150.99 only
this book costs 150.990 only
this book costs 151 only
this book costs 1.509900e+02 only
this book costs 150.99 only
this book costs 150 only
this book costs 150 only
this book costs 226 only
this book costs 10010110 only
– 15
– 15
15
2.7 LIBRARIES
2.7.1 Math and CMath Libraries
Math is the basic math module that deals with mathematical operations
like sum, mean, exponential, etc., and this library is not useful with com-
plex mathematical operations like matrix multiplication. The disadvan-
tage is the mathematical operations performed with the math library are
very slow. For instance, if we consider the example shown here, we per-
formed the basic mathematical operations. The statement math.exp is used
to find the exponent of the number. For example, math.exp (5) means e to
the power of 5, that is, e5. The value of e is approximately 2.17. The state-
ment math.pi returns the value approximately 3.14. The constant math.e
returns the value 2.17. The ceil returns the ceiling value not greater than
34 ◾ Learning Professional Python
that number. The floor returns the floor value of the given number. The
math.trunc method returns the truncated part of the number.
Program
import math
x,y,z=10,20,30
print(“min=”,min(x,y,z))
print(“max=”,max(x,y,z))
print(“sqrt of ”,x,“=”,math.sqrt(x))
print(“round=”,round(0.5))
print(“power=”,pow(2,3))
f=1.5
print(“ceil=”,math.ceil(f))
print(“floor=”,math.floor(f))
x=2
print(“exponent=”,math.exp(x))
print(“log=”,math.log(x))
print(“log10=”,math.log10(x))
x=-1
print(“absolute=”,abs(x))
print(“absolute=”,math.fabs(x))
Output
min= 10
max= 30
Python Operators ◾ 35
sqrt of 10 = 3.1622776601683795
round= 0
power= 8
ceil= 2
floor= 1
exponent= 7.38905609893065
log= 0.6931471805599453
log10= 0.3010299956639812
absolute= 1
absolute= 1.0
The preceding example uses some math operations and produces the
output based on the mathematical operation used.
import math
print(“exp(5)”,math.exp(5))
print(“Pi”,math.pi)
print(“Exponent”,math.e)
print(“factorial(5)”,math.factorial(5))
print(“ceil(-5)”,math.ceil(-5))
print(“ceil(5)”,math.ceil(5))
print(“ceil(5.8)”,math.ceil(5.8))
print(“floor(-5)”,math.floor(-5))
print(“floor(5)”,math.floor(5))
print(“floor(5.8)”,math.floor(5.8))
print(“trunc(-5.43)”,math.trunc(-5.43))
print(“pow(3,4)”,math.pow(3,4))
print(“pow(3,4.5)”,math. pow(3,4.5))
print(“pow(math.pi,4)”,math. pow(math.pi,4))
print(“log(4)”,math.log(4))
print(“log(3,4)”,math.log(3,4))
print(“log(math.pi,4)”,math.log(math.pi,4))
print(“sqrt(8)”,math.sqrt(8))
import cmath
print(“cmath.pi”,cmath.pi)
36 ◾ Learning Professional Python
print(“cmath.e”,cmath.e)
print(“sqrt(4+j5)”,cmath.sqrt(4 + 5j))
print(“cos(4 + 5j)”,cmath.cos(4 + 5j))
print(“sin(4 + 5j)”,cmath.sin(4 + 5j))
print(“tan(4 + 5j)”,cmath.tan(4 + 5j))
print(“asin(4 + 5j)”,cmath.asin(4 + 5j))
print(“acos(4 + 5j)”,cmath.acos(4 + 5j))
print(“atan(4 + 5j)”,cmath.atan(4 + 5j))
print(“sinh(4 + 5j)”,cmath.sinh(4 + 5j))
print(“cosh(4 + 5j)”,cmath.cosh(4 + 5j))
print(“tanh(4 + 5j)”,cmath.tanh(4 + 5j))
print(“rect(3,4)”,cmath.rect(3,4))
print(“log(1 + 2j)”,cmath.log(1 + 2j))
print(“exp(1 + 2j)”,cmath.exp(1 + 2j))
Solved Examples
Program
a = 5
a = 1, 2, 3
print(a)
Output
(1, 2, 3)
Python Operators ◾ 37
Program
i=10
print(i!=i>5)
Output
False
Program
x=int(input(“enter number:”))
y=int(input(“enter number:”))
global x,y
test={“add”:x+y,“sub”:x-y,“mul”:x*y,“div”:x/y}
op=input(“enter operation:”)
print(test.get(op,“wrong option”))
Output
enter number:1
enter number:3
enter operation:add
4
EXERCISE
1. Check the result for this Python program:
print (3**2)
print (3. **2)
print (3**2.)
print (3. **2.)
2. Check the result for this Python program:
print (3*2)
print (3. *2)
print (3*2.)
print (3. *2.)
38 ◾ Learning Professional Python
Decision-Making
and Conditionals
3.1 INTRODUCTION
Conditional statements can check the conditions and accordingly change
the behavior of the program.
Python programming language supports different decision-making
statements:
• If statement
• If-else statement
• Nested if statement
• elif statement
3.2 IF STATEMENT
The condition after the if statement is the Boolean expression. If the
condition becomes true, then the specified block of statement runs,
otherwise nothing happens.
DOI: 10.1201/9781003414322-3 41
42 ◾ Learning Professional Python
Syntax
if condition:
#Execute the indented block if true
Statement-1
Statement-2
Statement-3
Statement-4
1. The if keyword.
2. One or more white spaces.
3. An expression whose value is intercepted as true or false. If the
expression is interpreted as true, then the indented block will be
executed. If the expression that is evaluated is false, the indented
block will be omitted, and the next instruction after the indented
block level will be executed.
4. A colon followed by a newline.
5. An indented set of statements.
Program
a,b=10,5
if(a<b):
print(“ a is smaller than b”)
if(b<a):
print(“ b is smaller than a”)
Output
b is smaller than a
Syntax
if condition:
#Execute the indented block if true
Statement-1
Statement-2
else:
#Execute the indented block if condition meets false
Statement-3
Statement-4
Program
# python program to find the maximum of two numbers
def maximum(a, b):
if a >= b:
return a
else:
return b
# main code
a = 2
b = 4
print(maximum(a, b))
Output
4
Program
#Find maximum of two numbers using ternary operator
num1 = int(input(“Enter the num1: ”))
44 ◾ Learning Professional Python
The preceding program finds max of two numbers by using the ternary
operator.
Syntax-1
if condition1:
#Execute the indented block if true
if condition2:
Statement-1
Statement-2
else:
#Execute the indented block if condition mets false
if condition3:
Statement-3
Statement-4
Syntax-2
if condition1:
#Execute the indented block if true
if condition2:
Statement-1
Statement-2
else:
Statement-3
Statement-4
else:
#Execute the indented block if condition mets false
if condition3:
Statement-4
Statement-5
Decision-Making and Conditionals ◾ 45
Synatx-3
if condition1:
#Execute the indented block if true
if condition2:
Statement-1
Statement-2
else:
Statement-3
Statement-4
else:
#Execute the indented block if condition mets false
if condition3:
Statement-5
Statement-6
else:
Statement-7
Statement-8
Syntax-4
if condition1:
#Execute the indented block if true
if condition2:
Statement-1
Statement-2
if condition3:
Statement-3
Statement-4
Syntax-5
if condition1:
#Execute the indented block if condition 1 is true
if condition2:
Statement-1
Statement-2
if condition3:
Statement-3
Statement-4
else:
#Execute the indented block if condition 3 is false
Statement-5
Statement-6
46 ◾ Learning Professional Python
Syntax-6
if condition1:
#Execute the indented block if true
if condition2:
Statement-1
Statement-2
if condition3:
Statement-3
Statement-4
else:
#Execute the indented block if condition 1 is false
Statement-5
Statement-6
Program
year = 2000
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print(“{0} is a leap year”.
format(year))
else:
print(“{0} is not a leap year”.
format(year))
else:
print(“{0} is a leap year”.format(year))
else:
print(“{0} is not a leap year”.format(year))
Output
2000 is a leap year
Syntax
If condition 1:
Statements-1
elif condition 2:
Decision-Making and Conditionals ◾ 47
In the elif statement, else is always the last branch, and the else block is an
optional block.
Program
#Calculating Grade
m1=int(input(“enter ml:”))
m2=int(input(“enter m2:”))
m3=int(input(“enter m3:”))
p=(int)(ml+m2+m3/3)
if(p>90):
print(“Grade-A”)
elif (p>80 and p<=90):
print(“Grade-B”)
elif (p>60 and p<=80):
print(“Grade-c”)
elif (p>60 and p<=45):
print(“Pass”)
else:
print(“Fail”)
Output
enter m1:78
enter m2:89
enter m3:94
Grade-A
The preceding program calculates grade using elif.
48 ◾ Learning Professional Python
3.6 WHILE
While loop repeats the execution if the condition evaluates to true. If the
condition is false for the first time, the while loop body is not executed
even once. The loop body should be able to change the condition value
because if the condition is true at the beginning, the loop body may run
continuously to infinity.
Syntax
while condition:
# Indent block is executed if the condition evaluates
to true
statement 1
statement 2
statement 3
statement 4
Program
# Python3 program to find Smallest of
#three integers withoutcomparison operators
def smallest(x, y, z):
c = 0
while (x and y and z) :
x = x-1
y = y-1
z = z—1
c = c + 1
return c
# Driver Code
x = 12
y = 15
z = 5
print(“Minimum of 3 numbers is”,
smallest(x, y, z))
Output
Mininum of 3 numbers is 5
The preceding program finds min of three numbers using while loop.
Decision-Making and Conditionals ◾ 49
Program
#program to Display the Multiplication Table
num = int(input(“ Enter the number : ”))
i = 1
# using for loop to iterate multiplication 10 times
print(“Multiplication Table of : ”)
while i<=10:
num = num * 1
print(num,‘×’,i,‘=’,num*i)
i += 1
Output
Enter the number : 5
Multiplication Table of :
5 × 1 = 5
5 × 2 = 10
5 × 3 = 15
5 × 4 = 20
5 × 5 = 25
5 × 6 = 30
5 × 7 = 35
5 × 8 = 40
5 × 9 = 45
5 × 10 = 50
Syntax
for value in sequence-range:
loop body
• For keyword.
50 ◾ Learning Professional Python
• The variable after the for keyword is the control variable of the loop,
automatically counts the loop turns.
• The in keyword.
• The range () function. The range () function accepts only the integers
as its arguments, and it generates the sequence of integers.
Body of the for loop. Sometimes the pass keyword inside the loop body is
nothing but the empty loop body. The body of the loop may consist of the
if statement, if-else statement, elif statement, while loop.
Note: The range () function may accept the three arguments: start,
end, increment. The default value of the increment is 1.
Program
#range with one argument
for seq in range(10):
print(seq)
0
1
2
3
4
5
6
7
8
9
The preceding program uses for . . . range with one argument to print a
sequence of numbers from 0 to 9.
Program
#range with two argument
for seq in range(5,10):
print(seq)
Decision-Making and Conditionals ◾ 51
Output
5
6
7
8
9
The preceding program uses for . . . range with two arguments to print
a sequence of numbers from 5 to 10 with step value 1.
Program
#range with three argument and argument is ascending
for seq in range(50,1000,100):
Print(seq)
Output
50
150
250
350
450
550
650
750
850
950
The preceding program uses for . . . range with three arguments, and
argument is ascending to print a sequence of numbers from 50 to 1000
with step value of 100.
Program
#range with three argument and argument is descending
for seq in range(100,10,-10):
print(seq)
100
90
80
70
52 ◾ Learning Professional Python
60
50
40
30
20
The preceding program uses for . . . range with three arguments, and
argument is descending to print a sequence of numbers from 100 to 10
with step value of – 10.
Program:
#Negative range()
for i in range(-1, -11, -1):
print(i, end=‘, ’)
Output:
-1, -2, -3, -4, -5, -6, -7, -8, -9, -10
The previous program uses the negative values for start, end, and the
step values.
Syntax
# outer for loop
for element in sequence
# inner for loop
for element in sequence:
body of inner for loop
body of outer for loop
Decision-Making and Conditionals ◾ 53
Output:
1 2 3 4 5 6 7 8 9
2 4 6 8 10 12 14 16 18
3 6 9 12 15 18 21 24 27
4 8 12 16 20 24 28 32 36
Program
n=int(input(“enter number:”))
for i in range(1,n+1):
for j in range(1,i+1):
print(i,end=“ ”)
print()
Output
enter number:5
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
Program
n=int(input(“enter number:”))
for i in range(1,n+1):
for j in range(1,i+1):
print(j,end=“ ”)
print()
Output
enter number:5
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Syntax
while expression:
while expression:
statement(s)
statement(s)
Program
#Strong number
n=int(input(“enter number”))
t=n
sum=0
while(n!,=0):
i,f=1,1
r=n%10
while{i<=r):
f*=i
i+=l
sum+=f
n//=10
if(t==sum):
print(t,“is strong number”)
else:
print(t,“is not strong number”)
Output
enter number9
9 is not strong number
Program
# multiplication table using nested while
n=2
while 1:
i=1;
Decision-Making and Conditionals ◾ 55
while i<=10:
print(“%d × %d = %d\n”%(n,i,n*i));
i = i+l;
choice = int(input(“Do you want to continue printing
the table, press 0 for no?”))
if choice == 0:
break;
n=n+1
Output
2 × 1 = 2
2 × 2 = 4
2 × 3 = 6
2 × 4 = 8
2 × 5 = 10
2 × 6 = 12
2 × 7 = 14
2 × 8 = 16
2 × 9 = 18
2 × 10 = 20
Do you want to continue printing the table, press 0
for no?0
The preceding program prints the multiplication table using the nested while.
Syntax
for statement
# For loop code
else:
# Else block code
Program
for i in range(1, 5):
print(i)
else: # Executed because no break in for
print(“No Break”)
56 ◾ Learning Professional Python
Output
1
2
3
4
No Break
Syntax
for val in sequence:
pass
Program
for i in “this is to test”:
if i==“e” or i==“o”:
pass
else:
print(i,end=“ ”)
Output
this is t tst
Syntax
break
Decision-Making and Conditionals ◾ 57
Program
# Use of break statement inside the loop
for val in “string”:
if val == “i”:
break
print(val)
Output
s
t
r
The preceding program uses the break statement in the for loop. The for
loop iterates through the string literal “string” and when the character “i”
is encountered the for loop breaks.
Program
n = 1
while n < 5:
n += 1
if n == 3:
break
print(n)
Output
Program
for i in range(3):
for j in range(2):
if j == i:
break
print(i, j)
58 ◾ Learning Professional Python
Output
1 0
2 0
2 1
Program
#break inner loop while
while True:
print (“In outer loop”)
i = 0
while True:
print (“In inner loop”)
if i >= 5: break
i += 1
print(“Got out of inner loop, still inside outer
loop”)
break
Output
In outer loop
In inner loop
In inner loop
In inner loop
In inner loop
In inner loop
In inner loop
Got out of inner loop, still inside outer loop
The preceding program uses the break statement in nested inner while
loop.
3.13 CONTINUE
Continue – skips the remaining body of the loop.
Syntax
continue
Decision-Making and Conditionals ◾ 59
Program
# Program to show the use of continue statement inside
loops
for val in “string”:
if val == “i”:
continue
print(val)
Output
s
t
r
n
g
Program
i = 1
while i <= 5:
i = i+1
if(i==3):
continue
print(i)
Output
2
4
5
6
Program
first = [1,2,3]
second = [4,5]
for i in first:
for j in second:
if i == j:
60 ◾ Learning Professional Python
continue
print(i, ‘*’, j, ‘=’, i * j)
Output
1 * 4 = 4
1 * 5 = 5
2 * 4 = 8
2 * 5 = 10
3 * 4 = 12
3 * 5 = 15
Program
i=1
while i<=2 :
print(i,“outer ”)
j=1
while j<=2:
print(j,“Inner ”)
j+=1
if(j==2):
continue
i+=1;
Output
1 Outer
1 Inner
2 Inner
2 Outer
1 Inner
2 Inner
Syntax
while condition:
statements
else:
statements
If the condition becomes false at the very first iteration, then the while
loop body never executes.
Note: The else block executes after the loop finishes its execution if
it has not been terminated by the break statement.
Solved examples
Program
for i in “test”:
if i == “s”:
break
print(i)
Output
t
e
Output
t
e
t
62 ◾ Learning Professional Python
Program
#Amstrong number
n=int(input(“enter number”))
sum=0
t=n
C=0
while t>0:
c = c+1
t=t//10
t=n
while t>0:
r=t%l0
sum+=(r**c)
t//=10
if n==sum:
print(n,“is amstrong number”)
else:
print(n,“is not amstrong number”)
Output
enter number5
5 is amstrong number
Program
#Factorial of a number
n=int(input(“enter number”))
f=1
for i in range(1,n+1):
f*=i
print(“factorial is”,f)
Output
enter number5
factorial is 120
Program
#Reverse the number
n=int(input(“enter number”))
rev=0
while(n>0):
r=n%10
rev=rev*10+r
n=n//10
print(“reverse number”,rev)
Output
enter number123
reverse number 321
The preceding program prints the given number in the reverse order.
Program
#Palindrome Number
n=int(input(“enter number”))
rev=0
t=n
while(n>0):
r=n%l0
rev=rev*l0+r
n=n//10
if(t==rev):
print(t,“ is plindrome”)
else:
print(t,“ is not plindrome”)
Output
enter number121
121 is plindrome
Program
#Printing first max and the second max number
64 ◾ Learning Professional Python
n=int(input(“enter range”))
fbig,sbig=0,0
for i in range(0,n,1):
num=int(input(“enter number”))
if(num>fbig:
sbig=fbig
fbig=num
if(num>sbig and num<fbig):
sbig=num
print(“first max:”,fbig)
print(“second max:”,sbig)
Output
enter range5
enter number4
enter number9
enter nubmer23
enter number45
enter number89
first max: 89
second max: 45
The preceding program prints first max and the second max number
without using array.
Program
#perfect number
n=int(input(“enter number”))
sum=0
for i in range(1,n):
if(n%i==0):
sum+=i
if(n==sum):
print(n,“is perfect number”)
else:
print(n,“is not perfect number”)
Output
enter number5
5 is not perfect number
Decision-Making and Conditionals ◾ 65
Program
n=int(input(“enter number:”))
for i in range(n,0,-1):
for j in range(1,i+1):
print(j,end=“ ”)
print()
Output
enter number:5
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
Program
n=int(input(“enter number:”))
for i in range(n,0,-1):
for j in range(i,0,-1):
print(j,end=“ ”)
print()
Output
enter number:5
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1
Program
# Python program to find the
66 ◾ Learning Professional Python
Output
2
Program
# function computes the gross salary from basic
salary.
def calculate_gross_salary(basic_salary):
hra = 0;
da = 0;
# salary is less than 2500, hra and da is calculated
if (basic_salary < 2500):
hra = (basic_salary * 10) / 100;
da = (basic_salary * 90) / 100;
else:
hra = 1000;
da = (basic_salary * 95) / 100;
return (basic_salary + hra + da);
if __ name__ == “__main__”:
# Type casting from input string into float value.
basic_salary = float(input(“Enter basic salary: ”));
gross_salary = calculate_gross_salary(basic_salary);
print(“Gross Salary is: %f” % gross_salary);
Output
Enter basic salary: 10000
Gross Salary is: 20500.000000
Decision-Making and Conditionals ◾ 67
Program
#max of 3 numbers using while loop
numbers = [1,2,5,8,4,99,3]
x = 0
lar = numbers[x]
while x < len(numbers):
if numbers[x] > lar:
lar = numbers[x]
x = x+1
print(lar)
Output
99
The preceding program prints the max of seven numbers using while
loop.
Program
#Infinite loop using while
while True:
num = int(input(“Enter an integer: ”))
print(“The double of”,num,“is”,2 * num)
Output
Enter an integer: 5
The double of 5 is 10
Enter an integer: 7
The double of 7 is 14
Enter an integer: 0
The double of 0 is 0
Enter an integer: -1
The double of -1 is -2
Enter an integer: -0.5
--------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-132-d7b1308085a4> in <module>()
1 #1: Infinite loop using while
68 ◾ Learning Professional Python
The preceding program is for the infinite loop using the while statement.
Program
#Program to Display the Multiplication Table
num = int(input(“ Enter the number : ”))
# using for loop to iterate multiplication 10 times
print(“Multiplication Table of : ”)
for i in range(1,11):
print(num,‘×’,i,‘=’,num*i)
Output
Enter the number : 1
Multiplication Table of :
1 × 1 = 1
1 × 2 = 2
1 × 3 = 3
1 × 4 = 4
1 × 5 = 5
1 × 6 = 6
1 × 7 = 7
1 × 8 = 8
1 × 9 = 9
1 × 10 = 10
The preceding program prints the multiplication table for the given
number using the for statement.
Program
# Python program to
# demonstrate continue
# statement
# loop from 1 to 10
for i in range(l, 11):
# If i is equals to 6,
# continue to next iteration
# without printing
if i == 6:
continue
else:
# otherwise print the value
Decision-Making and Conditionals ◾ 69
# of i
print(i, end = “ ”)
Output
1 2 3 4 5 7 8 9 10
Program
#Infinite loop using for
import itertools
for i in itertools.count():
print(i)
Program
#Pascal triangle
n=int(input(“enter range”))
for i in range(0,n):
for s in range(0,n-i):
print(end=“ ”)
for j in range(0,i+1):
if(j==0 or i==0):
c=l
else:
c=(int)(c*(i-j+1)/j)
print(c,end=“ ”)
print()
Output
enter range5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Program
#check even or odd using ternary operator
x=int(input(“enter number”))
s=“even” if x%2==0 else “odd”
print(x,“is”,s)
Output
enter number5
5 is odd
The preceding program used the ternary operator to check whether the
given number is even or odd.
Program
#Max of three numbers using ternary operator
x=int(input(“enter number”))
y=int(input(“enter number”))
z=int(input(“enter number”))
max= x if x>y and x>z else y if y>z else z
print(“max:”,max)
Output
enter number5
enter number9
enter number11
max: 11
The preceding program used the ternary operator to find the max of the
three numbers.
Program
#Max of four numbers using ternary operator
p=int(input(“enter number”))
q=int(input(“enter number”))
r=int(input(“enter number”))
s=int(input(“enter number”))
max= p if p>q and p>r and p>s else
q if q>r and q>s else r if r>s else s
print(“max:”,max)
Decision-Making and Conditionals ◾ 71
Output
enter number4
enter number8
enter number3
enter number2
max: 8
The preceding program used the ternary operator to find the max of the
four numbers.
Program
# Python program to find the largest
# number among the three numbers
def maximum(a, b, c):
if (a >= b) and (a >= c):
largest = a
elif (b >= a) and (b >= c):
largest = b
else:
largest = c
return largest
# Driven code
a = 10
b = 14
c = 12
print(maximum(a, b, c))
Program
# Python3 program to find Smallest
# of three integers using division operator to find
# minimum of three numbers
def smallest(x, y, z):
if (not (y / x)): # Same as “if (y < x)”
return y if (not (y / z)) else z
return x if (not (x / z)) else z
# Driver Code
if __name__== “__main__”:
x = 78
y = 88
z = 68
72 ◾ Learning Professional Python
Output
Minimum of 3 numbers is 68
Program
#Even inclusive range()
step = 2
for i in range(2, 20 + step, step):
print(i, end=‘ ’)
Output
2 4 6 8 10 12 14 16 18 20
Program
#range() indexing and slicing
range1 = range(0, 10)
# first number (start number) in range
print(range1[0])
# access 5th number in range
print(range1[5])
#Output 5
# access last number
print(range1[range1.stop - 1])
Output
0
5
9
Program
#Negative indexing range
# negative indexing
# access last number
print(range(10)[-1])
# output 9
# access second last number
print(range(10)[-2])
Decision-Making and Conditionals ◾ 73
Output
9
8
Program
#Slicing range
for i in range(10)[3:8]:
print(i, end=‘ ’)
Output
3 4 5 6 7
Program
#Reverse range
for i in reversed(range(10, 21, 2)):
print(i, end=‘ ’)
Output
20 18 16 14 12 10
Program
#One-Line while Loops
n = 5
while n> 0: n -= 1; print(n)
Output
4
3
2
1
0
Program
# Use of break statement inside the loop
for val in “string”:
if val == “i”:
break
print(val)
74 ◾ Learning Professional Python
Output
s
t
r
Program
#concatenate two or more range functions using the
itertools
from itertools import chain
a1 = range(10,0,-2)
a2 = range(30,20,-2)
a3 = range(50,40,-2)
final = chain(a1,a2,a3)
print(final)
Output
<itertools.chain object at 0x7f2e824a6ad0>
EXERCISE
1. Write a Python program. Use the while loop and continuously ask
the programmer to enter the word unless the programmer enters the
word “quit”. By entering the word “quit”, the loop should terminate.
2. Write a Python program to read an input from the user and separate
the vowels and consonants in the entered word.
3. Write a Python program to read an input from the user and to print
the uppercase of the entered word.
Chapter 4
Strings
P ython does not provide a character data type. String is a data type
in Python language, and the programmers can create a string by
surrounding characters in quotes.
Syntax
String name=“content inside quotes”
DOI: 10.1201/9781003414322-4 75
76 ◾ Learning Professional Python
Program
s=“this is to test”
print(s[0])
print(s[13])
Output
t
s
The preceding program used the indexing operator ([]) to display the string.
Program
s=“this is to test”
print(s[0:])
print(s[5:10])
print(s[-3])
print(s[-7:-3])
Output
this is to test
is to
e
to t
The preceding program used the slicing operator (:) to display the string.
Program
s=“this is to test”
print(s)
print(“s[:6]--”,s[:6])
print(“s[4:]--”,S[4:])
print(“s[-l]--”,s[-1])
print(“s[-2:]--”,s[-2:])
print(“s[-2:5]--”,s[-2:5])
print(“s[5:-2]--”,s[5:-2])
print(“s[::-1]--”,s[::-1])
Strings ◾ 77
print(“s[-14]--”,s[-14])
print(“s[-15]--”,s[-15])
print(“s[:-1]--”,s[:-1])
print(“s[5:-1]--”,s[5:-1])
print(“s[5:-2]--”,s[5:-2])
print(“s[-5:-2]--”,s[-5:-2])
Output
this is to test
s[:6]-- this i
s[4:]-- is to test
s[-1]-- t
s[-2:]-- st
s[-2:5]--
s[5:-2]-- is to te
s[::-1]-- tset ot si siht
s[-14]-- h
s[-15]-- t
s[:-1]-- this is to tes
s[5:-1]-- is to tes
s[5:-2]-- is to te
s[-5:-2]-- te
Program
s=“this is to test”
print(s[15])
Output
IndexError Traceback (most recent call last)
<ipython-input-12-e2bc36c787f4> in <module>()
1 s=“this is to test”
----> 2 print(s[15])
IndexError: string index out of range
Program
s=“this is to test”
print(s[1.5])
78 ◾ Learning Professional Python
Output
TypeError Traceback (most recent call last)
<ipython-input-13-8a4d10de04c8> in <module>()
1 s=“this is to test”
----> 2 print(s[1.5])
TypeError: string indices must be integers
Program
s=“this is to test”
print(s)
s=“india”
print(s)
Output
this is to test
india
We can modify the part of the string by using the slicing operator.
Program
s=“this is to test”
print(s[0:])
print (“updated string :- ”, s[:6] + ‘Python’)
Output
this is to test
Updated String :- this iPython
In the preceding program, from the six character onwards, the string
has been modified as the string Python. Modified the string “s to test” with
the string “python”.
Strings ◾ 79
Program
s=“Vijayawada”
print(s)
s=“pyhton”
print(s)
s=“string example”
print(s)
s=“this is to test”
print(s)
Output
vijayawada
pyhton
string example
this is to test
Program
print(“\\”)
80 ◾ Learning Professional Python
Output
\
Program
s=“python”
print(s+s)
print(s+s+s)
print(s*4)
print(‘t’ in s)
print(‘t’ not in s)
print(“12345”*3)
Output
pythonpython
pythonpythonpython
pythonpythonpythonpython
True
False
123451234512345
Program
s=“{}{}{}{}”.format(‘this’, ‘is’, ‘for’, ‘test’)
print(s)
s=“{} {} {} {}”.format(‘this’, ‘is’, ‘for’, ‘test’)
print(s)
s=“{3}{2}{1}{0}”.format(‘this’, ‘is’, ‘for’, ‘test’)
print(s)
s=“{t}{i}{f}{e}”.format(t=‘this’,i=‘is’,f=‘for’,e=‘t
est’)
print(s)
s=“{}, string format example”.format(“pyhton”)
print(s)
s=“string example in {}”.format(“pyhton”)
print{s)
s=“this example is for {}, string”.format(“pyhton”)
print(s)
82 ◾ Learning Professional Python
Output
thisisfortest
this is for test
testforisthis
thisisfortest
pyhton, string format example
string example in pyhton
this example is for pyhton, string
Program
s=“this is to test”
print(s)
s1=‘this is to test’
print(s1)
s2=“ ‘this is to test’ ”
print(s2)
s3=‘ “this is to test” ’
print(s3)
s4=‘‘‘this is
to
test’’’
print(s4)
s5=“this is \n to test”
print(s5)
s5=“this is \t to test”
print(s5)
print(“ ‘{}’ ”.format(“this is to test”))
print(‘ “{}” ’.format(“this is to test”))
st=“this is to test”
print(“%s”%st)
print(“\\%s\\”%st)
print(“\“%s\””%st)
print(“It\’s pyhton \‘String\’ testing”)
print(“\”Python\“ String example”)
print(r“\”Python\“ String example”)#raw string
print(R“\”Python\“ String example”)#raw string
print(“{:.7}”.format(“this is to test”))
Strings ◾ 83
Output
this is to test
this is to test
‘this is to test’
“this is to test”
this is
to
test
this is
to test
this is to test
‘this is to test’
“this is to test”
this is to test
\this is to test\
“this is to test”
It’s python ‘String’ testing
“Python” String example
\“Python” String example
\“Python\” String example
this is
Program
print(“this {0:10} is to test {1:10} {2:10}”.format
(‘example’,‘pyhton’,‘string’))
print(“this {0:>10} is to test {1:>10} {2:>10}”.format
(‘example’,‘pyhton’,‘string’))
print(“this {0:<10} is to test {1:<10} {2:<10}”.format
(‘example’,‘pyhton’,‘string’))
print(“this {0:^10} is to test {1:^10} {2:^10}”.format
(‘example’,‘pyhton’,‘string’))
print(“this {0:@>10} is to test {1:*>10}{2:&>10}”.format
(‘example’,‘pyhton’,‘string’))
print(“this {0:$<10} is to test {1:%<10} {2:~<10}”.format
(‘example’,‘pyhton’,‘string’))
print(“this {0:#^10} is to test {1:!^10} {2:*^10}”.format
(‘example’,‘pyhton’,‘string’))
84 ◾ Learning Professional Python
Output:
this example is to test pyhton string
this example is to test pyhton string
this example is to test pyhton string
this example is to test pyhton string
this @@@example is to test ****pyhton &&&&string
this example$$$ is to test pyhton%%%% string~~~~
this #example## is to test !!pyhton!! **string**
The preceding program formats the strings using the alignments by format ().
Program
s=“““this is
to test”””
print(s)
Output
this is
to test
Program
print(u‘test’)
Output
test
Program
s=“Vijayawada”
print(s)
s[0]=‘b’
Output
Vijayawada
------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-18-1f023e1b5186> in <module>()
1.s=“Vijayawada”
2 print(s)
---->3 s[0]=‘b’
TypeError: ‘str’ object does not support item assignment
86 ◾ Learning Professional Python
The preceding program tries to modify the string using = operator. The
interpreter throws error. To modify the string, we must use the predefined
method replace ().
Program
s=“Vijayawada”
print(s)
print(s.replace(‘V’,‘B’))
Output
Vijayawada
Bijayawada
Program
s=“this is to test”
print(s.capitalize())
print(s.lower())
print(s.swapcase())
print(s.title())
print(s.upper())
print(s.count(‘t’))
print(s.find(‘s’))
print(s.index(‘is’))
print(s.rfind(‘is’))
print(s.rindex(‘is’))
print(s.startswith(‘this’))
print(s.endswith(‘t’))
print(“ this is to test ”.lstrip())
print(“ this is to test ”.rstrip())
print(“ this is to test ”.strip())
print(s.partition(‘@’))
print(s.rpartition(‘@’))
print(s.split())
print(s.rsplit())
print(s.splitlines())
print(“this \t is \v to \b test”.splitlines())
print(“this is to test”.casefold())
print(“THIS IS TO TEST”.casefold())
print(s.encode())
Strings ◾ 87
Output
This is to test
this is to test
THIS IS TO TEST
This Is To Test
THIS IS TO TEST
4
3
2
5
5
True
True
this is to test
this is to test
this is to test
(‘this is to test’, ‘’, ‘’)
(‘’, ‘’, ‘this is to test’)
[‘this’, ‘is’, ‘to’, ‘test’]
[‘this’, ‘is’, ‘to’, ‘test’]
[‘this is to test’]
[‘this \t is ’, ‘to \x08 test’]
this is to test
this is to test
b‘this is to test’
Program
s=“python”
print(“the given sting is: ”,s)
del s
print(s)
Output
the given sting is: python
-----------------------------------------------------------------
88 ◾ Learning Professional Python
The preceding program deletes the string s. After deleting the string,
when the user tries to retrieve the string, the name error, the string not
defined is thrown.
Program
s=“this is to test”
del s[1]
Output
--------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-8-6bfc7ff42e45> in <module>()
1 s=“this is to test”
----> 2 del s[1]
TypeError: ‘str’ object doesn’t support item deletion
The preceding program tries to delete the part of the string. Python
does not support deleting the part of the string, so we got the error.
EXERCISE
1. Write a Python program using the new line and the escape characters
to match the expected result as follows:
“This is”
“to test”
“Python language”
2. Write a program to count the number of the characters in the string
(Do not use the predefined method).
3. Access the first three characters and the last two characters from the
given string.
Strings ◾ 89
Lists
5.1 INTRODUCTION
List is a collection of elements, but each element may be a different type.
List is a data type in Python programming language, which can be written
as a list of commas separated values between square brackets. Creating a
list is putting different comma separated values between square brackets.
The list is a type in python used to store multiple objects. It is an ordered
and mutable collection of elements.
The value inside the bracket that selects one element of the list is called
an index, while the operation of selecting an element from the list is called
as indexing. List indexing is shown in Figure 5.1, and the specific indica-
tion of the index is shown in Figure 5.2.
DOI: 10.1201/9781003414322-5 91
92 ◾ Learning Professional Python
FIGURE 5.2 Specific indexing location and its content of the list.
List indices start at 0, and lists can be sliced, concatenated, and soon.
The built functions and the predefined methods are tabulated in Table 5.1
and Table 5.2.
Lists ◾ 93
For loop
r = range(2, 20, 3)
l = list()
for x in r :
l.append(x)
print(1)
Result
[2, 5, 8, 11, 14, 17]
In the cited example, list () is the list constructor and l is the list object
created using the list constructor. The variable r was created using the
94 ◾ Learning Professional Python
range with the starting element of 2 and the ending element with 20 and
increment was 3; that is, the first element is 2, the second element is 5, the
third element is 8, and so on. By using the for loop, the r variable elements
are appended to the list l by using the predefined method append of the list
at line number 4. At line 5 the list is displayed using the print statement.
While loop
l1 = [1, 3, 5, 7, 9]
l = len(l1)
i = 0
while i < l
print(l1[i])
i += 1
1
3
5
7
9
In the cited example, l1 is the list, which consists of five integer ele-
ments. Using the while loop to print the list l1 elements. The variable i
is used as the index variable. The while condition is i<l, that is, the loop
repeats for the length of the list. If the condition is true, then it prints the
list element based on the index location and incrementing the index. If the
while is false, then the while loop gets terminated.
5.3.1 Range
The range function generates the numbers based on the given specified
values. The syntax is
The start indicator is the starting element, end indicator is the end ele-
ment, and step indicator is used to increment the elements.
print(list(range(6)))
Result
[0, 1, 2, 3, 4, 5]
Lists ◾ 95
r = range(2, 20, 5)
l = list(r)
print(l)
Result
[2, 7, 12, 17]
In the cited example, start value is 2 and the end element is number
20 and step is 5. The first element is 2, the second element is (first ele-
ment + step that is 2 + 5 = 7) 7, the third element is (second element +
step=>7 + 5 = 12)12 and so on.
Result
this
[‘this’, ‘is’, ‘to’]
An element with an index equal to – 1 is the last element in the list. The
index – 2 is the one before last element in the list. The negative index for
the list is shown in Figure 5.3, and the list that contains different data types
along with index and negative index is shown in Figure 5.4.
96 ◾ Learning Professional Python
FIGURE 5.4 Negative index for different data types in the list.
Example:
# Python program to Print the length of the list
a = []
a.append(“this”)
a.append(“is”)
a.append(“to”)
a.append(“test”)
print(“The length of list is: ”, len(a))
Result
The length of list is: 4
The cited example prints the length of the list. The variable “a” is created
with the empty list. To that empty list, first the string “this” was appended.
Now the list contains one element, that is, a=[“this”]. Next, three more
strings are appended to the list – append means adding the content to the
last of the existing list. After line 5 the list seems like a= [“this”,” is”,” to”,”
test”]. The length is the total number of the elements of the list. The pre-
defined method len() returns the length of the list.
Lists ◾ 97
Example
#Accessing Elements in Reversed Order
systems = [‘Windows’, ‘macOS’, ‘Linux’]
# Printing Elements in Reversed Order
For o in reversed(systems):
print(o)
Result
Linux
macOS
Windows
The cited example reverses the elements of the list. The reversed () is the
predefined method that reverses the sequence of the elements. The original
sequence of the list is the Windows, MacOS, and Linux. After applying the
reversed () on the list systems, the sequence becomes Linux, MacOS, and
Windows.
Example
#program to swap any two elements in the list
# Getting list from user
myList = []
length = int(input(“Enter number of elements: ”))
for i in range(0, length):
val = int(input())
myList.append(val)
print(“Enter indexes to be swapped”)
index1 = int(input(“index 1: ”))
index2 = int(input(“index 2: ”))
print(“Initial List: ”, myList)
# Swapping given elements
myList[index1], myList[index2] = myList[index2],
myList[index1]
# printing list
print(“List after Swapping: ”, myList)
Result
Enter number of elements: 4
98 ◾ Learning Professional Python
2
4
7
9
Enter indexes to be swapped
index 1: 1
index 2: 3
Initial List: [2, 4, 7, 9]
List after Swapping: [2, 9, 7, 4]
The cited example swaps the elements in the list. The list name myl-
ist the list variable, and it is the empty list. The length consists of the
count value, which the user wants to enter the number of values to the
list. The user-entered value is stored in the variable val, and this variable
is appended to the list mylist. Later swapped the index1 value with the
index2 value.
Example
#Negative List Indexing In a Nested List
L = [‘a’, ‘b’, [‘cc’, ‘dd’, [‘eee’, ‘fff’]], ‘g’, ‘h’]
print(L[-3])
# Prints [‘cc’, ‘dd’, [‘eee’, ‘fff’]]
print(L[-3] [-1])
# Prints [‘eee’, ‘fff’]
print(L[-3] [-1] [-2])
Result
[‘cc’, ‘dd’,[‘eee’, ‘fff’]]
[‘eee’, ‘fff’]
eee
The cited example retrieves the list elements using the negative index.
The index – 1 represents the list element ‘h’ and – 2 represents the list ele-
ment ‘g’, – 3 list element [‘cc’, ‘dd’, [‘eee’, ‘fff’]], – 4 list element ‘b’, and – 5
points to the list element ‘a’. In line 4, L [-3] [-1] first retrieves the element
[‘cc’, ‘dd’, [‘eee’, ‘fff’]] and later – 1 retrieves the element [‘eee’, ‘fff’]. L [-3]
[-1] [-2] first retrieves the – 3 element [‘cc’, ‘dd’, [‘eee’, ‘fff’]] and later – 1
retrieves the element [‘eee’, ‘fff’]. In this list – 1 is ‘fff’ and – 2 is ‘eee’. So L
[-3] [-1] [-2] retrieves the element ‘eee’.
Lists ◾ 99
Example
L1= [‘this’, ‘is’, ‘to’, ‘test’]
print(L1[0:3])
L1[1] =‘testing’
print(L1[0:3])
Result
[‘this’, ‘is’, ‘to’]
[‘this’, ‘testing’, ‘to’]
Example
# Python program to demonstrate comparison
# between extend, insert and append
# assign lists
list_1 = [1, 2, 3]
list_2 = [1, 2, 3]
list_3 = [1, 2, 3]
a = [2, 3]
# use methods
list_1.append(a)
list_2.insert(3, a)
list_3.extend(a)
# display lists
print(list_1)
print(list_2)
print(list_3)
Result
[1, 2, 3, [2, 3]]
[1, 2, 3, [2, 3]]
[1, 2, 3, 2, 3]
100 ◾ Learning Professional Python
Example
L1=[‘this’, ‘is’, ‘to’, ‘test’]
print(L1[0:4])
print(L1[3])
del(L1[3])
print(L1[0:3])
Result
[‘this’, ‘is’, ‘to’, ‘test’]
test
[‘this’, ‘is’, ‘to’]
In the cited example, del () method is used to delete the elements from
the list. The statement del(L1[3]) deletes the index 3 element from the list,
that is, the string test is deleted from the list L1.
5.7 SORTING
Sort the list is sorting the elements of the list, that is, arranging the ele-
ments in the list. The predefined methods sort () and sorted () are used to
sort the list.
vowels.sort()
# print vowels
print(‘sorted list: ’, vowels)
Result
sorted list: [‘a’, ‘e’, ‘i’, ‘o’, ‘u’]
Example
# Python prog to illustrate the following in a list
def find_len(list1):
length = len(list1)
list1.sort()
print(“Largest element is:”, list1[length-1])
print(“Smallest element is:”, list1[0])
print(“Second Largest element is:”, list1[length-2])
print(“Second Smallest element is:”, list1[1])
# Driver Code
list1=[12, 45, 2, 41, 31, 10, 8, 6, 4]
Largest = find_len(list1)
Result
Largest element is : 45
Smallest element is: 2
Second Largest element is : 41
Second Smallest element is: 4
In the cited example, the list is sorted using the sort () function. After
sorting the list, it displays the first largest element, second largest element,
first smallest, and the second smallest element.
5.8 COPYING
The predefined method copy () returns the shallow copy of the list.
Example
#Copying a List
# mixed list
my_list = [‘cat’, 0, 6.7]
# copying a list
102 ◾ Learning Professional Python
new_list = my_list.copy()
print(‘copied List:’, new_list)
Result
Copied List: [‘cat’, 0, 6.7]
The cited example copies one complete list to another list. The pre-
defined method copy copies the my_list elements to the list new_list.
Example
#Copy List Using Slicing Syntax
# shallow copy using the slicing syntax # mixed list
list = [‘cat’, 0, 6.7]
# copying a list using slicing
new_list = list[:]
# Adding an element to the new list
new_list.append(‘dog’)
# Printing new and old list
print(‘Old List:’, list)
print(‘New List:’, new_list)
Result
Old List: [‘cat’, 0, 6.7]
New List: [‘cat’, 0, 6.7, ‘dog’]
In the cited example, the variable list contains three elements. The variable
new_list copies the variable list elements, that is, it does not specify the index
location, so it copies all the target list elements. A string ‘dog’ is appended to
the new_list variable. The new_list contains the elements [‘cat’, 0, 6.7, ‘dog’].
Example
#Repetition operator on Strings
s1=“python”
print (s1*3)
Result
pythonpythonpython
Example
# membership operators in lists
Result
Yes! w found in Hello world
yes! X does not exist in Hello world
Yes! 30 found in [10, 20, 30, 40, 50]
Yes! 90 does not exist in [10, 20, 30, 40, 50]
Syntax
List name [start end]
List name [: end] ~ list name [0: end]
A slice of the list makes a new list, taking elements from the source list
and the elements of the indices from start to end-1.
Note: Can use the negative values for both start and the end
limits.
Example: Slicing
#whole list using slicing
# Initialize list
List = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(“\nSliced List: ”)
Result
Original List:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Sliced Lists:
[4, 6, 8]
[1, 3, 5, 7, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
In the cited example, the variable list consists of nine elements. The state-
ment List [3:9:2] returns the elements starting from index 3, that is, index
3 element is 4, and last slice operator 2 indicates 2 steps increment (that is,
the next element to retrieve is +2 element means index 3 + 2, so retrieves the
index 5 element) retrieves the element 6, and it repeats up to last list index 9.
Result
How many numbers: 4
Enter number 1
Enter number 3
Enter number 5
Enter number 7
Maximum element in the list is : 7
Minimum element in the list is : 1
106 ◾ Learning Professional Python
In the cited example, max () and min () are predefined methods to dis-
play the maximum and the minimum elements from the list.
# Driver program
arr = [1, 23, 12, 9, 30, 2, 50]
# n = len(arr)
k = 3
kLargest(arr, k)
Result
50 30 23
In the cited example, the max three elements are displaying. For this,
first the array is sorted in the ascending order, and later the top three ele-
ments are used by using the for loop.
The negative index for the nested list is represented in Figure 5.6.
L1=[‘A’, ‘B’, [7, “test”, 5.8], 25.5]
Lists ◾ 107
#2D list
a = [[1, 2, 3, 4], [5, 6], [7, 8, 9]]
for i in range(len(a)):
for j in range(len(a[i])):
print(a[i][j], end=‘ ’)
print()
Result
1 2 3 4
5 6
7 8 9
In the cited example, the nested 2D list is presented. The outer list con-
sists of only one element, and the inner list consists of three elements.
Result
3
2
108 ◾ Learning Professional Python
The cited examples display the length of the nested list. The outer list
consists of three elements, and the inner list consists of two elements.
Nested list: 3D
#3D list
x = 2
y = 2
z = 2
a_3d_list = []
for i in range(x):
a_3d_list.append([])
for j in range(y):
a_3d_list[i].append([])
for k in range(z):
a_3d_list[i][j].append(0)
print(a_3d_list)
Result
[[[0, 0], [0, 0]], [[0, 0], [0,0]]]
Result
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4],
[0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
Example
# Nested list comprehension
matrix = [[j for j in range(5)] for i in range(5)]
print(matrix)
Result
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4],
[0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
Example
print (“enter first matrix size”)
row=int (input (“enter row size ”))
col=int (input (“enter column size ”))
a= []
for i in range(row):
c= []
for j in range(col):
c.append(int(input(“number:”)))
a.append(c)
for i in range(row):
for j in range(col):
print(a[i][j],end=“ ”)
print()
Result
enter first matrix size
enter row size 2
110 ◾ Learning Professional Python
Lists can be represented as lists in the cited example. The variable ‘a’
is the empty list and all the user entered elements are stored in the list ‘c’.
Later the list ‘c’ is appended to the list ‘a’.
Example
print(“enter first matrix elements”)
row=int(input(“enter row size ”))
col=int(input(“enter column size ”))
a=[]
for i in range(row):
c=[]
for j in range(col):
c.append(int(input(“number:”)))
a.append(c)
for i in range(row):
for j in range(col):
print(a[i][j],end=“ ”)
print()
print(“enter second matrix elements”)
row1=int(input(“enter row size ”))
col1=int(input(“enter column size ”))
a1=[]
for i in range(row1):
c1=[]
for j in range(col1):
c1.append(int(input(“number:”)))
a1.append(c1)
for i in range(row1):
for j in range(col1):
print(a1[i][j],end=“ ”)
print()
print(“Matrix Addition”)
if row==row1 and col==col1:
Lists ◾ 111
for i in range(row1):
for j in range(col1):
print(a[i][j]+a1[i][j],end=“ ”)
print()
else:
print(“addition not possible”)
Result
enter first matrix elements
enter row size 2
enter column size 2
number:1
number:2
number:3
number:4
1 2
3 4
enter second matrix elements
enter row size 2
enter column size 2
number:5
number:6
number:7
number:8
5 6
7 8
Matrix Addition
6 8
10 12
The cited examples perform the matrix addition. The result shown is
only for 2 × 2 matrix additions. The uses can try other than this row and
column sizes.
Solved Examples
Example
# Python program to Print the length of the list
n = len([10, 20, 30])
print(“The length of list is: ”, n)
112 ◾ Learning Professional Python
Result
The length of list is: 3
Example
# Python program to Print the length of the list
# Initializing list
test_list = [1, 4, 5, 7, 8]
# Printing test_list
print (“The list is : ” + str(test_list))
# Finding length of list using loop Initializing
counter
counter = 0
for i in test_list:
# incrementing counter
counter = counter + 1
# Printing length of list
print (“Length of list using naive method is : ” +
str(counter))
Result
The list is : [1, 4, 5, 7, 8]
Length of list using naive method is : 5
Result
Original List: [‘Windows’, ‘macOS’, ‘Linux’]
Updated List: [‘Linux’, ‘macOS’, ‘Windows’]
Example
#Reverse a List Using Slicing Operator
systems = [‘Windows’, ‘macOS’, ‘Linux’]
Lists ◾ 113
Result
Original List: [‘Windows’, ‘macOS’, ‘Linux’]
Updated List: [‘Linux’, ‘macOS’, ‘Windows’]
Example
#Swapping two values based on their values entered by
the user
# Getting list from user
myList = []
length = int(input(“Enter number of elements: ”))
for i in range(0, length):
val = int(input())
myList.append(val)
print(“Enter values to be swapped ”)
value1 = int(input(“value 1: ”))
value2 = int(input(“value 2: ”))
index1 = myList.index(value1)
index2 = myList.index(value2)
print(“Initial List: ”, myList)
# Swapping given element
myList[index1], myList[index2] = myList[index2],
myList[index1]
# Printing list
print(“List after Swapping: ”, myList)
Result
Enter number of elements: 4
1
3
4
5
Enter values to be swapped
value 1: 3
value 2: 5
114 ◾ Learning Professional Python
Example
#Python program to interchange first and last elements
in a list
# Swap function
def swapList(newList):
size = len(newList)
# Swapping
temp = newList[0]
newList[0] = newList[size - 1]
newList[size - 1] = temp
return newList
# list
newList = [12, 35, 9, 56, 24]
print(swapList(newList))
[24, 35, 9, 56, 12]
Example
#Swap the first and last elements is to use inbuilt
function list.pop().
# Swap function
def swapList(list):
first = list.pop(0)
last = list.pop(-1)
list.insert(0, last)
list.append(first)
return list
#list
newList = [12, 35, 9, 56, 24]
print(swapList(newList))
Result
[24, 35, 9, 56, 12]
Example
#Reverse the first half of list elements in python
l=list(map(int,input(“Enter Number:”).split()))
start=0
Lists ◾ 115
stop=len(l)//2 -1
while(start<stop):
l[start],l[stop]=l[stop],l[start]
start+=1
stop-=1
print(l)
Result
Enter Numbers:4
[4]
Result
Updated List: [‘a’, ‘e’, ‘i’, ‘o’, ‘u’]
Example
#Inserting a Tuple (as an Element) to the List
mixed_list = [{1,2}, [5, 6, 7]]
# number tuple
number_tuple = (3, 4)
# inserting a tuple to the list
mixed_list.insert(1, number_tuple)
print(‘Updated List:’, mixed_list)
Result
Updated List: [{1, 2}, (3, 4), [5, 6, 7]]
Example
# python program to demonstrate working of append
function
# assign list
l = [‘pythom’]
116 ◾ Learning Professional Python
# use method
l.append(‘program’)
l.append(‘course’)
# display list
print(l)
Result
[‘pythom’, ‘program’, ‘course’]
Example
#Nested List
L = [‘a’, ‘b’, [‘cc’, ‘dd’, [‘eee’, ‘fff’]], ‘g’, ‘h’]
print(L[2])
# Prints [‘cc’, ‘dd’, [‘eee’, ‘fff’]]
print(L[2][2])
# Prints [‘eee’, ‘fff’]
print(L[2][2][0])
# Prints eee
Result
[‘cc’, ‘dd’, [‘eee’, ‘fff’]]
[‘eee’, ‘fff’]
eee
Example
import functools
# filtering odd numbers
lst = filter(lambda x : x % 2 == 1, range(1,20))
print(lst)
# filtering odd square which are divisible by 5
lst = filter(lambda x : x % 5 == 0,
[x ** 2 for x in range(1,11) if x % 2 ==1])
print(lst)
# filtering negative numbers
lst = filter((lamba x: x < 0), range(-5,5))
print(lst)
# implementing max() function, using
print (functools.reduce(lambda a,b: a if (a > b) else
b, [7, 12, 45, 100, 15]))
Lists ◾ 117
Result
<filter object at 0x7f9ec4201f50>
<filter object at 0x7f9ec84b4410>
<filter object at 0x7f9ec4201f50>
100
Example 18
x= []
t=x [0]
print(t)
Result
–-----------------------------------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-12-a29e2cf34d86> in <module>()
1 x= []
– ----> 2 t=x [0]
3 print(t)
IndexError: list index out of range
– --------------------------
Example
# Python code to clone or copy a list Using the
in-built function list()
def Cloning(li1):
li_copy = li1
return li_copy
# list
li1 = [4, 8, 2, 10, 15, 18]
li2 = Cloning(li1)
print(“Original List:”, li1)
print(“After Cloning:”, li2)
Result
Original List: [4, 8, 2, 10, 15, 18]
After Cloning: [4, 8, 2, 10, 15, 18]
118 ◾ Learning Professional Python
Example 36
# python code to clone or copy a list Using list
comprehension
def Cloning(li1):
li_copy = [i for i in li1]
return li_copy
# list
li1 = [4, 8, 2, 10, 15, 18]
li2 = Cloning(li1)
print(“Original List:”, li1)
print(“After Cloning:”, li2)
Result
Original List: [4, 8, 2, 10, 15, 18]
After Cloning: [4, 8, 2, 10, 15, 18]
Example
# python code to clone or copy a list Using append()
def closing(li1):
li_copy =[]
for item in li1: li_copy.append(item)
return li_copy
# list
li1 = [4, 8, 2, 10, 15, 18]
li2 = Cloning(li1)
print(“Original List:”, li1)
print(“After Cloning:”, li2)
Result
Original List: [4, 8, 2, 10, 15, 18]
After Cloning: [4, 8, 2, 10, 15, 18]
Example
# python code to clone or copy a list Using bilt-in
method copy()
def Cloning(li1):
li_copy = []
li_copy = li1.copy()
return li_copy
Lists ◾ 119
# list
li1 = [4, 8, 2, 10, 15, 18]
li2 = Cloning(li1)
print(“Original List:”, li1)
print(“After Cloning:”, li2)
Result
Original List: [4, 8, 2, 10, 15, 18]
After Cloning: [4, 8, 2, 10, 15, 18]
Result
Line 1 – a is not available in the given list
Line 2 – b is not available in the given list
Line 3 – a is available in the given list
Example
# * Operator on lists
def multiply(a, b):
return a * b
values = [1, 2]
120 ◾ Learning Professional Python
print(multiply(*values))
print(multiply(1,2))
Result
2
2
Example
#Repetition operator on lists
l1=[1,2,3]
print (l1 * 3)
Result
[1, 2, 3, 1, 2, 3, 1, 2, 3]
Example
#Repetition operator on a nested list
l1=[[2]]
l2=l1*2
print (l2)
l1[0][0]=99
print (l1)
print (l2)
Result
[[2], [2]]
[[99]]
[[99], [99]]
Example
#whole list using slicing
# Initialize list
Lst = [50, 70, 30, 20, 90, 10, 50]
# Display list
print(Lst[::])
Result
[50, 70, 30, 20, 90, 10, 50]
Lists ◾ 121
Result
[50, 70, 30, 20, 90, 10, 50]
Example 50
# Negative indexing in lists
my_list = [‘p’,‘r’,‘o’,‘b’,‘e’]
print(my_list[-1])
print(my_list[-5])
Result
e
p
Result
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 8]
122 ◾ Learning Professional Python
Result
[]
Example
#Change Nested List Item Value
L = [‘a’, [‘bb’, ‘cc’], ‘d’]
L[1][1] = 0
print(L)
Result
[‘a’, [‘bb’, 0], ‘d’]
Example
#Add items to a Nested list
L = [‘a’, [‘bb’, ‘cc’], ‘d’]
L[1].append(‘xx’)
print(L)
# Prints [‘a’, [‘bb’, ‘cc’, ‘xx’], ‘d’]
Result
[‘a’, [‘bb’, ‘cc’, ‘xx’], ‘d’]
Example
#Insert items to a Nested list
L = [‘a’, [‘bb’, ‘cc’], ‘d’]
L[1].insert(0, ‘xx’)
print(L)
Result
[‘a’, [‘xx’, ‘bb’, ‘cc’], ‘d’]
Lists ◾ 123
Example
#extend items to a Nested list
L = [‘a’, [‘bb’, ‘cc’], ‘d’]
L[1].extend([1,2,3])
print(L)
# Prints [‘a’, [‘bb’, ‘cc’, 1, 2, 3], ‘d’]
Result
[‘a’, [‘bb’, ‘cc’, 1, 2, 3], ‘d’]
Example
#Remove items from a Nested List
L = [‘a’, [‘bb’, ‘cc’, ‘dd’], ‘e’]
x = L[1].pop(1)
print(L)
# removed item
print(x)
# Prints cc
Result
[‘a’, [‘bb’, ‘dd’], ‘e’]
cc
Example
#Remove items from a Nested List use the del
statement.
L = [‘a’, [‘bb’, ‘cc’, ‘dd’], ‘e’]
del L[1][1]
print(L)
# Prints [‘a’, [‘bb’, ‘dd’], ‘e’]
Result
[‘a’, [‘bb’, ‘dd’], ‘e’]
Example
#Remove items from a Nested List use remove() method
to delete it by value.
124 ◾ Learning Professional Python
Result
[‘a’, [‘bb’, ‘dd’], ‘e’]
Example
#Iterate through a Nested List
L = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]
for list in L:
for number in list:
print(number, end=‘ ’)
Result
1 2 3 4 5 6 7 8 9
Example
# * Operator on lists
def multiply(a, b):
return a * b
values = [1, 2]
print(multiply(*values))
print(multiply(1, 2))
Result
2
2
Example
#Strings are concatenated
s1=“Welcome”
s2=“to”
s3=“python”
s4=s1+s2+s3
print (s4)
Lists ◾ 125
Result
Welcometopython
Example
#Repetition operator on Strings
s1=“python”
print (s1*3)
Result
pythonpythonpython
Example
#Repetition operator on lists
l1=[1,2,3]
print (l1 * 3)
Result
[1, 2, 3, 1, 2, 3, 1, 2, 3]
Example
#Repetition operator on a nested list
l1=[[2]]
l2=l1*2
print (l2)
l1[0][0]=99
print (l1)
print (l2)
Result
[[2], [2]]
[[99]]
[[99], [99]]
Example
#whole list using slicing
# Initialize list
Lst = [50, 70, 30, 20, 90, 10, 50]
126 ◾ Learning Professional Python
# Display list
print(Lst[::])
Result
[50, 70, 30, 20, 90, 10, 50]
Example
#negative slicing
# Initialize list
Lst = [50, 70, 30, 20, 90, 10, 50]
# Display list
print(Lst[-7::1])
Result
[50, 70, 30, 20, 90, 10, 50]
EXERCISE
1. Write a Python program to print only the second element of the
student names list.
2. Write a Python program to print the maximum element in the list.
3. Write a Python program to remove duplicate elements in the list.
Chapter 6
Tuple
T1= ()
If the tuple contains a single element, the programmer must include the
comma operator even if the tuple contains a single element. For example:
T1= (1,)
Program
t=tuple((1,2,3))
print(t)
t1=tuple((“this”,“is”,“to”,“test”))
print(t1)
t2=tuple((1,2,3,3,(“this”,“is”,“to”,“test”,“test”)))
print(t2)
Output
(1, 2, 3)
(‘this’, ‘is’, ‘to’, ‘test’)
(1, 2, 3, 3, (‘this’, ‘is’, ‘to’, ‘test’, ‘test’))
The preceding program demonstrates the tuple creation using tuple ().
Program
t=tuple((1,2,3))
print(t)
t1=tuple((“this”,“is”,“to”,“test”))
print(t1)
t2=tuple((1,2,3,3,(“this”,“is”,“to”,“test”,“test”),
[“test”,1]))
print(t2)
Output
(1, 2, 3)
(‘this’, ‘is’, ‘to’, ‘test’)
(1, 2, 3, 3, (‘this’, ‘is’, ‘to’, ‘test’, ‘test’),
[‘test’, 1])
Program
t=tuple((1,2,3,3,“this”,“is”,“to”,“test”,“test”,
[“test”,1]))
print(t.count(3))
print(t.count(“test”))
print(t.index(3))
print(t.index(“test”))
Output
2
2
2
7
T1=(“this”,“is”,“to”,“test”)
print(T1[0])
print(T1[0:3])
Output
this
(‘this’, ‘is’, ‘to’)
Program
s=tuple((“this”,“is”,“to”,“test”,“python”,“tuple”,
“example”,“collection”,“data”,“type”))
print(s)
130 ◾ Learning Professional Python
print(“s[:6]--”,s[:6])
print(“s[4:]--”,s[4:])
print(“s[-1]--”,s[-1])
print(“s[-2:]--”,s[-2:])
print(“s[-2:5]--”,s[-2:5])
print(“s[5:-2]--”,s[5:-2])
print(“s[::-1]--”,s[::-1])
print(“s[-10]--”,s[-10])
print(“s[-9]--”,s[-9])
print(“s[:-1]--”,s[:-1])
print(“s[5:-1]--”,s[5:-1])
print(“s[5:-2]--”,s[5:-2])
print(“s[-5:-2]--”,s[-5:-2])
Output
(‘this’, ‘is’, ‘to’, ‘test’, ‘python’, ‘tuple’,
‘example’, ‘collection’, ‘data’, ‘type’)
s[:6]-- (‘this’, ‘is’, ‘to’, ‘test’, ‘python’, ‘tuple’)
s[4:]-- (‘python’, ‘tuple’, ‘example’, ‘collection’,
‘data’, ‘type’)
s[-1]-- type
s[-2:]-- (‘data’, ‘type’)
s[-2:5]-- ()
s[5:-2]-- (‘tuple’, ‘example’, ‘collection’)
s[::-1]-- (‘type’, ‘data’, ‘collection’, ‘example’,
‘tuple’, ‘python’, ‘test’, ‘to’, ‘is’, ‘this’)
s[-10]-- this
s[-9]-- is
s[:-1]-- (‘this’, ‘is’, ‘to’, ‘test’, ‘python’,
‘tuple’, ‘example’, ‘collection’, ‘data’)
s[5:-1]-- (‘tuple’, ‘example’, ‘collection’, ‘data’)
s[5:-2]-- (‘tuple’, ‘example’, ‘collection’)
s[-5:-2]-- (‘tuple’, ‘example’, ‘collection’)
Program
t=tuple((1,2,3))
for x in t:
print(x)
t1=tuple((“this”,”is”,”to”,”test”))
Tuple ◾ 131
for x in t1:
print(x)
t2=tuple((1,2,3,3,(“this”,”is”,”to”,”test”,”test”),
[“test”,1]))
for x in t2:
print(x)
Output
1
2
3
this
is
to
test
1
2
3
3
(‘this’, ’is’, ’to’, ’test’, ’test’)
[‘test’, 1]
Program
s=tuple((“this”,“is”,“to”,“test”))
print(s)
print(sorted(s))
print(sorted(s,reverse=True))
Output
(‘this’, ’is’, ’to’, ’test’)
[‘is’, ’test’, ’this’, ’to’]
[‘to’, ’this’, ’test’, ’is’]
print(sorted(s))
print(sorted(s,reverse=True))
Output
(2, 3, 1, 7, 3, 4, 5, 8, 9)
[1, 2, 3, 3, 4, 5, 7, 8, 9]
[9, 8, 7, 5, 4, 3, 3, 2, 1]
The preceding program sorts tuple of numbers using the sorted function.
Program
t=((‘t’,‘h’,‘i’,‘s’))
print(“.join(t))
Output
this
T1=(“this”,“is”,“to”,“test”)
T2=(1,2,3,4,5)
T3=T1+T2
print(T3)
Program
s=tuple((“this”,”is”,”to”,”test”))
print(“s:”,s)
s=list(s)
s.append(“tuple”)
Tuple ◾ 133
s=tuple(s)
print(s)
Output
s: (‘this’, ‘is’, ‘to’, ‘test’)
(‘this’, ‘is’, ‘to’, ‘test’, ‘tuple’)
Program
t=tuple((1,2,3))
print(t)
print(“concat”,t+t)
print(“replicate”,t*3)
Output
(1, 2, 3)
concat (1, 2, 3, 1, 2, 3)
replicate (1, 2, 3, 1, 2, 3, 1, 2, 3)
T1=(“this”,”is”,”to”,”test”)
print(T1[0:3])
del(T1)
print(T1)
Output
(‘this’, ‘is’, ‘to’)
--------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-5-f29dc347d682> in <module>()
2 print(T1[0:3])
3 del(T1)
134 ◾ Learning Professional Python
---->4 print(T1)
NameError: name ’T1’ is not defined
Program
t=tuple((1,2,3))
print(t)
del t
Output
(1, 2, 3)
Program
t=tuple((1,2,3,3,”this”,”is”,”to”,”test”,”test”,
[“test”,1]))
print(t)
t=list(t)
t.remove(3)
print(t)
t.remove(“test”)
print(t)
for x in t:
t.remove(x)
t=tuple(t)
print(t)
Output
(1, 2, 3, 3, ‘this’, ‘is’, ‘to’, ‘test’, ‘test’,
[‘test’, 1])
[1, 2, 3, ’this’, ’is’, ’to’, ’test’, ’test’,
[‘test’, 1]]
[1, 2, 3, ’this’, ’is’, ’to’, ’test’, [‘test’, 1]]
(2, ’this’, ’to’, [‘test’, 1])
Program
t=(1, 2, 3)
t1=(4, 5, 6)
print(t+t1)
Output
(1, 2, 3, 4, 5, 6)
Program
t=(1, 2, 3)
t1=(‘test’)
print(t+t1)
Output
--------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-d4200773bff6> in <module>()
1 t=(1, 2, 3)
2 t1=(‘test’)
----> 3 print(t+t1)
TypeError: can only concatenate tuple (not ”str”) to
tuple
Program
t=(1, 2, 3)
print(t*3)
Output
(1, 2, 3, 1, 2, 3, 1, 2, 3)
Program
t1=(‘test’)
print(t1*3)
Output
testtesttest
Program
s=tuple((“this”,”is”,”to”,”test”,(1,2,3),(“true”,
”false”),”1”))
print(“s:”,s)
print(“this in s:”, ”this” in s)
print(“3 in s:”,3 in s)
print(“false in s:”,”false” in s)
print(“(1,2,3) in s:”,(1,2,3) in s)
print(“(1,2) in s:”,(1,2) in s)
print(“(1,2) not in s:”,(1,2) not in s)
Output
s: (‘this’, ’is’, ’to’, ’test’, (1, 2, 3), (‘true’,
’false’), ’1’)
this in s: True
3 in s: False
false in s: False
(1,2,3) in s: True
(1,2) in s: False
(1,2) not in s: True
Program
s=tuple((1,2,3,4,5,6,9))
print(len(s))
print(max(s))
Tuple ◾ 137
print(min(s))
print(sum(s))
Output
7
9
1
30
Program
s=tuple((1,2,3,4))
s1=tuple((1,2,3))
print(“s:”,s)
print(“s1:”,s1)
print(“s==s1:”,s==s1)
print(“s!=s1”,s!=s1)
print(“s<s1:”,s<s1)
print(“s>s1:”,s>s1)
print(“s>=s1:”,s>=s1)
print(“s<=s1:”,s<=s1)
Output
s: (1, 2, 3, 4)
s1: (1, 2, 3)
s==s1: False
s!=s1 True
s<s1: False
s>s1: True
s>=s1: True
s<=s1: False
Program
# Tuple Largets and Smallest Item
lgsmTuple = (25, 17, 33, 89, 77, 10, 64, 11, 55)
print(“Tuple Items = ”, lgsmTuple)
138 ◾ Learning Professional Python
tupLargest = lgsmTuple[0]
tupSmallest = lgsmTuple[0]
for i in range(len(lgsmTuple)):
if(tupLargest < lgsmTuple[i]):
tupLargest = lgsmTuple[i]
tupLargestPos = i
if(tupSmallest > lgsmTuple[i]):
tupSmallest = lgsmTuple[i]
tupSmallestPos = i
Output
Tuple Items = (25, 17, 33, 89, 77, 10, 64, 11, 55)
Largest Item in lgsmTuple Tuple = 89
Largest Tuple Item index Position = 3
Smallest Item in lgsmTuple Tuple = 10
Smallest Tuple Item index Position = 5
T=(‘this’,’is’,’to’,’test’) # packing
Unpacking:
Program
s=(“this”,”is”,”to”,”test”,(1,2,3),(“true”,
”false”), ”1”)
(a,b,c,d,e,f,g)=s
print(a)
print(b)
print(c)
print(d)
print(e)
print(f)
print(g)
print(“Unpacking-1”)
(a,b,*c)=s
print(a)
print(b)
print(c)
print(“Unpacking-2”)
(a,*b,c)=s
print(a)
print(b)
print(c)
print(“Unpacking-3”)
(*a,b,c)=s
print(a)
print(b)
print(c)
Output
this
is
to
test
(1, 2, 3)
(‘true’, ’false’)
1
Unpacking-1
this
is
140 ◾ Learning Professional Python
Program
t = (‘a’, ’b’, ’c’, ’d’)
print(t[1])
print(t[-1])
print(t[:2])
print(t[1:3])
print(t[::2])
Output
b
d
(‘a’, ’b’)
(‘b’, ’c’)
(‘a’, ’c’)
Tuple ◾ 141
Program
t = (1,2,3,4)
print(t[1])
print(t[-1])
print(t[:2])
print(t[1:3])
print(t[::2])
Output
2
4
(1, 2)
(2, 3)
(1, 3)
Nested Tuple
Program
s=tuple((“this”,”is”,”to”,”test”,(1,2,3),(“true”,
”false”),”1”))
print(s[4])
print(s[4][0])
print(s[4][1])
print(s[4][2])
print(s[5])
print(s[5][0])
print(s[5][1])
Output
(1, 2, 3)
142 ◾ Learning Professional Python
1
2
3
(‘true’, ’false’)
true
false
Program
s=tuple(“this”,”is”,”to”,”test”,[1,2,3],[“true”,
”false”],”1”))
s[4][1]=“test”
print(s)
s[5][0]=“boolean”
print(s)
Output
(‘this’, ’is’, ’to’, ’test’, [1, ’test’, 3], [‘true’,
’false’], ’1’)
(‘this’, ’is’, ’to’, ’test’, [1, ’test’, 3],
[‘boolean’, ’false’], ’1’)
EXERCISE
1. Unpack a tuple with seven different types of elements.
2. Convert a tuple to string.
3. Retrieve the repeated elements of the tuple.
4. Convert a list to a tuple.
5. Find the length of the tuple.
6. Reverse the tuple.
7. Convert a tuple to dictionary.
8. Compute the sum of all the elements of the tuple.
Chapter 7
Sets
7.1 INTRODUCTION
A set is a collection that is unordered and unindexed. In Python, sets are
written with curly brackets.
Output
{‘test’,‘is’,‘to’,‘this’}
{‘test’,‘is’,‘to’,‘this’}
Output
{‘this is to test’, (‘pyhton’, ‘set’, ‘example’),
10.34567, (1, 2, 3)}
{‘this is to test’, (‘pyhton’, ‘set’, ‘example’),
10.34567, (1, 2, 3)}
Pyhton elements
this is to test
(‘pyhton’, ‘set’, ‘example’)
10.34567
(1, 2, 3)
Output
{1, 2, 3, ‘to’, ‘test’, ‘this’, ‘is’}
{1, 2, 3, ‘to’, ‘test’, ‘this’, ‘is’}
{(‘this’, ‘is’, ‘to’, ‘test’, ‘test’), (1, 2, 3, 2)}
Sets ◾ 145
Output
{‘test’, ‘is’, ‘to’, ‘this’}
test
is
to
this
Output
{‘test’, ‘is’, ‘to’, ‘this’}
{‘this’, ‘to’, ‘pyhton’, ‘test’, ‘is’}
{‘this’, ‘to’, ‘pyhton’, ‘set’, ‘test’, ‘is’}
{‘this’, ‘example’, ‘to’, ‘pyhton’, ‘set’, ‘test’,
‘is’}
146 ◾ Learning Professional Python
Output
{‘test’, ‘is’, ‘to’, ‘this’}
{‘python’, ‘this’, ‘example’, ‘to’, ‘set’, ‘test’, ‘is’}
Output
{‘test’, ‘is’, ‘to’, ‘this’}
{‘is’, ‘to’, ‘this’}
{‘is’, ‘to’}
{‘to’}
print(s)
s.clear()
print(s)
del s
Output
{‘test’, ‘is’, ‘to’, ‘this’}
Set()
Output
s: {1, 2, 3, ‘test’}
s1: {1, ‘this’, ‘1’, ‘to’, ‘test’, ‘is’}
s|s1: {1, 2, 3, ‘this’, ‘1’, ‘to’, ‘test’, ‘is’}
s&s1: {1, ‘test’}
s^s1: {2, ‘is’, 3, ‘this’, ‘1’, ‘to’}
s-sl: {2, 3}
s1-s: {‘1’, ‘is’, ‘to’, ‘this’}
148 ◾ Learning Professional Python
Output
s: {1, 2, 3, ‘test’}
test in s: True
1 in s: True
5 in s: False
5 not in s True
Output
{‘test’, ‘is’, ‘to’, ‘this’}
[‘is’, ‘test’, ‘this’, ‘to’]
[‘to’, ‘this’, ‘test’, ‘is’]
Sets ◾ 149
Output
s: {‘test’, ‘is’, ‘to’, ‘this’}
s1: {1, ‘this’, ’1’, ‘to’, ‘test’, ‘is’}
union: {1, ‘this’, ’1’, ‘to’, ‘test’, ‘is’}
intersection: {‘this’, ‘is’, ‘to’, ‘test’}
difference s-s1: set()
difference s1-s: {’1’, 1}
150 ◾ Learning Professional Python
Output
s: {‘test’, ‘is’, ‘to’, ‘this’}
s1: {1, ‘this’, ’1’, ‘to’, ‘test’, ‘is’}
s2: {(‘this’, ‘is’, ‘to’, ‘test’, ‘test’), (1, 2, 3, 2)}
union: {1, ‘this’, ’1’, ‘to’, (‘this’, ‘is’, ‘to’,
‘test’,‘test’), ‘test’, (1, 2, 3, 2), ‘is’}
intersection: set()
difference s-s1: set()
difference s1-s: {’1’, 1}
print(“difference s2-(s1,s,s3):”,
s2.difference(s,s1,s3))
print(“difference s3-(s1,s2,s):”,
s3.difference(s,s1,s2))
Output:
s: {‘test’, ‘is’, ‘to’, ‘this’}
s1: {1, ‘this’, ’1’, ‘to’, ‘test’, ‘is’}
s2: {(‘this’, ‘is’, ‘to’, ‘test’, ‘test’), (1, 2, 3, 2)}
s3: {‘this is to test’, (‘pyhton’, ‘set’, ‘example’),
10.34567, (1, 2, 3)}
Output
s: (1, 2, 3, 4)
s1: (1, 2, 3)
s==s1: False
s!=s1 True
s<s1: False
152 ◾ Learning Professional Python
s>s1: True
s>=s1: True
s<=s1: False
Output
s: {‘test’, ‘is’, ‘to’, ‘this’}
s1: {1, ‘this’, ’1’, ‘to’, ‘test’, ‘is’}
intersection: None
difference s-(s1): None
difference s1-(s): None
Symmetric_difference s-(s1): None
Symmetricdifference s1-(s): None
Syntax
frozenset(object), where object is the object of list, tuple etc.
Output
frozenset({‘test’, ‘is’, ‘to’, ‘this’})
Sets ◾ 153
Output
s: frozenset({‘test’, ‘is’, ‘to’, ‘this’})
s1: frozenset({1, ‘this’, ’1’, ‘to’, ‘test’, ‘is’})
s|s1: frozenset({1, ‘this’, ’1’, ‘to’, ‘test’, ‘is’})
s&s1: frozenset({‘this’, ‘is’, ‘to’, ‘test’})
s^s1: frozenset({1, ’1’})
s-s1: frozenset()
s1-s: frozenset({’1’, 1})
Output
s: frozenset({‘test’, ‘is’, ‘to’, ‘this’})
s1: frozenset({1, ‘this’, ’1’, ‘to’, ‘test’, ‘is’})
union: frozenset({1, ‘this’, ’1’, ‘to’, ‘test’, ‘is’})
intersection: frozenset({‘this’, ‘is’, ‘to’, ‘test’})
difference s-s1: frozenset()
difference s1-s: frozenset({’1’, 1})
symmetric_difference s-s1: frozenset({1, ’1’})
symmetric_difference s1-s: frozenset({1, ’1’})
Output
s: frozenset({l,2,3,4})
s1: frozenset({1,2,3})
Sets ◾ 155
s==s1: False
s!=s1 True
s<s1: False
s>s1: True
s>=s1: True
s<=s1: False
Output
s: frozenset({‘to’, ‘test’, ‘this’, ‘is’})
s1: frozenset({1, ‘to’, ‘this’, ‘is’, ‘test’, ’1’})
s2: {(1, 2, 3, 2), (‘this’, ‘is’, ‘to’, ‘test’,
‘test’)}
s3: frozenset({10.34567, (1, 2, 3), ‘this is to test’,
(‘pyhton’, ‘set’, ‘example’)})
union: frozenset({1, (‘pyhton’, ‘set’, ‘example’), (1,
2, 3, 2), ‘to’, ‘this’, 10.34567, (1, 2, 3), ‘is’,
‘test’, ‘this is to test’, ’1’, (‘this’, ‘is’, ‘to’,
‘test’, ‘test’)})
intersection: frozenset()
difference s-(s1, s2,s3): frozenset()
156 ◾ Learning Professional Python
Output
s: frozenset({‘to’, ‘test’, ‘this’, ‘is’})
s1: frozenset({1, ‘to’, ‘this’, ‘is’, ‘test’, ’1’})
s2: {(1, 2, 3, 2), (‘this’, ‘is’, ‘to’, ‘test’,
‘test’)}
union: frozenset({1, (1, 2, 3, 2), ‘to’, ‘this’, ‘is’,
‘test’, ’1’, (‘this’, ‘is’, ‘to’, ‘test’, ‘test’)})
intersection: frozenset()
difference s-(s1, s2): frozenset()
difference s1-(s, s2): frozenset({1, ’1’})
difference s2-(s1, s): {(1, 2, 3, 2), (‘this’, ‘is’,
‘to’, ‘test’, ‘test’)}
EXERCISE
1. Perform the union and the intersection operations on the set.
2. Verify whether the set is the subset of another set.
3. Remove all elements from the set and the frozen set.
4. Compare two sets.
5. Find the max and min elements from the set and the frozen set.
Chapter 8
Dictionary
Note: Each key must be unique. It may be any type, and keys are
case sensitive.
In dictionary, each key is separated from its value by a colon (:), the items
are separated by the comma operator, and both the keys and values are
enclosed by curly braces.
Program
marks = {‘java’: 80, ’python’: 90, ’ruby’: 86}
print(list(marks)[0])
print(list(marks)[1])
print(list(marks)[2])
print(marks[‘java’])
Output
java
python
ruby
80
The preceding program accesses key elements. The dictionary name in this
program is marks, and it consists of three elements. The keys in the marks
dictionary are java, python, and ruby, and the corresponding values for
the specified keys are 80, 90, and 86. To access the dictionary value, use the
dictionary and its key value, that is, to access the java value from the marks
dictionary, use marks[‘java’].
Program
marks = {‘java’: 80, ’python’: 90, ’ruby’: 86}
if ”java” in marks:
print(“Exists”)
else:
print(“Does not exist”)
Output
Exists
The preceding program checks the existence of the key using the mem-
bership operators.
Program
marks = {‘java’: 80, ’python’: 90, ’ruby’: 86}
print(“java” in marks)
print(“c” not in marks)
Output
True
True
Dictionary ◾ 159
Program
test= (‘a’, ’b’, ’c’)
dict = dict.fromkeys(test)
print(“New Dictionary : %s” % str(dict))
Output
New Dictionary : {‘a’: None, ’b’: None, ’c’: None}
New Dictionary : {‘a’: 11, ’b’: 11, ’c’: 11}
Program
marks = {‘java’: 80, ’python’: 90, ’ruby’: 86}
print(sorted(marks.keys()))
print(sorted(marks.items()))
Output
[‘java’, ’python’, ’ruby’]
[(‘java’, 80), (‘python’, 90), (‘ruby’, 86)]
Program
marks = {‘java’: 80, ’python’: 90, ’ruby’: 86}
print(“Value : %s” % marks.items())
Output
Value : dict_items([(‘java’, 80), (‘python’, 90),
(‘ruby’, 86)])
Program
marks = {‘java’: 80, ’python’: 90, ’ruby’: 86}
print(“Value : %s” % marks.values())
Output
Value : dict_values([80, 90, 86])
Program
marks = {‘java’: 80, ’python’: 90, ’ruby’: 86}
new = ”JAVA”
old = ”java”
marks[new] = marks.pop(old)
print(marks)
Output
{‘python’: 90, ’ruby’: 86, ’JAVA’: 80}
Program
marks = {‘java’: 80, ’python’: 90, ’ruby’: 86}
print(marks.pop(“ruby”,None))
print(marks)
Output
86
{‘java’: 80, ’python’: 90}
Program
marks = {‘java’: 80, ’python’: 90, ’ruby’: 86}
print(marks)
marks[‘pascal’]=99
print(marks)
Dictionary ◾ 161
Output
{‘java’: 80, ’python’: 90, ’ruby’: 86}
{‘java’: 80, ’python’: 90, ’ruby’: 86, ’pascal’: 99}
Program
marks = {‘java’: 80, ’python’: 90, ’ruby’: 86}
print(marks)
marks.update({‘pascal’:99})
print(marks)
Output
{‘java’: 80, ’python’: 90, ’ruby’: 86}
{‘java’: 80, ’python’: 90, ’ruby’: 86, ’pascal’: 99}
The preceding program inserts keys and items in the dictionary using
update ().
Program
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
x = {n: n*n for n in a}
print(x)
Output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64,
9: 81, 10: 100}
Program
d={‘id’:1,’name’:’usharani’,’age’:33,’id’:5}
print(d[‘id’])
Output
5
Output
{1: ’this’, 2: ’is’, 3: ’to’, 4: ’test’}
{‘a’: ’this’, ’b’: ’is’, ’c’: ’to’, ’d’: ’test’}
d=dict.fromkeys(k,v)
print(d)
V1=(10)
d1=dict.fromkeys(k,v1)
print(d1)
d2=dict.fromkeys(k)
print(d2)
Output
{‘k1’: (10, 20, 30), ’k2’: (10, 20, 30), ’k3’: (10,
20, 30)} {‘k1’: 10, ’k2’: 10, ’k3’: 10}
{‘k1’: None, ’k2’: None, ’k3’: None}
Program
d={1:”this”,2:”is”,3:to”,4:”test”}
print(d)
for x in d:
print(“key:”,x,”value:”,d.get(x))
print(“using index”)
for x in d:
print(d[x])
print(“keys”)
for x in d.values():
print(x)
print(“values”)
for x in d.keys():
print(x)
print(“items”)
for x,y in d.items():
print(x,y)
164 ◾ Learning Professional Python
Output
{1: ’this’, 2: ’is’, 3: ’to’, 4: ’test’}
key: 1 value: this
key: 2 value: is
key: 3 value: to
key: 4 value: test
using index
this
is
to
test
keys
this
is
to
test
values
1
2
3
4
items
1 this
2 is
3 to
4 test
Program
d={1:”this”,2:”is”,3:”to”,4:”test”}
k=d.keys()
print(k)
v=d.values()
print(v)
x=d.items()
print(x)
Output
dict_keys([1, 2, 3, 4])
dict_values([‘this’, ’is’, ’to’, ’test’])
dict_items([(1, ’this’), (2, ’is’), (3, ’to’) (4,
’test’)])
Dictionary ◾ 165
The preceding program prints the dictionary keys and values separately.
Output
origianal {3: ’to’, 2: ’is’, 1: ’this’, 4: ’test’}
sorting keys [1, 2, 3, 4]
sorted dictionary: [(1, ’this’), (2, ’is’), (3, ’to’),
(4, ’test’)]
sorted reverse dictionary: [(4, ’test’), (3, ’to’),
(2, ’is’), (1, ’this’)]
• By using copy ()
• By using = operator
Program
d={1:”this”,2:”is”,3:”to”,4:”test”}
print(d)
d1=d.copy()
print(d1)
d2=dict(d)
print(d2)
Output
{1: ’this’, 2: ’is’, 3: ’to’, 4: ’test’}
{1: ’this’, 2: ’is’, 3: ’to’, 4: ’test’}
{1: ’this’, 2: ’is’, 3: ’to’, 4: ’test’}
Program
d={1:”this”,2:”is”,3:”to”,4:”test”}
print(d)
d1=d
print(“copy d1:”,d1)
d2=dict(d)
print(“copy uisng dict():”,d2)
Output
{1: ’this’, 2: ’is’, 3: ’to’, 4: ’test’}
copy d1: {1: ’this’, 2: ’is’, 3: ’to’, 4: ’test’}
copy uisng dict(): {1: ’this’, 2: ’is’, 3: ’to’, 4:
’test’}
Program
d={‘a’: ’this’, ’b’: ’is’, ’c’: ’to’, ’d’: ’test’}
d1={‘a1’: ’this’, ’b1’: ’is’, ’c1’: ’to’, ’d1’:
’test’}
d2={“d”: d, ”d1”:d1}
print(d2)
Output
{‘d’: {‘a’: ’this’, ’b’: ’is’, ’c’: ’to’, ’d’:
’test’}, ’d1’: {‘a1’: ’this’, ’b1’: ’is’, ’c1’:
’to’, ’d1’: ’test’}}
Program
d={‘a’: ’python’, ’b’: [“this”,”is”,”to”,”test”]}
print(d)
Dictionary ◾ 167
Output
{‘a’: ’python’, ’b’: [‘this’, ’is’, ’to’, ’test’]}
Program
d={‘a’: ’python’, ’b’: tuple((“this”,”is”,”to”,”test”)),
’c’:set((“this is to test”)),’d’:frozenset((“this”,”is
”,”to”,”test”))}
print(d)
Output
{‘a’: ’python’, ’b’: (‘this’, ’is’, ’to’, ’test’),
’c’: {‘o’, ’i’, ’t’, ’h’, ’s’, ”, ’e’}, ’d’:
frozenset({‘test’, ’is’, ’to’, ’this’})}
Program
d={1:”this”,2:”is”,3:”to”,4:”test”}
print(“orginal”,d)
d[4]=“testing”
print(“modified”,d)
d.update({4:”test dictionary”})
print(“updated”,d)
Output
orginal {1: ’this’, 2: ’is’, 3: ’to’, 4: ’test’}
modified {1: ’this’, 2: ’is’, 3: ’to’, 4: ’testing’}
updated {1: ’this’, 2: ’is’, 3: ’to’, 4: ’test
dictionary’}
168 ◾ Learning Professional Python
Program
d={1:”this”,2:”is”,3:”to”,4:”test”}
print(d)
d[“test”]=1
print(d)
Output
{1: ’this’, 2: ’is’, 3: ’to’, 4: ’test’}
{1: ’this’, 2: ’is’, 3: ’to’, 4: ’test’, ’test’: 1}
Program
d={1:”this”,2:”is”,3:”to”,4:”test”}
print(“orginal”,d)
d.update({5:”python”,6:”dictionary”})
print(“updated”,d)
Output
orginal {1: ’this’, 2: ’is’, 3: ’to’, 4: ’test’}
updated {1: ’this’, 2: ’is’, 3: ’to’, 4: ’test’, 5:
’python’, 6: ’dictionary’}
The preceding program adds elements to the dictionary using the update().
Program
d={1:”this”,2:”is”,3:”to”,4:”test”}
print(d)
print(d.popitem())
print(d)
d.pop(1)
print(d)
del d[3]
print(d)
Output
{1: ’this’, 2: ’is’, 3: ’to’, 4: ’test’}
(4, ’test’)
{1: ’this’, 2: ’is’, 3: ’to’}
{2: ’is’, 3: ’to’}
{2: ’is’}
Program
d={1:”this”,2:”is”,3:”to”,4:”test”}
print(d)
d.clear()
print(d)
Output
{1: ’this’, 2: ’is’, 3: ’to’, 4: ’test’}
{}
Program
d={i.lower(): i.upper() for i in ’python’}
print(d)
Output
{‘p’: ’P’, ’y’: ’Y’, ’t’: ’T’, ’h’: ’H’, ’o’: ’O’,
’n’: ’N’}
Program
d={i: i*i for i in range(5)}
print(d)
s=“python”
d1={i: s[i] for i in range(0,len(s))}
print(d1)
d2={i:i*i for i in [1,2,3,4,5]}#uisng list
print(d2)
d3={i:i*i for i in (1,2,3,4,5)}#uisng tuple
print(d3)
d4={i:i*i for i in {1,2,3,4,5}}
print(d4)
d5={x:i for x,i in enumerate([“this”,”is”,”to”,”test”])}
print(d5)
Output
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
{0: ’p’, 1: ’y’, 2: ’t’, 3: ’h’, 4: ’o’, 5: ’n’}
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{0: ’this’, 1: ’is’, 2: ’to’, 3: ’test’}
Program
d={i: i for i in range(20) if i%2==0}
print(“even elements dictionary”,d)
Dictionary ◾ 171
Output
even elements dictionary {0: 0, 2: 2, 4: 4, 6: 6, 8:
8, 10: 10,12: 12,14: 14,16: 16,18: 18}
Program
d={1:”this”,2:”is”,3:”to”,4:”test”}
print(“original”,d)
d1={k:v for(k,v) in d.items()}
print(“copy”,d1)
d2={k*2:v for(k,v) in d.items()}
print(“copy d2”,d2)
d3={k:v*2 for(k,v) in d.items()}
print(“copy d3”,d3)
d4={k:v.capitalize() for(k,v) in d.items()}
print(“copy”,d4)
Output
original {1: ’this’, 2: ’is’, 3: ’to’, 4: ’test’}
copy {1: ’this’, 2: ’is’, 3: ’to’, 4: ’test’}
copy d2 {2: ’this’, 4: ’is’, 6: ’to’, 8: ’test’}
copy d3 {1: ’thisthis’, 2: ’isis’, 3: ’toto’, 4:
’testtest’}
copy {1: ’This’, 2: ’Is’, 3: ’To’, 4: ’Test’}
Program
d={1:’a’,1.5:’b’,True:’c’,(0,1):’d’}
print(d)
Output
{1: ’c’, 1.5: ’b’, (0, 1): ’d’}
Program
d={1:”this”,2:”is”,3:”to”,4:”test”}
print(d)
print(“1 in d:”,1 in d)
print (“test in d:”,”test” in d.values())
print(“5 not in d:”,5 not in d)
Output
{1: ’this’, 2: ’is’, 3: ’to’, 4: ’test’}
1 in d: True
test in d: True
5 not in d: True
Program
d={1:”this”,2:”is”,3:”to”,4:”test”} d1={1:”this”,2:
”is”,3:”to”,4:”test”,
5:”pyhton”,6:”dictionary”}
print(“d:”,d)
print(“d1:”,d1)
print(“d==d1:”,d==d1)
print(“d!=d1:”,d!=1)
Output
d: {1: ’this’, 2: ’is’, 3: ’to’, 4: ’test’}
d1: {1: ’this’, 2: ’is’. 3: ’to’ 4: ’test’, 5:
’pyhton’, 6: ’dictionary’}
d==d1: False
d!=d1: True
EXERCISE
1. Concatenate two dictionaries.
2. Create a dictionary where the keys are the numbers.
3. Sum all the values in the dictionary.
4. Sort a dictionary based on the keys.
5. Find the max value in the dictionary.
6. Print the dictionary in the table form.
7. Split the dictionary into two lists.
Chapter 9
Syntax
from module-name import attribute2[, attribute2 . . .
attribute n]]
To import all names from a module into the current name space, use
import *.
Syntax
from module import *
Namespace
A namespace is a space.
Writing sample1.py
Program
[56] %%writefile sample2.py
def square(n):
print(“square”,n*n)
def cube(n):
print(“cube”,n*n*n)
Writing sample2.py
square 100
cube 125
Program
%%writefile sample3.py
class samp:
def display(self):
print(“display method”)
Writing sample3.py
display method
Program
[64] %%writefile sample4.py
class testing:
def display(self):
print(“display method”)
Writing sample4.py
[65] from sample4 import *
s=testing()
s.display()
display method
Program
[66] %%writefile mymodule.py
class testing1:
def __init__(self,i,j):
print(“constructor”)
self.i=i
self.j=j
def display(self):
print(“i=”,self.i)
print(“j=”,self.j)
Writing mymodule1.py
constructor
i= 10
j= 20
Modules and Packages ◾ 179
Program
[68] %%writefile mymodule1.py
class sample:
def __init__(self,i,j):
print(“constructor”)
self.i=i
self.j=j
def display(self):
print(“i=”,self.i)
print(“j=”,self.j)
Writing mymodule1.py
constructor
i= 10
j= 20
in main prg i= 10
module. In the main program, the variables of the class that existed in
another module was invoked and retrieved the value of those variables.
Program
[70] %%writefile mymodule2.py
class sample:
def __init__(self,i,j) :
print(“constructor”)
self.i=i
self.j=j
def display(self):
print(“i=”,self.i)
print(“j=”,self.j)
Writing mymodule2.py
constructor
i= 10
j= 20
in main prg i= 100
Program
[72] %%writefile mymodule3.py
class sample:
Modules and Packages ◾ 181
def __init__(self,i,j):
print(“sample constructor”)
self.i=i
self.j=j
def display(self):
print(“i=”,self.i)
print(“j=”,self.j)
class test:
def __init__(self,s):
print(“test constructor”)
self.s=s
def put(self):
print(“string:”,self.s)
Writing mymodule3.py
sample constructor
i= 10
j= 20
in main prg i= 100
test constructor
string: python
in main prg i= module example
module. In the main program, the variables of the class that existed in
another module was invoked and retrieved the value of those variables.
t.s=“usharani”
print(“in main prg i=”,t.s)
mymodule5.fun1()
mymodule5.square(5)
mymodule5.cube(5)
Modules and Packages ◾ 183
Output
[‘__builtins__’, ‘__cached__’, ‘__doc__’, ‘__file__’,
‘__loader__’, ‘__name__’, ‘__package__’, ‘__spec__’,
‘cube’, ‘fun1’, ‘samplee’, ‘square’, ‘testt’]
Sample constructor
i= 10
j= 20
in main prg i=,j= 150 450
test constructor
string: test class
in main prg i= usharani
parameterless function
square 25
cube 125
9.3 PACKAGE
A package in Python is a collection of one or more relevant modules.
Program
Step 1: Mounted the GDrive in colab
[11] from google.colab import drive
drive.mount(‘/content/GDrive/’)
Mounted at /content/GDrive/
[13] import os
print (os.listdir(‘GDrive’))
[‘MyDrive’, ‘.shortcut-targets-by-id’,
‘.file-revisions-by-id’, ‘.Trash-θ’]
[16] os.chdir(‘GDrive/MyDrive/pythonpackage’)
184 ◾ Learning Professional Python
Writing p22.py
!ls
Step 5: Imported the pythonpackage and the p1 file and call the
function fun1 that was created in the file p1
[48] import p1
from p1 import *
p1.fun1()
Step 6: Imported the p2 file and call the function fun2 that was cre-
ated in the file p22
import p22
from p22 import *
p22.fun2()
Program
Step 1: Mounted the GDrive in colab
[11] from google.colab import drive
drive.mount(‘/content/GDrive/’)
Mounted at /content/GDrive/
[13] import os
print (os.listdir(‘GDrive’))
[‘MyDrive’, ‘.shortcut-targets-by-id’,
‘.file-revisions-by-id’, ‘.Trash-θ’]
[16] os.chdir(‘GDrive/MyDrive/pythonpackage’)
Output
Sample constructor
i= 10
j= 20
in main prg i=,j= 100 300
test constructor
string: python
in main prg i= package example
The preceding program created classes in the files and store in the pack-
age my_package
Program
p5.py
def f3():
print(“testing outside colab function”)
[93] from google.colab import files
src = list(files.upload().values())[0]
open(‘mylib.py’,’wb’).write(src)
import mylib
mylib.f3()
Choose Files p5.py
• p5.py(n/a) - 53 bytes, last modified:
9/11/2021 - 100% done
Modules and Packages ◾ 187
The preceding program is importing the Python file at run time and
loading that file function at run time. The uploaded file name is p5.py. It is
saved in the local desktop directory and uploaded at run time.
EXERCISE
1. Retrieve the elements of the list in the module program.
2. Retrieve the elements of the dictionary in the module program.
3. Retrieve the elements of the tuple and set in the module program.
4. Print the multiplication table using the module concept.
5. Display the contents of the CSV file using the module concept.
Chapter 10
Functions
1. Function blocks start with the keyword def followed by the user-
defined function name and parentheses.
2. The input parameters or arguments should be put within these
parentheses.
3. The parentheses are followed by the colon (:).
4. The initial statement of a function is the documentation string or doc
string of the function, and this statement is the optional.
Syntax of Function
def function name([parameters]):
#Doc string
Statement-1
Statement-2
Statement-3
return[expression]
Example Program
def test ():
print (“this is inside the function”)
print (“this is the second statement inside the
function”)
test()
Note: The variable name and the function name should not be the
name.
For example:
def test ():
print (“inside function”)
test=“a”
test()
Output
--------------------------------------------------------------
TypeError Traceback (most
recent call last)
Functions ◾ 191
<ipython-input-98-4b4c6e06c695> in <module>()
2 print (“inside function”)
3 test=“a”
---->4 test()
TypeError: ’str’ object is not callable
--------------------------------------------------------------
Type error has occurred in the preceding program because the variable
name and the function name are the same – test is given for both the vari-
able and function.
For example:
test () #calling a function before defining the function
test ()
def test ():
print(“inside function”)
Output
--------------------------------------------------------------
TypeError Traceback (most
recent call last)
<ipython-input-100-a2dea2f337e3> in <module>()
---->1 test () #calling a function before defining the
function test ()
2 def test ():
3 print(“inside function”)
TypeError: ’str’ object is not callable
The name error has occurred in the preceding program because the
function test is calling in line 1 before it is defined. The error name ‘test’ is
not defined has occurred.
There is no limitation for the number of the parameters in the function.
At the time of calling the function, the first argument is copied to the first
parameter, the second argument is copied to the second parameter, and
the process continues for the rest of the arguments.
192 ◾ Learning Professional Python
Program
def sum (i, j):
print (“sum=“, i+ j)
sum (10,20)
Output
sum= 30
Program
def sum (i, j, k):
print (“sum=“, i+ j+ k)
sum (10,20,30)
Output
sum= 60
Program
def test():
global 1
print(1)
1=[2,3,4,5]
1=[0,1]
Functions ◾ 193
test()
print(“in main list=“,1)
Output
[0, 1]
in main list= [2, 3, 4, 5]
In the preceding program the list elements have been modified, and its
new values are reflected back in main function.
For example
def test (i, j):
print(“i=“, i, ”j=“,j)
def(10)
Output
File ”<ipython-input-105-4ec7275e726b>“, line 3
def(10)
^
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable arguments
Program
def test(i,j):
print(“i=“,i,”j=“,j)
test(10,20)
test(20,10)
Output
i= 10 j= 20
i= 20 j= 10
Program
def test(name,surname):
print(“name:”,name,”surname:”,surname)
test(name=“usharani”,surname=“bhimavarapu”)
test(surname=“bhimavarapu”,name=“usharani”)
Output
name: usharani surname: bhimavarapu
name: usharani surname: bhimavarapu
Note: When mixing both the keyword and the positional param-
eters, the positional parameters should be before the keyword parameters.
Program
def add(a,b,c):
print(“add=“,(a+b+c))
add(10,c=20,b=30)
Output
add= 60
The preceding program is about mix of both the positional and the key-
word arguments.
Program
def add(a,b,c):
print(“add=“,(a+b+c))
add(c=10,20,b=30)
Output
File ”<ipython-input-110-f7d678c0b9db>“, line 3
add(c=10,20,b=30)
^
SyntaxError: positional argument follows keyword
argument
196 ◾ Learning Professional Python
Program
def add(a,b,c):
print(“add=“,(a+b+c))
add(c=10,a=20,b=30)
Output
add= 60
Program
def add(a,b,c):
print(“add=“,(a+b+c))
add(10,a=20,b=30)
Output
--------------------------------------------------------------
TypeError Traceback (most
recent call last)
<ipython-input-112-d05b0f077928> in <module>()
1 def add(a,b,c):
2 print(“add=“,(a+b+c))
---->3 add(10,a=20,b=30)
In the preceding program, in function call add (), the first argument
is positional argument, and it is copied to the parameter a. The second
argument is the keyword argument and trying to copy the value 20
again to the parameter a. The error has occurred at this point because
of trying to pass multiple values to the same parameter a. When
using keyword arguments, avoid passing more than one value to one
parameter.
Functions ◾ 197
Program
def add(a=1,b=5,c=8):
print(“add=“,(a+b+c))
add(10)
Output
add= 23
Program
def add(a=1,b=5,c=8):
print(“add=“,(a+b+c))
add(10,20,30)
Output
add= 60
Program
def add(a=1,b=5,c=8):
print(“add=“,(a+b+c))
add()
Output
add= 14
Program
def add(a=1,b=5,c=8):
print(“add=“,(a+b+c))
add(b=10)
Output
add= 19
198 ◾ Learning Professional Python
Program
def add(a=1,b=5,c=8):
print(“add=“,(a+b+c))
add(a=10,c=20)
Output
add= 35
Program
def add(a,b=5,c):
print(“add=“,(a+b+c))
add(a=10,c=20)
Output
File ”<ipython-input-118-957033311ea7>“, line 1
def add(a,b=5,c):
^
SyntaxError: non-default argument follows default
argument
When the user specifies the default arguments before the non-default
argument, an error will arise.
Program
def test(*args):
n = args[0]
for i in args:
if i < n:
n = i
return n
test(4,1,2,3,4)
Functions ◾ 199
Output
1
Syntax
lambda [arg1[, arg2[, arg3 . . . argn]]]: expression
lambda arguments: expression
Program
t=lambda: None
print(t)
Output
〈function〈lambda〉at 0x7f301ff33d40>
Program
j = lambda i : i + 5
print(j(3))
Output
8
Program
m = lambda i,j : i+j
print(m(3,4))
Output
7
Program
s = [1,2,3,4,5,6,7]
m = list(map(lambda i: i + 2, s))
print(m)
Output
[3, 4, 5, 6, 7, 8, 9]
Program
s = [1,2,3,4,5,6,7]
m = list(filter(lambda i: i%2==0, s))
print(m)
Output
[2, 4, 6]
Syntax
return
return(expression)
The return statement stops the function execution and goes back to the
point of the function invocation. When the programmer wants to return
to point of function invocation despite reaching the end of the program,
they can use the variants of the return statement.
Program
def test():
print(“inside function”)
Functions ◾ 201
return;
print(“end of functions”)
print(“in main”)
test()
print(“end of main”)
Output
in main
inside function
end of main
Program
def test():
return None
test()
print(“end of main”)
Output
end of main
Program
def test(i):
if(i<10):
print(“ should be >10”)
return
test(5)
print(“end of main”)
Output
should be >10
end of main
202 ◾ Learning Professional Python
Program
def test(i,j):
return(i+j)
print(“add”,test(5,10))
print(“end of main”)
Output
add 15
end of main
Program
def test(i):
if(i<10):
return True
print(test(5))
Output
True
Program
def test():
s=“test”
print(s)
Functions ◾ 203
Output
python
Program
s=“test”
def test():
s=“python”
print(s)
print(s)
Output
test
Program
def test():
z=10
print(“z=“,z)
print(“z=“,z)
Output
--------------------------------------------------------------
NameError Traceback (most
recent call last)
<ipython-input-144-4bf440bl933a> in <module>()
2 z=10
3 print(“z=“,z)
---->4 print(“z=“,z)
Name error has occurred because the scope of the parameter is in the
function itself. At line 4, trying to print the function parameter outside the
function. So the error x not defined is raised.
Program
def test(x):
i=10
204 ◾ Learning Professional Python
i*=x
print(“inside function i=“,i)
i=25
test(5)
print(“in main i=“,i)
Output
inside function i= 50
in main i= 25
Program
def test():
print(“inside function i=“,i)
i=10
test()
print(“in main i=“,i)
Output
inside function i= 10
in main i= 10
Program
def test():
print(“inside function i=“,i)
i=i+l
i=10
test()
print(“in main i=“,i)
Output
--------------------------------------------------------------
UnboundLocalError Traceback (most recent call
last)
Functions ◾ 205
<ipython-input-130-78236c23d9d2> in <module>()
3 i=i+l
4 i=10
----> 5 test()
6 print(“in main i=“,i)
<ipython-input-130-78236c23d9d2> in test()
1 def test():
----> 2 print(“inside function i=“,1)
3 i=i+1
4 i=10
5 test()
UnboundLocalError: local variable ’i’ referenced
before assignment
Program
def test(i):
print(“inside function i=“,i)
i+=1
i=10
test(i)
print(“in main i=“,i)
Output
inside function i= 10
in main i= 10
Program
def test():
global i
print(“inside function i=“,i)
i=i+1
i=10
test()
print(“in main i=“,i)
Output
inside function i= 10
in main i= 11
By using the global keyword inside the function, despite creating the
new variable inside the function, the function uses the outside function
defined variable. In the preceding program, using the global i at line 2, it
makes the variable i global. At line 4, trying to modify the variable i, this
modification reflects to the outside function.
Program
a=10
def test():
global a
print(“inside function a=“,a)
a=50
print(“in main a=“,a)
Output
in main a= 10
Program
def test(1):
Functions ◾ 207
for i in 1:
print(i)
1=[“this”,”is”,”to”,”test”]
test(1)
Output
this
is
to
test
The preceding program accesses the list elements inside the function.
Program
def test():
global 1
print(1)
1=[2,3]
1=[0,1]
test()
print(“in main list=“,1)
Output
[0, 1]
in main list= [2, 3]
The preceding program modifies the list elements inside the function.
Program
def test():
global 1
print(1)
1=[2,3,4,5]
1=[0,1]
test()
print(“in main list=“,l)
Output
[0, 1]
in main list= [2, 3, 4, 5]
208 ◾ Learning Professional Python
The preceding program appends the list elements inside the function.
Program
def test():
global 1
print(1)
del 1[1]
1=[0,1]
test()
print(“in main list=“,1)
Output
[0, 1]
in main list= [0]
Program
def test():
1=[]
print (“enter how many strings do u want to enter”)
n=int(input())
for i in range(0,n,1):
s=input(“enter string”)
1.insert(i,s)
return 1
print(test())
Output
enter how many strings do u want to enter
3
enter stringtesting
enter stringpython
enter stringsample
[‘testing’, ’python’, ’sample’]
Program
def test():
1=[]
print(“enter how many float \
values do u want to enter”)
n=int(input())
for i in range(0,n,l):
f=float(input(“enter float”))
1.insert(i,f)
return 1
1=test()
print(1)
sum=0
for i in range(len(1)):
sum+=1[i]
print(“sum=“,sum)
Output
enter how many float values do u want to enter
3
enter float1.1
enter float2.2
enter float3.3
[1.1, 2.2, 3.3]
sum= 6.6
10.9 RECURSION
A function calling itself is known as recursion.
Program
def rec(n):
if n == 1:
return n
else:
return n*rec(n-l)
n = 5
if n < 0:
print(“no factorial for negative numbers”)
210 ◾ Learning Professional Python
elif n == 0:
print(“The factorial of 0 is 1”)
else:
print(“The factorial of”, n, ”is”, rec(n))
Output
The factorial of 5 is 120
Program
def fib(n):
if n <= 1:
return n
else:
return(fib(n-l) + fib(n-2))
n = 8
if n <= 0:
print(“enter a positive integer”)
else:
print(“Fibonacci sequence:”)
for i in range(n):
print(fib(i))
Output
Fibonacci sequence:
0
1
1
2
3
5
8
13
Program
def prime(i,n):
if n==i:
return 0
else:
if(n%i==0):
return 1
else:
return prime(i+1,n)
n=9
print (“Prime Number are: ”)
for i in range(2,n+1):
if(prime(2,i)==0):
print(i,end=“ ”)
Output
Prime Number are:
2 3 5 7
EXERCISE
1. Check the output for the following Python program:
def test():
print(“inside function”)
test(“1”)
2. Check the output for the following Python program:
test(“1”)
def test():
print(“inside function”)
test()
212 ◾ Learning Professional Python
Syntax
import time
Example
import time
t=time.time()
print(t)
Output
1631509053.0120902
Example
import time
lt=time.localtime(time.time())
print(lt)
Output
time.struct_time(tm_year=2021, tm_mon=9, tm_mday=13,
tm_hour=4, tm_min=45, tm_sec=30, tm_wday=0,
tm_yday=256, tm_isdst=0)
11.2 CALENDAR
The calendar module has predefined methods to retrieve and process the
year and month.
Example
import calendar
C=calendar.month(2020,10)
print(c)
Output
October 2020
Mo Tu We Th Fr Sa Su
1 2 3 4
5 5 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
The cited example displays the calendar for the month 10 (October) and
for the year 2020.
(Continued)
216 ◾ Learning Professional Python
Syntax
import datetime
Getting the current date by using the datetime module is as follows:
import datatime
d = datetime.date.today()
print(d)
Output
2021-09-29
The today() method in the date class is used to get the date object, which
contains the current local date.
Example
import pytz
print(‘the timezones are’, pytz.all_timezones, ‘\n’)
Example
import pytz
import datetime
from datetime import datetime
218 ◾ Learning Professional Python
u = pytz.uzc
k = pytz.timezone(‘Asia/Kolkata’)
print(‘UTC Time =’, datetime.now(tz=u))
print(‘Asia Time =‘, datetime.now(tz=k))
Output
UTC Time = 2021-09-29 04:15:09.099077 + 00:00
Asia Time = 2021-09-29 09:45:09.100941 + 05:30
In the cited example, datetime instances were created using the time
zone instance.
Output
2021-10-29 04:29:08.289926
2021-11-05 04:29:08.289926
2021-11-05 17:29:08.289926
The cited example computes the relative dates for next week or next
month.
Example
import calendar as c
print(c.month(2020,11))
Date and Time ◾ 219
Output
November 2020
Mo Tu We Th Fr Sa Su
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30
Example
import calendar as c
print(c.leapdays(1920,2020))
Output
25
The cited example prints count the leap years between the range of
years.
Example
from datetime import date
print(date.today())
Output
2021-09-13
Example
import calendar as c
print(c.calendar(2020,1,1,1))
220 ◾ Learning Professional Python
Output
2020
January February March
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 3 4 5 1 2 1
6 7 8 9 10 11 12 3 4 5 6 7 8 9 2 3 4 5 6 7 8
13 14 15 16 17 18 19 10 11 12 13 14 15 16 9 10 11 12 13 14 15
20 21 22 23 24 25 26 17 18 19 20 21 22 23 16 17 18 19 20 21 22
27 28 29 30 31 24 25 26 27 28 29 23 24 25 26 27 28 29
30 31
April May June
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 3 4 5 1 2 3 1 2 3 4 5 6 7
5 7 8 9 10 11 12 4 5 6 7 8 9 10 8 9 10 11 12 13 14
13 14 15 16 17 18 19 11 12 13 14 15 16 17 15 16 17 18 19 20 21
20 21 22 23 24 25 26 18 19 20 21 22 23 24 22 23 24 25 26 27 28
27 28 29 30 25 26 27 28 29 30 31 29 30
July August September
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 3 4 5 1 2 1 2 3 4 5 6
5 7 8 9 10 11 12 3 4 5 6 7 8 9 7 8 9 10 11 12 13
13 14 15 16 17 18 19 10 11 12 13 14 15 16 14 15 16 17 18 19 20
20 21 22 23 24 25 26 17 IS 19 20 21 22 23 21 22 23 24 25 26 27
27 28 29 30 31 24 25 26 27 28 29 30 28 29 30
31
October November December
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 3 4 1 1 2 3 4 5 6
5 6 7 8 9 10 11 2 3 4 5 6 7 8 7 8 9 10 11 12 13
12 13 14 15 16 17 18 9 10 11 12 13 14 15 14 15 16 17 18 19 20
19 20 21 22 23 24 25 16 17 IS 19 20 21 22 21 22 23 24 25 26 27
26 27 28 29 30 31 23 24 25 26 27 28 29 28 29 30 31
30
Example
from datetime import date
t=date.today()
print(“day”,t.day)
print(“month”,t.month)
print(“year”,t.year)
Date and Time ◾ 221
Output
day 13
month 9
year 2021
Example
from datetime import date
t=date.today()
print(“weekday:”,t.weekday())
Output
Weekday: 0
Example
from datetime import datetime
print(“Todays date and time:”,datetime.now())
Output
Todays date and time: 2021-09-13 04:50:10.232992
Example
from datetime import datetime
n=datetime.now()
print(“weekday date and time:”,m.strftime(“%c”))
print(”date” n.strftime(“%x”))
print(“Time:“,n.strftime(“%X”))
print(“Hours and Minutes:”,n.strftime(“%H:%M”))
print(“time with Meridie“,n. strftime(“%I:%M:%S %p”))
222 ◾ Learning Professional Python
Output
weekday date and time: Mon Sep 13 04:50:23 2021
date 09/13/21
Time: 04:50:23
Hours and Minutes: 04:50
time with Meridie 04:50:23 AM
The cited example prints date and time using strftime formats.
Example
from datetime import date
d1=date(20l9,ll,19)
d2=date(2020,ll,17)
d=d2-dl
print(d.days)
print(type(d))
Output
364
<class ‘datetime.timedelta’>
Example
from datetime import date t=datetime.now()
print(“Year 4 digits:”,t.strftime(“%Y”)) print(“Year 2
digits:”,t.strftime(“%y”))
print(“Month:”,t.strftime(“%m”))
print(“Minutes:”,t.strftime(“%M”)) print(“Date”,t.
strftime(“%d”)) print(“weekday”,t.strftime(“%a”))
print(“weekday Fullname”,t.strftime(“%A”))
print(“weekday(decimal)”,t.strftime(“%w”))
print(“Month(abbr)”,t.strftime(“%b”))
print(“Month(FullName)”,t.strftime(“%B”))
print(“Microseconds:“,t.strftime(“%f”))
Output
Year 4 digits: 2021
Year 2 digits: 21
Date and Time ◾ 223
Month: 09
Minutes: 50
Date 13
weekday Mon
weekday Fullname Monday
weekday(decimal) 1
Month(abbr) Sep
Month(FullName) September
Microseconds: 270905
The cited example prints formatted data and time using strftime.
Example
import datetime
print(“Max year”,datetime.MAXYEAR)
print(“Min Year”,datetime.MINYEAR)
print(type(datetime.MAXYEAR)) print(type(datetime.
MINYEAR))
Output
Max year 9999
Min Year 1
<class ‘int’>
<class ‘int’>
The cited example prints the min and max year using the datetime module.
Example
import datetime
print(“Min year”,datetime.date.min)
print(“Min year”,datetime.date.max)
print(type(datetime.date.min))
print(type(datetime.date.max))
Output
Min year 0001-01-01
Min year 9999-12-31
<class ‘datetime.date’>
<class ‘datetime.date’>
224 ◾ Learning Professional Python
The cited example prints the data of the min and max year using the
datetime module.
Example
import datetime
d=datetime.date(2020,11,17)
print(“year:”,d.year)
print(“month:”,d.month)
print(“day:”,d.day)
Output
year: 2020
month: 11
day: 17
The cited example separates the date, month, and year of the given date.
Example
import datetime as d
n=d.date.today()
print(n)
n=n.replace(month=5,year=2021)
print(n)
Output
2021-09-13
2021-05-13
The cited example replaces today’s date with the specified date.
Example
import datetime
d=datetime.date.today()
print(d.timetuple())
Output
time.struct_time(tm_year=2020, tm_mon=11, tm_mday=17,
tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=322,
tm_isdst=-1)
Date and Time ◾ 225
Example
import time
print(time.time())
Output
1605595205.6687665
Example
import calendar as c
from datetime import date
t=date.today()
cal=c.Calendar()
y=t.year
m=t.month
print(cal.monthdays2calendar(y,m))
Output
[[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (1, 6)],
[(2, 0), (3, 1), (4, 2), (5, 3), (6, 4), (7, 5), (8, 6)],
[(9, 0), (10, 1), (11, 2), (12, 3), (13, 4), (14, 5), (15,
6)], [(16, 0), (17, 1), (18, 2), (19, 3), (20, 4), (21, 5),
(22, 6)], [(23, 0), (24, 1), (25, 2), (26, 3), (27, 4),
(28, 5), (29, 6)], [(30, 0), (0, 1), (0, 2), (0, 3), (0,
4), (0, 5), (0, 6)]]
Example
import calendar as c
from datetime import date
t=date.today()
cal=c .Caleindar()
y=t.year
m=t.month
226 ◾ Learning Professional Python
for i in cal.monthdays2calendar(y,m):
print(i)
Output
[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (1, 6)]
[(2, 0), (3, 1), (4, 2), (5, 3), (6, 4), (7, 5), (8, 6)]
[(9, 0), (10, 1), (11, 2), (12, 3), (13, 4), (14, 5), (15, 6)]
[(16, 0), (17, 1), (18, 2), (19, 3), (20, 4), (21, 5), (22, 6)]
[(23, 0), (24, 1), (25, 2), (26, 3), (27, 4), (28, 5), (29, 6)]
[(30, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6)]
Example
import calendar as c
from datetime import date
t=date.today()
y=t.year
m=t.month
c= calendar.TextCalendar(firstweekday=5)
print(c.formatmonth(y,m,w= 5))
Output
September 2021
Sat Sun Mon Tue Wed Thu Fri
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30
Example
import calendar as c
from datetime import date t=date.today()
y=t.year
m=t.month
c= calendar.TextCalendar(firstweekday=l)
print(c.formatmonth(y,m,w=3))
Date and Time ◾ 227
Output
September 2021
Tue Wed Thu Fri Sat Sun Mon
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 IS 19 20
21 22 23 24 25 26 27
28 29 30
Example
import calendar as c
from datetime import date
t=date.today()
y=t.year
m=t.month
cal=c.Calendar()
for i in cal.monthdayscalendar(y,m):
print(i)
Output
[0, 0, 1, 2, 3, 4, 5]
[6, 7, 8, 9, 10, 11, 12]
[13, 14, 15, 16, 17, 18, 19]
[20, 21, 22, 23, 24, 25, 26]
[27, 28, 29, 30, 0, 0 , 0]
Example
import calendar as c
from datetime import date
t=date.today()
y=t.year
m=t.month
cal=c.Calendar()
print(cal.monthdayscalendar(y,m))
228 ◾ Learning Professional Python
Output
[[0, 0, 0, 0, 0, 0, 1], [2, 3, 4, 5, 6, 7, 8], [9, 10,
11, 12, 13, 14, 15], [16, 17, 18, 19, 20, 21, 22],
[23, 24, 25, 26, 27, 28, 29], [30, 0, 0, 0, 0, 0, 0]]
Example
import calendar as c
from datetime import date
t=date.today()
y=t.year
m=t.month
cal=c.Calendar()
for i in cal.itermonthdays2(y,m):
print(i, end=” ”)
Output
(0, 0) (0, 1) (0, 2) (0, 3) (0, 4) (0, 5) (1, 6)
(2, 0) (3, 1) (4, 2) (5, 3) (6, 4) (7, 5) (8, 6)
(9, 0) (10, 1) (11, 2) (12, 3) (13, 4) (14, 5) (15,
6) (16, 0) (17, 1) (18, 2) (19, 3) (20, 4) (21, 5)
(22, 6) (23, 0) (24, 1) (25, 2) (26, 3) (27, 4)
(28, 5) (29, 6) (30, 0) (0, 1) (0, 2) (0, 3) (0, 4)
(0, 5) (0, 6)
Example
import calendar as c
from datetime import date
t=date.today()
cal=c.Calendar(firstweekday=5)
y=t.year
m=t.month
for i in cal.itermonthdays2(y,m):
print(i, end=” ”)
Date and Time ◾ 229
Output
(0, 5) (1, 6) (2, 0) (3, 1) (4, 2) (5, 3) (6, 4) (7,
5) (8, 6) (9, 0) (10, 1) (11, 2) (12, 3) (13, 4) (14,
5) (15, 6) (16, 0) (17, 1) (18, 2) (19, 3) (20, 4)
(21, 5) (22, 6) (23, 0) (24, 1) (25, 2) (26, 3) (27,
4) (28, 5) (29, 6) (30, 0) (0, 1) (0, 2) (0, 3) (0, 4)
Example
import calendar as c
cal=c.Calendar()
for i in cal.iterweekdays():
print(i, end=” ”)
Output
0 1 2 3 4 5 6
Example
import calendar as c
cal=c.Calendar(firstweekday=5)
for i in cal.iterweekdays():
print(i, end=” ”)
Output
5 6 0 1 2 3 4
The cited example retrieves the weekdays if the first day of the week is
the 5.
Example
import calendar as c
from datetime import date
230 ◾ Learning Professional Python
t=date.today()
cal=c.Calendar()
y=t.year
m=t.month
for day in cal.itermonthdays(y,m):
print(day,end=“ ”)
Output
0 0 0 0 0 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
18 19 20 21 22 23 24 25 26 27 28 29 30 0 0 0 0 0 0
Example
import calendar as c
from datetime import date
t=date.today()
cal=c.Calendar()
y=t.year
m=t.month
for i in cal.yeardayscalendar(y,m):
print(i)
Output
[[[0, 0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11, 12],
[13, 14, 15, 16, 17, 18, 19], [20, 21, 22, 23, 24, 25,
26], [27, 28, 29, 30, 31, 0, 0]], [[0, 0, 0, 0, 0, 1,
2], [3, 4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15,
16], [17, 18, 19, 20, 21, 22, 23], [24, 25, 26, 27,
28, 29, 0]], [[0, 0, 0, 0, 0, 0, 1], [2, 3, 4, 5, 6,
7, 8], [9, 10, 11, 12, 13, 14, 15], [16, 17, 18, 19,
20, 21, 22], [23, 24, 25, 26, 27, 28, 29], [30, 31, 0,
0, 0, 0, 0]], [[0, 0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10,
11, 12], [13, 14, 15, 16, 17, 18, 19], [20, 21, 22,
23, 24, 25, 26], [27, 28, 29, 30, 0, 0, 0]], [[0, 0,
0, 0, 1, 2, 3], [4, 5, 6, 7, 8, 9, 10], [11, 12, 13,
14, 15, 16, 17], [18, 19, 20, 21, 22, 23, 24], [25,
26, 27, 28, 29, 30, 31]], [[1, 2, 3, 4, 5, 6, 7], [8,
9, 10, 11, 12, 13, 14], [15, 16, 17, 18, 19, 20, 21],
[22, 23, 24, 25, 26, 27, 28], [29, 30, 0, 0, 0, 0,
Date and Time ◾ 231
The cited example retrieves the month days in the calendar for the com-
plete year.
Example
import calendar as c
from datetime import date
t=date.today()
cal=c.Calendar()
y=t.year
m=t.month
for i in cal.itermonthdates(y,m):
print(i,end=“ ”)
Output
2020–10–26 2020–10–27 2020–10–28 2020–10–29 2020–10–30
2020–10–31 2020–11–01 2020–11–02 2020–11–03 2020–11–04
2020–11–05 2020–11–06 2020–11–07 2020–11–08 2020–11–09
2020–11–10 2020–11–11 2020–11–12 2020–11–13 2020–11–14
2020–11–15 2020–11–16 2020–11–17 2020–11–18 2020–11–19
2020–11–20 2020–11–21 2020–11–22 2020–11–23 2020–11–24
2020–11–25 2020–11–26 2020–11–27 2020–11–28 2020–11–29
2020–11–30 2020–12–01 2020–12–02 2020–12–03 2020–12–04
2020–12–05 2020–12–06
232 ◾ Learning Professional Python
The cited example retrieves the days of the month starting from today’s
date.
Example
import calendar as c
from datetime import date
t=date.today()
y=t.year
m=t.month
cal= calendar.TextCalendar(firstweekday=1)
print(c.prmonth(y,m,w=3))
Output
September 2021
Mon Tue Wed Thu Fri Sat Sun
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
None
Example
import calendar as c
from datetime import date
t=date.today()
y=t.year
m=t.month
cal= calendar.TextCalendar()
print(cal.formatyear(y,2))
Output
2021
January February March
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 3 1 2 3 4 5 6 7 1 2 3 4 5 6 7
4 5 6 7 8 9 10 8 9 10 11 12 13 14 8 9 10 11 12 13 14
11 12 13 14 15 16 17 15 16 17 18 19 20 21 15 16 17 18 19 20 21
18 19 20 21 22 23 24 22 23 24 25 26 27 28 22 23 24 25 26 27 28
25 25 27 28 29 30 31 29 30 31
Date and Time ◾ 233
2021
April May June
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 3 4 1 2 1 2 3 4 5 6
5 6 7 8 9 10 11 3 4 5 6 7 8 9 7 8 9 10 11 12 13
12 13 14 15 16 17 18 10 11 12 13 14 15 16 14 15 16 17 18 19 20
19 20 21 22 23 24 25 17 18 19 20 21 22 23 21 22 23 24 25 26 27
26 27 28 29 30 24 25 26 27 28 29 30 28 29 30
31
July August September
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 3 4 1 1 2 3 4 5
5 6 7 8 9 10 11 2 3 4 5 6 7 8 6 7 8 9 10 11 12
12 13 14 15 16 17 18 9 10 11 12 13 14 15 13 14 15 16 17 18 19
19 20 21 22 23 24 25 16 17 18 19 20 21 22 20 21 22 23 24 25 26
26 27 28 29 30 31 23 24 25 26 27 28 29 27 28 29 30
30 31
October November December
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 3 1 2 3 4 5 6 7 1 2 3 4 5
4 5 6 7 8 9 10 8 9 10 11 12 13 14 6 7 8 9 10 11 12
11 12 13 14 15 16 17 15 16 17 18 19 20 21 13 14 15 16 17 18 19
18 19 20 21 22 23 24 22 23 24 25 26 27 28 20 21 22 23 24 25 26
25 25 27 28 29 30 31 29 30 27 28 29 30 31
The preceding program displays the calendar for the complete year
based on today’s date and year.
Example
import calendar as c
print(c.firstweekday())
Output
0
The preceding program displays the first day of the week in the numeri-
cal form.
Example
from datetime import timedelta
t1 = timedelta(seconds = 15)
234 ◾ Learning Professional Python
t2 = timedelta(seconds = 74)
t3 = t1 - t2
print(“t3 =“, t3)
print(“t3 =“, abs(t3))
Output
t3 = -1 day, 23:59:01
t3 = 0:00:59
Example
from datetime import datetime, timedelta
now = datetime.now()
tomorrow = timedelta(days=+l)
print(now + tomorrow)
Output
2021-09-13 05:52:56.799161
2021-09-14 05:52:56.799161
The preceding program displays today’s date and the next date using the
time delta module.
Example
from datetime import datetime, timedelta
t1 = datetime.now()
t2 = timedelta(days=+1)
print(t1+t2)
Output
2021-09-14 06:52:01.829130
Example
from datetime import datetime, timedelta
t1 = datetime.now()
Date and Time ◾ 235
t2 = timedelta(days=+1)
print(t1-t2)
Output
2021-09-12 06:52:18.075289
Example
from datetime import timedelta
d = timedelta(microseconds=-1)
print(d*5)
Output
-1 day, 23:59:59.999995
Example
from datetime import timedelta
d = timedelta(microseconds=-100)
print(d*0.1)
Output
-1 day, 23:59:59.999990
Example
from datetime import datetime, timedelta
d = timedelta(microseconds=-100)
t2 = timedelta(days=+1)
print(d/t2)
236 ◾ Learning Professional Python
Output
-1.1574074074074074e-09
Example
from datetime import datetime, timedelta
t2 = timedelta(days=+1)
print(t2/5)
Output
4:48:00
Example:
from datetime import datetime, timedelta
t2 = timedelta(days=+1)
print(t2/0.5)
Output
2 days, 0:00:00
Example
from datetime import datetime, timedelta
t1 = timedelta(microseconds=-100)
t2 = timedelta(days=+1)
print(t1%t2)
Output
23:59:59.999900
Example
from datetime import datetime timedelta
tl = timedelta(microseconds=-100)
t2 = timedelta(days=+l)
q,r=divmod(tl,t2)
print(q)
print(r)
Output
-1
23:59:59.999900
Example
from datetime import datetime, timedelta
tl = timedelta(microseconds=-100)
t2 = timedelta(days=+l)
print(+tl)
print(-tl)
print(+t2)
print(-t2)
Output
-1 day, 23:59:59.999900
0:00:00.000100
1 day, 0:00:00
-1 day, 0:00:00
Example
from datetime import datetime, timedelta
tl = timedelta(microseconds=-100)
t2 = timedelta(days=+l)
print(str(tl))
print(str(t2))
238 ◾ Learning Professional Python
Output
-1 day, 23:59:59.999900
1 day, 0:00:00
Example
from datetime import datetime, timedelta
t1 = timedelta(microseconds=-100)
t2 = timedelta(days=+l)
print(repr(tl))
print(repr(t2))
Output
datetime.timedelta(days=-l, seconds=86399,
microseconds=999900)
datetime.timedelta(days=l)
EXERCISE
1. Print a particular weekday using relative delta ().
2. Print the previous month and previous week using relative delta.
3. Write a Python program to subtract three days from today’s date.
4. Write a Python program to print today’s date and the current time.
5. Write a Python program to print today’s date and weekday.
6. Write a Python program to print today’s date, yesterday’s date, and
tomorrow’s date.
7. Write a Python program to print all the Saturdays of the specified
year.
8. Write a Python program to print the delay of 5 minutes 15 seconds
from the current time.
Date and Time ◾ 239
Regular Expression
Syntax
import re
Syntax
re.match(pattern,string,flags=0)
Example
import re
s=“this is to test the python regular expressions”
m=re.match(r’(.*)are(.*?).*’, s,re.M)
print(m)
if m:
print(m.group())
print(m.group(1))
print(m.group(2))
Output
None
Example
import re
s=“this is to test”
x=re.match(“^t . . .”,s)
if x:
print(“found”)
else:
print(“not found”)
Output
found
The preceding program searches whether any word starts with ‘t’ and
word length is four.
Syntax
re.search(pattern,string,flags=0)
Output
First white-space at: 2
In the preceding example the first occurrence of the first empty space
is returned.
Example
import re
str = “This is to test”
s = re.search(“test”, str)
print(s.span())
print(s.group())
print(s.string)
Output
(11, 15)
test
This is to test
The preceding program searches for the string test in the given string
str (i.e., This is to test).
246 ◾ Learning Professional Python
Example
import re
str = “This is to test the regex test”
s = re.search(“test”, str)
print(s)
print(type(s))
Output
<re.Match object; span=(11, 15), match=‘test’>
<class ‘re.Match’>
Example
import re
s = “this is to test”
r = re.search(r“\bt”, s)
print(r.start())
print(r.end())
print(r.span())
Output
0
1
(0, 1)
Example
import re
s = “this is to test”
r = re.search(r“\D{2} t”, s)
print(r.group())
Output
is t
Example
import re
Output
Found “this” in “test” -> Found “is” in “test” ->
Found “to” in “test” -> Found “test” in “test” ->
found a match!
no match
Modifier Description
re.I Case-insensitive matching
re.L By following the current system locale, interpretation of the words using the
alphabetic group
re.M Do search at the end of the line and at the beginning of the line.
re.S checking for period match including the new line
re.U Interprets the letters as per the Unicode letters.
re.X Ignores white space
248 ◾ Learning Professional Python
Pattern Description
^ Searches at the beginning of the line
$ Searches at the end of the line
. checks the single character
[. . .] Searches for the characters within the brackets
[^ . . .] Searches for the characters not with in the brackets
re* Searches for the zero or more occurrences of the specified pattern
re+ Searches for the one or more occurrences of the specified pattern
re? Searches for the zero or one occurrences of the specified pattern
re{n} Searches for the n number of occurrences of the specified pattern
re{n,} Searches for the n or more occurrences of the specified pattern
re{n,m} Searches at least n and at most m occurrences of the specified pattern
a|b Searcher either for a or b
(re) Remember the matched pattern
(?:re) Does not remember the matched pattern
(?# . . .) comment
(?=re) Specifies the position using the pattern
(?!re) Specifies the position using the negation
(?>re) Searches for the independent pattern
\w Searches to match for word
\W Searches to match for non-word
\s Searches for the white space
\S Searches for the non-white space
\d Searches for the digits
\D Searches for the non-digits
\A Returns match pattern if the corresponding characters are at the beginning of
the string.
\Z Search at the end of the string
\z Search at the end of the string
\G returns at the last match found
\b Returns match pattern if the corresponding characters are at the beginning of
the string or at the end of the string.
\B Returns match pattern if the corresponding characters are present in the string
but not at the beginning of the string
\1..\9 Returns a match for any digit between 0 and 9
Syntax
re.compile(patern, flags=0)
Example
import re
x=re.compile(‘\w+’)
Print(x.findall(“This pen costs rs100/-”))
Output
[‘This’, ‘pen’, ‘costs’, ‘rs100’]
Example
import re
x=re.compile(‘\d’)
print(x.findall(“this is my 1st experiment on regex”))
Output
[’1’]
The preceding program extracts the digits from the given string.
Syntax
re.findall(patern,string, flags=0)
250 ◾ Learning Professional Python
Example
import re
x=re.compile(‘\W’)
print(x.findall(“This is costs rs100/0-”))
Output
[‘ ’, ‘ ’, ‘ ’, ‘/’, ‘-’]
Example
import re
x=re.compile(‘\d’)
print(x.findall(“we got independence on 15th
august 1947”))
Output
[’1’, ’5’, ’1’, ’9’, ’4’, ’7’]
The preceding program extracts all the digits from the given string. The
\d extracts all the digits.
Example
import re
x=re.compile(‘\d+’)
print(x.findall(“we got independence on 15th
august 1947”))
Regular Expression ◾ 251
Output
[’15’, ’1947’]
Example
import re
str = “This is to test the regex test”
s = re.findall(“test”, str)
print(s)
Output
[‘test’, ‘test’]
Syntax
re.split(pattern, string, maxsplit=0, flags=0)
Example
import re
s = ‘five:5 twenty one:21 ten:10’
p = ‘\d+’
r=re.split(p, s, 1)
print(r)
252 ◾ Learning Professional Python
Output
[‘five:’, ‘ twenty one:21 ten:10’]
Example
from re import split
print(split(‘\W+’, ‘this, is,to, test’))
print(split(‘\W+’, ‘This, is,to, test’))
print(split(‘\W+’, ‘This is my 1st experiment in re’))
print(split(‘\d+’, ‘This is my 100 experiment in re’))
Output
[‘this’, ‘is’, ‘to’, ‘test’]
[‘This’, ‘is’, ‘to’, ‘test’]
[‘This’, ‘is’, ‘my’, ’1st’, ‘experiment’, ‘in’, ‘re’]
[‘This is my ’, ‘experiment in re’]
Example
import re
print(re.split(‘\d+’, ‘this is 1 test’, 1))
print(re.split(‘[a-f]+’, ‘This IS To Test’, flags=re.
IGNORECASE))
print(re.split(‘[a-f]+’, ‘This IS To Test’))
Syntax
re.sub(pattern, repl, string, count=0, flags=0)
Example
import re
s = ‘this is to test’
p = ‘\s+’
r=‘’
s1 = re.sub(p, r, s)
print(s1)
Output
thisistotest
Example
import re
s = ‘this is to test’
r=‘’
s1 = re.sub(r‘\s+’, r, s, 1)
print(s1)
Output
thisis to test
Example
import re
s = ‘this is to test’
p = ‘\s+’
r=‘’
s1 = re.subn(p, r, s)
print(s1)
Output
(‘thisistotest’, 3)
Output
[‘this is ’, ‘ test’]
[‘This IS To T’, ‘st’]
[‘This IS To T’, ‘st’]
254 ◾ Learning Professional Python
Example
import re
print(re.escape(“this is to test”))
print(re.escape(“this is to test \t ^test”))
Output
this\ is\ to\ test
this\ is\ to\ test\ \ \ \^test
Example
import re
expr = ‘(a^b)’
eqn = ‘f*(a^b) – 3*(a^b)’
re.sub(re.escape(expr) + r‘\Z’, ‘c’, eqn)
Output
‘f*(a^b) – 3*c’
EXERCISE
1. Print a string that has ‘b’ followed by zero or one ‘a’.
2. Find sequences of uppercase letter followed by underscore.
3. Find sequences of uppercase letter followed by lowercase letters.
4. Extract the words that matches a word containing ‘s’.
5. Extract the words that start with a number or a underscore.
6. Extract the words that end with a number.
7. Extract all the substring from the given string.
8. Print the occurrences and the position of the substring within the string.
9. Replace all occurrences of space with a comma.
10. Extract all five-character words from the given string.
Index
A D
abs function, 34 data type, 11
anonymous functions, 199 def statement, 7
append method, 93 del, 79
arguments, 193 dictionary, 140
ASCII character code, 84 dictionary comprehensions, 169
assert, 4
assignments multiple, 12 E
assignment statements, 11, 22
attributes, 175 elif, 41
else, 36
exec, 4
B expression evaluation, 28
binary numeric literals, 16
binary operator, 19 F
Boolean literal, 16
false, 3
break statement, 56
findall method, 249
built-in mathematical functions, 34
floating point numbers, 15
built-in object types
floor division, 20
dictionaries, 158
flush method, 4
lists, 91
function, 168
sets, 143
strings, 75
tuples, 127 G
garbage collection, 2
get method, 162
C
global variable, 11
call-by-reference, 171
comment, 6
I
comparison operator, 20
concatenation operator, 71 if, 35
continue statement, 58 if else statement, 36
curly braces immutability, 127
dictionaries, 157 import statement, 155
sets, 143 indentation, 7
255
256 ◾ Index
U
N
unary operator, 16
namespace, 155 unpacking, 124
negative index, 67
nested conditionals, 45
none variable, 10 V
variable, 8
O
W
object, 230
object-oriented language, 1 while else, 64
operator, 16 while loop, 24