Usharani Bhimavarapu Jude D
Usharani Bhimavarapu Jude D
Usharani Bhimavarapu Jude D
Python Packages
Tomas Beuzen and Tiffany-Anne Timbers
Usharani Bhimavarapu
and Jude D. Hemanth
Cover Image Credit: Shutterstock.com
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.
DOI: 10.1201/9781003414322
Typeset in Minion
by Apex CoVantage, LLC
Contents
Preface
Author Biographies
CHAPTER 4 ◾ Strings
4.1 STRING CREATION
4.2 ACCESSING VALUES TO A STRING
4.3 MODIFY EXISTING STRING
4.4 ESCAPE CHARACTERS
4.5 STRING SPECIAL CHARACTERS
4.6 STRING FORMATTING OPERATOR
4.7 TRIPLE QUOTES
4.8 UNICODE STRINGS
4.9 BUILT-IN STRING METHODS
4.10 DELETING STRING
EXERCISE
CHAPTER 5 ◾ Lists
5.1 INTRODUCTION
5.2 CHARACTERISTICS OF LISTS
5.3 DECISION-MAKING IN LISTS
5.3.1 Range
5.4 ACCESSING VALUES IN THE LIST
5.5 UPDATING LIST
5.6 DELETE LIST ELEMENTS
5.7 SORTING
5.8 COPYING
5.9 OPERATORS ON LISTS
5.10 INDEXING, SLICING
5.11 SEARCHING IN LIST
5.12 NESTED LIST
5.13 LIST COMPREHENSION
5.14 MATRIX REPRESENTATION
EXERCISE
CHAPTER 6 ◾ Tuple
6.1 TUPLE CREATION
6.2 ACCESSING VALUES IN TUPLES
6.3 UPDATING TUPLES
6.4 DELETE TUPLE ELEMENTS
6.5 OPERATIONS ON TUPLES
6.6 UNPACKING OF TUPLES
6.7 INDEXING, SLICING ON TUPLES
EXERCISE
CHAPTER 7 ◾ Sets
7.1 INTRODUCTION
7.2 ACCESS SET ELEMENTS
7.3 ADDING ELEMENTS TO THE SET
7.4 REMOVE AN ELEMENT FROM THE SET
7.5 DELETE THE SET
7.6 PYTHON SET OPERATIONS
7.7 SET MEMBERSHIP OPERATORS
7.8 SET PREDEFINED METHODS
7.9 FROZEN SET
7.10 FROZEN SET OPERATIONS
7.11 FROZEN SET PREDEFINED OPERATIONS
EXERCISE
CHAPTER 8 ◾ Dictionary
8.1 ACCESSING THE ELEMENTS OF THE DICTIONARY
8.2 COPYING THE DICTIONARY
8.3 NESTED DICTIONARY
8.4 CHANGING THE DICTIONARY VALUES
8.5 ADDING THE ELEMENTS TO THE DICTIONARY
8.6 REMOVING THE ELEMENTS OF THE DICTIONARY
8.7 DICTIONARY COMPREHENSION
8.8 OPERATORS IN DICTIONARY
EXERCISE
CHAPTER 10 ◾ Functions
10.1 DEFINING A FUNCTION
10.2 PASS BY REFERENCE
10.3 FUNCTION ARGUMENTS
10.3.1 Required Arguments
10.3.2 Keyword Arguments
10.3.3 Default Arguments
10.3.4 Variable Length Arguments
10.4 ANONYMOUS FUNCTIONS
10.5 RETURN STATEMENT
10.6 FUNCTION VARIABLE SCOPE
10.7 PASSING LIST TO FUNCTION
10.8 RETURNING LIST FROM THE FUNCTION
10.9 RECURSION
EXERCISE
INDEX
Preface
Python Basics
DOI: 10.1201/9781003414322-1
Syntax
this is to test
print(this is to test)
Output
print () can operate with all types of data provided by Python. The data
type data strings, numbers, characters, objects, logical values can be
successfully 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”)
Output
this is to test
this is the second line in python program
In the preceding program, the second line print statement introduces the
empty line.
The following programs illustrate the separator and end argument:
Program
print(“this”,“is”,“to”,“test”,end=“@”)
Output
this is to test@
Program
Output
The string assigned to the end keyword argument can be any length. The
sep arguments value may be an empty string. In the previous example, 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”)
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
continuation character, for example:
a= {1,2,3,4,
5,6,7}
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)
Output
test#1
test#2
In the preceding program, the first and the second print statement
consists 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
x=‘test’;print(x)
Output
test
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.
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)
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.
a=5.0
b=3.0
c=(a**2+b**2)**0.5
print(“c=”,c)
Output
c= 5.830951894845301
a=b=c=1
In the previous line, the value of a, b, and c is 1.
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
1. Implicit conversion
2. Explicit conversion
x=123
y=12.34
print(x+y)
x=123
y=10.0
print(x+y)
x=10 + 1j
y=10.0
print(x+y)
Output
135.34
133.0
(20 + 1j)
x=“test”
y=10
print(x+y)
Output
--------------------------------------------------------------
TypeError Traceback (most recent call last)
<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))
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
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.
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”)
4. Check the following code:
print (true>false)
print (true<false)
5. What is the decimal value for the binary number 1101?
6. What is the decimal value for the binary number 1001?
7. What is the hexadecimal value for the binary number 1101?
8. What is the octal value for the binary number 1101?
9. What is the octal value for the decimal number 145?
10. What is the hexadecimal value for the decimal number 123?
CHAPTER 2
Python Operators
DOI: 10.1201/9781003414322-2
1. Unary Operator
2. Binary Operator
3. Ternary Operator
+, -,
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
a,b=l0,5
2 - subtraction a-b 5
print(a-b)
S.No Operator Name Example Program Result
a,b=l0,5
3 * multiplication a*b 50
print(a*b)
a,b=10,3
4 / division a/b 3.3333333333333335
print(a/b)
a,b=l0,3
5 % modulus a%b 1
print(a%b)
a,b=10,5
6 ** exponentiation a**b 100000
print(a**b)
a,b=10,3
7 // floor division a//b 3
print(a//b)
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.
a,b=10,5
2 += add and a+=b a+=b 15
print(a)
S.No Operator Name Example Program Result
a,b=10,5
3 -= subtract and a-=b a-=b 5
print(a)
a,b=10,5
4 *= multiply and a*=b a*=b 50
print(a)
a,b=10,5
5 /= divide and a/=b a/=b 2.0
print(a)
a,b=10,5
6 %= modulus and a%=b a%=b 0
print(a)
a,b=10,5
7 //= floor division and a//=b a//=b 2
print(a)
a,b=10,5
8 **= exponent and a**=b a**=b 100000
print(a)
a,b=10,5
9 &= bitwise and a&=b a&=b 0
print(a)
a,b=10,5
10 |= bitwise or and a|=b a|=b 15
print(a)
a,b=10,5
11 ^= bitwise xor and a^=b a^=b 15
print(a)
S.No Operator Name Example Program Result
a,b=10,5
12 >>= binary rght shift and a>>=b a>>=b 0
print(a)
a,b=10,5
13 <<= binary left shift and a<<=b a<<=b 320
print(a)
Program
a,b=10,5
2 != not equal to a!=b True
print(a!=b)
a,b=10,5
3 < less than a<b False
print(a<b)
a,b=10,5
4 <= less than equal to a<=b False
print(a<=b)
a,b=10,5
5 > greater than a>b True
print(a>b)
a,b=10,5
6 >= greater than equal to a>=b True
print(a>=b)
Program
a,b=10,5
2 or logical or a or b 10
print(a or b)
a
3 not logical not not a False
print(not a)
Program
a,b=10,5
2 | bitwise or a|b 15
print(a|b)
a,b=10,5
3 ~ bitwise not ã -6
print(~b)
a,b=10,5
4 ^ bitwise xor a ^b 15
print(a^b)
a,b=10,5
5 >> bitwise right shift a>>b 0
print(a”b)
a,b=10,5
6 << bitwise left shift a<<b 320
print(a<<b)
Program
The preceding program is about Python program to perform bitwise
operations.
String*number
Number*string
s=”test”
s1=”ing”
print(s+s1)
Output
testing
print(“test”*3)
print(3*“sample”)
print (3*”1”)#outputs 111 but not 3
Output
testtesttest
samplesamplesample
111
Operator Precedence
Meaning Associativity
Order
() Parentheses left-to-right
** Exponent right-to-left
Unary addition, Unary subtraction,
+,-,~ left-to-right
and unary bitwise not
Multiplication, division, floor
*, /, //, % left-to-right
division, modulus
+, - Addition, subtraction left-to-right
<<, >>
Bitwise shift operators left-to-right
?
& Bitwise and left-to-right
^ Bitwise xor left-to-right
| Bitwise or left-to-right
==, !=, >, >=, <, <=, is, Comparison, identity, and
left-to-right
is not, in, not in membership operators
and, or Logical and, logical or left-to-right
not Logical not right-to-left
=, +=, -
=, *=, /=, %=, &=, ^=, Assignment operators right-to-left
|=, >>=, <<=
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
In the cited example x is the local variable because it is defined inside the
eval function.
Note: The default return type of the input () function is the string.
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
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
Output
The preceding program performed sum of two floats. To convert the input
value to float, there is a need to typecast the input () function with float.
Program
n=int(input(“enter integer”))
print(n*“1”)
Output
enter integer4
1111
The program is about replication operation by reading data from the user.
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))
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
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 complex
mathematical operations like matrix multiplication. The disadvantage is the
mathematical operations performed with the math library are very slow. For
instance, if we consider the example shown here, we performed 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 statement 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 that number. The
floor returns the floor value of the given number. The math.trunc method
returns the truncated part of the number.
Function Description
min (x1, x2 …) The smallest of all its arguments
max (x1, x2 …) The largest of all its arguments
pow (x, y) The value of x**y, i.e. (2**3 = 8) (23=8)
round (x [, n]) X rounded to n digits from the decimal point
sqrt(x) The square root of x
abs(x) The absolute value of x
ceil(x) The smallest integer not less than x
floor(x) The largest integer not greater than x
exp(x) The exponent of x (ex)
log(x) The natural logarithm of x
Iog10(x) The base 10 logarithm of x
fabs((x) The absolute value of x
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
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)
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)
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.)
3. Check the result for this Python program:
print (8/2)
print (8. /2)
print (8/2.)
print (8. /2.)
4. Check the result for this Python program:
print (8//2)
print (8. //2)
print (8//2.)
print (8. //2.)
5. Check the result for this Python program:
print (-8//2)
print (8. //-2)
print (-8//2.)
print (-8. //2.)
6. Check the result for this Python program:
print (8%2)
print (8.5%2)
print (8%2.5)
print (8.5%2.5)
7. Run this Python program and check the result:
print (8 + 2)
print (-8.5 + 2)
print (-8 + 2.5)
print (8. +2.5)
8. Run this Python program and check the result:
print (8–2)
print (-8.5–2)
print (-8–2.5)
print (8.-2.5)
9. What is the output of the following Python program?
print ((4**2) +5%2–3*8)
10. What is the output of the following Python program?
print ((4%2),5**2, (5 + 4**3))
11. Write a Python program, create two variables, and assign different
values to them. Perform various arithmetic operations on them. Try to
print a string and an integer together on one line, for example, “sum=”
and total (sum of all variables).
12. Check the output for the following line:
print (5==5)
13. Check the output for the following line:
print (5==5.)
14. Run this Python program and check the result:
x,y,z=5,6,7
print(x>y)
print(x>z)
15. Run this Python program and check the result:
x,y,z=1,2,3
print(x>y)
print((z-2) ==x)
16. Run this Python program and check the result:
x=5
y=5.0
z=”5”
if(x==y):
print(x)
if (x==int(z)):
print(x)
CHAPTER 3
DOI: 10.1201/9781003414322-3
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.
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
In the preceding program, the first if condition becomes false, so the
corresponding print statement was not executed, and the second if statement
became true, so the corresponding print statement gets executed.
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
Output
Program
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
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
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
If condition 1:
Statements-1
elif condition 2:
#Execute the indented block if the condition-1 becomes false
Statements-2
elif condition 3:
#Execute the indented block if all the above two conditions
become false
. . .. . . . . . . .
elif condition-n:
#Execute the indented block if all the above n-1 conditions
become false
Statements-n
else:
#Execute the indented block if all the above conditions become
false
statement
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
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
Output
Mininum of 3 numbers is 5
The preceding program finds min of three numbers using while loop.
Program
Output
The preceding program prints the multiplication table using while loop.
Syntax
For keyword.
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
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
print(seq)
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
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
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.
3.8 NESTED FOR LOOPS
The nested for loop is used to iterate different data structures and iterable
data objects.
In Python, a for loop inside another for loop.
Syntax
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
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
Output
1
2
3
4
No Break
Syntax
Program
Output
this is t tst
break
Program
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
2
Program
for i in range(3):
for j in range(2):
if j == i:
break
print(i, j)
Output
1 0
2 0
2 1
Program
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
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:
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
for i in “test”:
if i == “s”:
continue
print(i)
Output
t
e
t
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
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
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
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
Output
Program
Output
Program
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
The preceding program is for the infinite loop using the while statement.
Program
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
# 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)
The preceding program is the infinite loop using the or control statement.
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
Output
enter number5
5 is odd
The preceding program used the ternary operator to check whether the
given number is even or odd.
Program
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
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
Program
Output
Minimum of 3 numbers is 68
Program
Output
2 4 6 8 10 12 14 16 18 20
Program
Output
0
5
9
Program
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
Output
4
3
2
1
0
Program
Output
s
t
r
Program
Output
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
DOI: 10.1201/9781003414322-4
Python 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
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
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])
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
Program
s=“this is to test”
print(s[1.5])
Output
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”.
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(“\\”)
Output
Operator Description
+ Concatenation
* Repetition
[] Slice
[:] Range slice
Membership operator – returns true if a specified character exists
In
in a string
Membership operator – returns false if a specified character
not in
exists in a string
% String formatting
r/r Raw string
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
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”))
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
Output:
Program
s=“““this is
to test”””
print(s)
Output
this is
to test
Program
print(u‘test’)
Output
test
Method Description
capitalize () Capitalizes first letter of string.
Count (str, Counts how many times str occurs in string or in substring
beg=0, of string if starting index beg and ending index end are
end=len(string)) given.
Determines if st occurs in string or in a substring of string
find (st, beg=0,
form starting index beg and ending index end are given
end=len(string))
returns index if found and – 1 otherwise.
join (seq) Merges the string.
Method Description
len (st) Returns the length of the string.
lower () Converts all uppercase letters in string to lowercase.
max (str) Returns the max alphabetical character from the string str.
min (str) Returns the min alphabetical character from the string str.
replace (old, Replaces all occurrences of old in string with new or at
new[, max]) most max occurrences if max given.
rstrip () Performs both lstrip () and rstrip () on string.
swapcase () Inverts case for all the letters in the string.
upper () Converts lowercase letters in string to uppercase.
zfill (width) Left padded with zeros to a total of width characters.
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
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())
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 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.
4. Count the number of occurrences of the first character in the given
string.
5. Access the longest word in the given sentence.
6. Exchange the first and the last characters of each word in a sentence.
7. Insert the character <> in the middle of each word in a sentence.
8. Access the words whose length is less than 3.
9. Reverse the words in a sentence.
10. Print the index of the characters of the string.
11. Replace the vowel with a specified character.
12. Remove the duplicate characters from the string.
CHAPTER 5
Lists
DOI: 10.1201/9781003414322-5
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
indication of the index is shown in Figure 5.2.
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.
Method Description
list.append(obj) Adds an element at the end of the list
list.count(obj) Counts the number of elements in the list
list.extend(seq) Adds all elements of the list to another list
list.index(obj) Returns the index of the first matched item
list.insert(index,obj) Inserts the elements at the defined index
list.pop(obj=list [-]) Removes an element at the given index
list.remove(obj) Removes the list
list.reverse() Reverses the order of elements of the list
list.sort([func]) Sorts items in a list in the ascending order
For loop
r = range(2, 20, 3)
l = list()
for x in r :
l.append(x)
print(1)
Result
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 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
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
element, and step indicator is used to increment the elements.
print(list(range(6)))
Result
[0, 1, 2, 3, 4, 5]
r = range(2, 20, 5)
l = list(r)
print(l)
Result
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 element +
step that is 2 + 5 = 7) 7, the third element is (second element + step=>7 + 5
= 12)12 and so on.
5.4 ACCESSING VALUES IN THE LIST
To retrieve values in the list, use the square brackets for slicing along with
the index or indices to acquire value presented at that index. For example:
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.
FIGURE 5.4 Negative index for different data types in the list.
Example:
Result
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
predefined method len() returns the length of the list.
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
Result
The cited example swaps the elements in the list. The list name mylist 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
The cited example retrieves the list elements using the negative index.
The index – 1 represents the list element ‘h’ and – 2 represents the list
element ‘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’.
Example
Result
Example
Result
Example
Result
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 elements
in the list. The predefined methods sort () and sorted () are used to sort the
list.
Example: sort the list elements
Result
Example
# 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
new_list = my_list.copy()
print(‘copied List:’, new_list)
Result
The cited example copies one complete list to another list. The
predefined method copy copies the my_list elements to the list new_list.
Example
Result
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’].
Operator Description
+ Concatenation
* Repetition
In Membership, iteration
not in Not membership
Example
#Repetition operator on Strings
s1=“python”
print (s1*3)
Result
pythonpythonpython
Example
Result
Syntax
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
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
statement 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
# 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 elements
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]
#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
consists of only one element, and the inner list consists of three elements.
Result
3
2
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
Result
Example
# Nested list comprehension
matrix = [[j for j in range(5)] for i in range(5)]
print(matrix)
Result
Example
Result
enter first matrix size
enter row size 2
enter column size 2
number:1
number:2
number:3
number:4
1 2
3 4
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
Result
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
Result
Example
Result
#Reverse a List
systems = [‘Windows’, ‘macOS’, ‘Linux’]
print(‘Original List:’, systems)
# List Reverse
systems.reverse()
# updated list
print(‘Updated List:’, system)
Result
Example
Result
Example
Result
Example
Example
Result
Example
Result
Enter Numbers:4
[4]
Result
Example
Result
Example
Result
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]))
Result
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
Result
Example 36
Result
Example
Example
Result
Result
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
Result
[1, 2, 3, 1, 2, 3, 1, 2, 3]
Example
Result
[[2], [2]]
[[99]]
[[99], [99]]
Example
#negative slicing
# Initialize list
Lst = [50, 70, 30, 20, 90, 10, 50]
# Display list
print(Lst[-7::1])
Result
Example 50
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]
Result
[]
Example
Result
Example
Result
Example
Result
Example
Result
Example
Result
Example
Result
[‘a’, [‘bb’, ‘dd’], ‘e’]
Example
Result
Example
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
Result
Welcometopython
Example
Result
pythonpythonpython
Example
Result
[1, 2, 3, 1, 2, 3, 1, 2, 3]
Example
Result
[[2], [2]]
[[99]]
[[99], [99]]
Example
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
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
DOI: 10.1201/9781003414322-6
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])
Function Description
cmp(tuple1, tuple2) Compares the elements of the two tuples
len(tuple) Gives the total length of the tuple
max(tuple) Returns the max value of the tuple
min(tuple) Returns min value of the tuple
tuple(sequence) Converts the list to tuple
Method Description
count() Returns the number of times a specified value occurs in a tuple
Searches the tuple for a specified value and returns the position of
index()
where it was found
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
The preceding program performs predefined methods of tuple.
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)
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
Program
t=tuple((1,2,3))
for x in t:
print(x)
t1=tuple((“this”,”is”,”to”,”test”))
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
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
The preceding program converts tuple to string.
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”)
s=tuple(s)
print(s)
Output
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
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
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
Program
s=tuple((1,2,3,4,5,6,9))
print(len(s))
print(max(s))
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
lgsmTuple = (25, 17, 33, 89, 77, 10, 64, 11, 55)
print(“Tuple Items = ”, lgsmTuple)
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
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
[‘to’, ’test’, (1, 2, 3), (‘true’, ’false’), ’1’]
Unpacking-2
this
[‘is’, ’to’, ’test’, (1, 2, 3), (‘true’, ’false’)]
1
Unpacking-3
[‘this’, ’is’, ’to’, ’test’, (1, 2, 3)]
(‘true’, ’false’)
1
Tuplename[index]
Syntax for tuple slicing
Tuplename[start:stop:step]
Program
Output
b
d
(‘a’, ’b’)
(‘b’, ’c’)
(‘a’, ’c’)
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)
The preceding program performs the tuple index and slicing on numbers.
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)
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
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
DOI: 10.1201/9781003414322-7
7.1 INTRODUCTION
A set is a collection that is unordered and unindexed. In Python, sets are
written with curly brackets.
setname={“item1”,”item2”, …}
Setname=set((={“item1”,”item2”, …))
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)
Program: giving duplicate values to the set
s={1,2,3,2,“this”,“is”,“to”,“test”,“test”}
print(s)
s1=set((1,2,3,2,“this”,“is”,“to”,“test”,“test”))
print(s1)
s2={(1,2,3,2),(“this”,“is”,“to”,“test”,“test”)}
Print(s2)
Output
{1, 2, 3, ‘to’, ‘test’, ‘this’, ‘is’}
{1, 2, 3, ‘to’, ‘test’, ‘this’, ‘is’}
{(‘this’, ‘is’, ‘to’, ‘test’, ‘test’), (1, 2, 3, 2)}
Output
{‘test’, ‘is’, ‘to’, ‘this’}
test
is
to
this
7.3 ADDING ELEMENTS TO THE SET
To add the elements in the set, there is a predefined method called the add
(). To add multiple items to the set, there is a predefined method called the
update ().
Output
{‘test’, ‘is’, ‘to’, ‘this’}
{‘this’, ‘to’, ‘pyhton’, ‘test’, ‘is’}
{‘this’, ‘to’, ‘pyhton’, ‘set’, ‘test’, ‘is’}
{‘this’, ‘example’, ‘to’, ‘pyhton’, ‘set’, ‘test’, ‘is’}
Output
{‘test’, ‘is’, ‘to’, ‘this’}
{‘python’, ‘this’, ‘example’, ‘to’, ‘set’, ‘test’, ‘is’}
7.4 REMOVE AN ELEMENT FROM THE SET
To remove an element from the set, there are two predefined methods called
the remove (), discard (). There is another predefined method called the pop
() to remove the topmost element from the set. There is no guarantee that by
using pop () which element from the set will be removed.
Output
{‘test’, ‘is’, ‘to’, ‘this’}
{‘is’, ‘to’, ‘this’}
{‘is’, ‘to’}
{‘to’}
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’}
Operation Description
in Returns true if the element is found in the set; otherwise false
Returns true if the element is not found in the set; otherwise
not in
false
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’]
Method Description
Adds an element to the set. Set maintains only unique
add() elements; if the newly added element already exists in the set,
then it does not add that element.
clear() Removes all elements from the set.
copy() Copies the set.
Returns the first set elements only that were not exist in the
difference()
second set.
intersection() Returns the elements that were common in the given sets.
pop() Removes the random element from the set.
symmetric Returns the distinct elements that were found in the given
difference() sets.
Method Description
union() Combines the given sets.
Updates the set by adding distinct elements from the passed
update()
ones.
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}
symmetric_difference s-s1: {1, ’1’}
symmetric_difference s1-s: {1, ’1’}
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}
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
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
Output
frozenset({‘test’, ‘is’, ‘to’, ‘this’})
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})
Method Description
Returns the first set elements only that were not existing
difference()
in the second set
Method Description
Returns the elements that were common in the given
intersection()
sets
symmetric_ Returns the distinct elements that were found in the
difference() given sets
union() Combines the given sets
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’})
Program 19: Relational operators on frozen sets
s=frozenset((l,2,3,4))
s1=frozenset((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: frozenset({l,2,3,4})
s1: frozenset({1,2,3})
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()
difference s1-(s, s2, s3): frozenset({1, ’1’})
difference s2-(s1, s, s3): {(1, 2, 3, 2), (‘this’, ‘is’, ‘to’,
‘test’, ‘test’)}
difference s3-(s1, s2, s): frozenset({10.34567, (1, 2, 3),
‘this is to test’, (‘pyhton’, ‘set’, ‘example’)})
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
DOI: 10.1201/9781003414322-8
Note: Each key must be unique. It may be any type, and keys are
case sensitive.
Empty dictionaries are constructed by an empty pair of curly braces, that is,
{}.
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.
Syntax
dictionaryname[key]
Program
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
Output
Exists
The preceding program checks the existence of the key using the
membership operators.
Program
Output
True
True
Program
Output
Output
Program
Output
Program
Output
print(marks)
Output
Program
Output
86
{‘java’: 80, ’python’: 90}
Program
Program
Output
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
d={‘id’:1,’name’:’usharani’,’age’:33,’id’:5}
print(d[‘id’])
Output
Function Description
cmp(d1,d2) Compares both elements of both dictionary
len(d) Total length of the dictionary(d)
Str(d) String representation of dictionary
Type(variable) Return type of dictionary
Method Description
Dict.clear Removes all elements of dictionary
Dict.copy Shallow copy of dictionary
Creates a new dictionary with keys from
Dict.fromKeys() seq and values set to value
Dict.get(key,default=None) For key key, returns value or default if
key not in dictionary
Returns true if key in dictionary dict,
Dict.has_key(key)
false otherwise
Method Description
Returns a list of dicts (key, value) tuple
pairs
Dict.items()
Returns list of dictionary dict’s keys
Dict.keys()
Similar to get() but will set
Dict.setdefault(key,default=None)
dict[key]=default if key is not already in
dict
Adds dictionary dict2’s key values pairs
Dict.update(d2)
to dict
Dict.values() Returns list of dictionary dicts values
d={1:”this”,2:”is”,3:”to”,4:”test”}
print(d)
d1=dict(a=“this”,b=“is”,c=“to”,d=“test”)
print(d1)
Output
k=(‘k1’,’k2’,’k3’)
v=(10,20,30)
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)
Output
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’)])
The preceding program prints the dictionary keys and values separately.
d={3:”to”,2:”is”,1: ”this”,4:”test”}
print(“origianal”,d)
print(“sorting keys”,sorted(d.keys()))
print(“sorted dictionary:”,sorted(d.items()))
print(“sorted reverse dictionary:”,
sorted(d.items(),reverse=True))
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
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
Program
Output
{‘d’: {‘a’: ’this’, ’b’: ’is’, ’c’: ’to’, ’d’: ’test’}, ’d1’:
{‘a1’: ’this’, ’b1’: ’is’, ’c1’: ’to’, ’d1’: ’test’}}
Output
Program
Output
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
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
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
{2: ’is’}
Program
d={1:”this”,2:”is”,3:”to”,4:”test”}
print(d)
d.clear()
print(d)
Output
Program
Output
{‘p’: ’P’, ’y’: ’Y’, ’t’: ’T’, ’h’: ’H’, ’o’: ’O’, ’n’: ’N’}
Program
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
Output
The preceding program accesses even elements from the dictionary using
dictionary comprehension.
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
Program
d={1:’a’,1.5:’b’,True:’c’,(0,1):’d’}
print(d)
Output
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
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
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
DOI: 10.1201/9781003414322-9
Syntax
To import all names from a module into the current name space, use
import *.
Syntax
Namespace
A namespace is a space.
Writing sample1.py
[55] import sample1
sample1.fun1()
Program
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
Program
Writing mymodule1.py
from mymodule1 import *
s=testing1(10,20)
s.display()
constructor
i= 10
j= 20
Program
Writing mymodule1.py
constructor
i= 10
j= 20
in main prg i= 10
Program
Writing mymodule2.py
Program
Writing mymodule3.py
sample constructor
i= 10
j= 20
in main prg i= 100
test constructor
string: python
in main prg i= module example
%%writefile mymodule5.py
class samplee:
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 testt:
def __init__(self,s):
print(“test constructor”)
self.s=s
def put(self):
print(“string:”,self.s)
def fun1():
print(“parameterless function”)
def square(n):
print(“square”,n*n)
def cube(n):
print(“cube”,n*n*n)
t.s=“usharani”
print(“in main prg i=”,t.s)
mymodule5.fun1()
mymodule5.square(5)
mymodule5.cube(5)
Output
9.3 PACKAGE
A package in Python is a collection of one or more relevant modules.
Program
Mounted at /content/GDrive/
[13] import os
print (os.listdir(‘GDrive’))
[16] os.chdir(‘GDrive/MyDrive/pythonpackage’)
print(“this is p1.py
function”)
Writing p1.py
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
created in the file p22
import p22
from p22 import *
p22.fun2()
Program
Mounted at /content/GDrive/
[13] import os
print (os.listdir(‘GDrive’))
[16] os.chdir(‘GDrive/MyDrive/pythonpackage’)
%%writefile p3.py
class sample:
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)
%%writefile p4.py
class test:
def __init__(self,s):
print(“test constructor”)
self.s=s
def put(self):
print(“string:”,self.s)
import p3
from p3 import *
import p4
from p4 import *
s=sample(10,20)
s.display()
s.i=100
s.j=s.i*3
print(“in main prg i=,j=”,s.i,s.j)
t=test(“python”)
t.put()
t.s=“package example”
print(“in main prg s=”,t.s)
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
package 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
saving p5.py to p5 (22).py
testing outside colab function
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
DOI: 10.1201/9781003414322-10
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.
5. The statements in the function are indented.
6. The last statement of the function is the return statement. This
statement exists the function and this statement is the optional.
7. Function ends where the nesting or indent ends.
Syntax of Function
Example Program
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)
<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
variable 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.
Program
Output
sum= 30
Program
Output
sum= 60
Program
def test():
global 1
print(1)
1=[2,3,4,5]
1=[0,1]
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
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
Note: When mixing both the keyword and the positional parameters,
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
keyword arguments.
Program
def add(a,b,c):
print(“add=“,(a+b+c))
add(c=10,20,b=30)
Output
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)
TypeError: add() got multiple values for argument ’a’
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.
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
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
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)
Output
Syntax
Program
t=lambda: None
print(t)
Output
Program
j = lambda i : i + 5
print(j(3))
Output
Program
Output
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”)
return;
print(“end of functions”)
print(“in main”)
test()
print(“end of main”)
Output
in main
inside function
end of main
In the preceding program, despite reaching the end of the program, return
to main program – unconditional return.
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
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)
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)
NameError: name ’7’ is not defined
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
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)
<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
Modifications inside the function cannot reflect outside the function, that
is, changing the parameter values does not reflect outside the function. The
scope of the variable can be extended by using the global keyword.
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):
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]
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
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
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”)
elif n == 0:
print(“The factorial of 0 is 1”)
else:
print(“The factorial of”, n, ”is”, rec(n))
Output
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
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()
3. Check the output for the following Python program:
def test():
print(“inside function”)
print(“main function”)
test()
print(“end of main”)
4. Check the output for the following program:
def test(name):
print(“welcome”,name)
name=input(“enter ur name”)
test(name)
5. Check the output for the following program:
def test(i):
print(“inside function i=“,i)
i=i+1
i=int(input(“Enter integer:”))
print(“in main i=“,i)
test(i)
print(“after function calling i=“,i)
6. Check the result for the following Python program:
def test(name,surname):
print(“name:”,name,”surname:”,surname)
test(“usharani”,”bhimavarapu”)
test(“bhimavarapu”,”usharani”)
7. Check the output for the following program:
def test():
i=10
print(i)
CHAPTER 11
DOI: 10.1201/9781003414322-11
The time module and the calendar module in Python helps to retrieve data
and time. The time module has the predefined methods to represent the time
and to process the time. The time are expressed in seconds since 00:00:00
hours January 1, 1970.
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
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
October 2020
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.
Attribute Description
time.timezone It is the offset of the local time zone from UTC in seconds.
Time.tzname It is the pair of local dependent string.
Function Description
It is the offset of local time zone to
time.altzone
UTC in seconds.
Returns the date in a readable 24-
time asctime character string.
([tupletime]) Returns the current CPU time.
time.clock() Returns the date in a readable 24-
time.ctime() character string in
terms of seconds.
time.gmtime([secs]) Returns a time tuple of UTC time.
Function Description
time.localtime([secs]) Returns the local time.
time.mktime(tupletime) Returns the time since the epoch.
Suspends the calling thread for the
time.sleep(secs) specified time in
terms of seconds.
time.strftime(fmt[,tupletime]) Returns the string format of time.
time.strptime
Returns the time in the time tuple
(str,fmt=’%a%b%d%H:
format.
%M:%S%Y’)
time.time() Returns the current time.
time.tzset() Resets the time conversion rules.
Function Description
Returns calendar for year and
calendar. calendar(year,w=2,l=1,c=6) formatted by the specified c, w and
l.
Returns the starting day of each
calendar. firstweekday()
week.
Function Description
Returns the number of leap days
calendar. leapdays(y1,y2) between
the given specified years.
Returns the calendar for specified
calendar. month (year,month,w=2,l=1)
month/
calendar. month calendar(year. month) Returns a list of weeks.
Returns the weekday of the month
and the
calendar. month range(year. month) total number of days in the
specified
month.
calendar.prcal(year,w=2,l=1,c=6) Displays the calendar.
calendar.prmonth(year,month,w=2,l=1) Displays the calendar for month.
Sets the weekday code. Default
weekday
Calendar. setfirstweekday(weekday) codes are 0 to Monday and 6 to
Sunday.
Sets the weekday code.
Returns the time in term of
Calendar. timegm(tupletime)
seconds.
Returns the weekday code for the
Calendar. weekday(year, month,day)
specified date.
Checks whether the specified year
calendar. isleap(year) is leap
or not.
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’)
The cited example returns all the time zones.
Example
import pytz
import datetime
from datetime import datetime
u = pytz.uzc
k = pytz.timezone(‘Asia/Kolkata’)
print(‘UTC Time =’, datetime.now(tz=u))
print(‘Asia Time =‘, datetime.now(tz=k))
Output
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))
Output
November 2020
Mo Tu We Th Fr Sa Su
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
Output
2021-09-13
Example
import calendar as c
print(c.calendar(2020,1,1,1))
Output
2020
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
2020
27 28 29 30 31 24 25 26 27 28 29 23 24 25 26 27 28 29
30 31
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
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
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
2020
30
Example
Output
day 13
month 9
year 2021
Example
Output
Weekday: 0
Example
Output
Example
Output
The cited example prints date and time using strftime formats.
Example
Output
364
<class ‘datetime.timedelta’>
Example
Output
Year 4 digits: 2021
Year 2 digits: 21
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
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
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
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
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
4 5 6 7 8 9 10
September 2021
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))
Output
September 2021
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))
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
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=” ”)
Output
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
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
The cited example retrieves the month days in the calendar for the
complete 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
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
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
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
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
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
2021
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
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
The preceding program displays the first day of the week in the
numerical form.
Example
from datetime import timedelta
t1 = timedelta(seconds = 15)
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
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
Output
2021-09-14 06:52:01.829130
Example
Output
2021-09-12 06:52:18.075289
Example
Output
-1 day, 23:59:59.999995
The preceding program performs arithmetic multiplication operation on
time delta.
Example
Output
-1 day, 23:59:59.999990
Example
Output
-1.1574074074074074e-09
Example
Output
4:48:00
Example:
Output
2 days, 0:00:00
Example
Output
23:59:59.999900
Output
-1
23:59:59.999900
Example
Output
-1 day, 23:59:59.999900
0:00:00.000100
1 day, 0:00:00
-1 day, 0:00:00
The preceding program performs unary addition and unary subtraction
operation on time delta.
Example
Output
-1 day, 23:59:59.999900
1 day, 0:00:00
Example
Output
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.
9. Write a Python program to print the five-column calendar of the
specified year.
10. Write a Python program to find whether the current year is a leap year
or not.
CHAPTER 12
Regular Expression
DOI: 10.1201/9781003414322-12
Syntax
import re
The different meta characters and different patterns are tabulated in Tables
12.1, 12.2, 12.3, and 12.4.
Modifier Description
re.l Case-insensitive matching
By following the current system locale,
re.L
interpretation of the words using the alphabetic group
Do search at the end of the line and at the
re.M
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
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
Pattern Description
re* Searches for the zero or more occurrences of the specified pattern
Searches for the one or more occurrences of the
re+
specified pattern
Searches for the zero or one occurrences of the
re?
specified pattern
Pattern Description
Searches for the n number of occurrences of the
re{n}
specified pattern
Searches for the n or more occurrences of the
re{n,}
specified pattern
Searches at least n and at most m occurrences of the specified
re{n,m}
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
Pattern Description
\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
Returns match pattern if the corresponding characters are at the
\A
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
Pattern Description
Returns match pattern if the corresponding
\b characters are at the beginning of the string or at the
end of the string
Returns match pattern if the corresponding
\B 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.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)
import re
txt = “It is still raining”
s = re.search(“\s”, txt)
print(“First white-space at:”, s.start())
Output
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).
Example
import re
str = “This is to test the regex test”
s = re.search(“test”, str)
print(s)
print(type(s))
Output
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
a = [“this”, “is”, “to”, “test”]
for s in a:
x = re.match(“(g\w+)\W(g\w+)”, s)
if x:
print((x.groups()))
Output
Modifier Description
re.I Case-insensitive matching
By following the current system locale, interpretation of the
re.L
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
Regular expression patterns
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
Searches at least n and at most m occurrences of the specified
re{n,m}
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
Pattern Description
Returns match pattern if the corresponding characters are at the
\A
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
Returns match pattern if the corresponding characters are at the
\b
beginning of the string or at the end of the string.
Returns match pattern if the corresponding characters are present
\B
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
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)
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
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”))
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
Example
import re
s = ‘five:5 twenty one:21 ten:10’
p = ‘\d+’
r=re.split(p, s, 1)
print(r)
Output
Example
Output
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’))
12.8 THE SUB () FUNCTION
The Python re.sub () function replaces the occurrences of the specified
pattern with the target pattern in the given string.
Syntax
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’]
import re
print(re.escape(“this is to test”))
print(re.escape(“this is to test \t ^test”))
Output
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
abs function, 34
anonymous functions, 199
append method, 93
arguments, 193
ASCII character code, 84
assert, 4
assignments multiple, 12
assignment statements, 11, 22
attributes, 175
dictionaries, 158
lists, 91
sets, 143
strings, 75
tuples, 127
call-by-reference, 171
comment, 6
comparison operator, 20
concatenation operator, 71
continue statement, 58
curly braces
dictionaries, 157
sets, 143
data type, 11
def statement, 7
del, 79
dictionary, 140
dictionary comprehensions, 169
elif, 41
else, 36
exec, 4
expression evaluation, 28
false, 3
findall method, 249
floating point numbers, 15
floor division, 20
flush method, 4
function, 168
garbage collection, 2
get method, 162
global variable, 11
if, 35
if else statement, 36
immutability, 127
import statement, 155
indentation, 7
index method, 129
index values, 78
infinite loops, 67
input (), 25
insert method, 93
int, 11
module, 155
modulus operator, 17
multiplication, 17
multiprocessing, 325
multithreading, 326
namespace, 155
negative index, 67
nested conditionals, 45
none variable, 10
object, 230
object-oriented language, 1
operator, 16
range function, 15
reduce function, 116
remove method, 146
replace method, 85
repr function, 238
re (regular expression) module, 241
return statement, 200
reverse method, 93
round function, 34
rstrip method, 85
unary operator, 16
unpacking, 124
V
variable, 8
while else, 64
while loop, 24