USIT 301 Python Programming
USIT 301 Python Programming
(IT)
SEMESTER - III (CBCS)
PYTHON PROGRAMMING
SUBJECT CODE : USIT301
© UNIVERSITY OF MUMBAI
Prof. Suhas Pednekar
Vice Chancellor
University of Mumbai, Mumbai.
Prof. Ravindra D. Kulkarni Prof. Prakash Mahanwar
Pro Vice-Chancellor, Director
University of Mumbai. IDOL, University of Mumbai.
UNIT I
1. Introduction 01
2. Variables And Expression 13
3. Conditional Statements, Looping, Control Statements 26
UNIT II
4 Functions 42
5. Strings 59
UNIT III
6. List 75
7. Tuples And Dictionaries 88
8. Files And Exceptions 112
UNIT IV
9. Regular Expression 125
10 . Classes And Objects 134
11. Multithreaded Programming 147
12. Module 157
UNIT V
13. Creating The GUI Form And Adding Widgets 169
14. Layout Management & Look & Feel Customization 192
15. Storing Data In Our Mysql Database Via Our GUI 213
*****
Syllabus
M. Sc (Information Technology) Semester – I
Course Name: Python Programming Course Code: USIT301
Periods per week (1 Period is 50 minutes)5
Credits
2
Hours Marks
Evaluation System Theory
TheoryExamination
Examination Internal
2½ 75
Theory Internal - 25
1.0 OBJECTIVES
1
We don’t need to use data types to declare variable because it
is dynamically typed so we can write a=10 to declare an integer
value in a variable.
Python makes the development and debugging fast because there is
no compilation step included in python development.
1.2 HISTORY
1.3 FEATURES
1. Easy to Code:
Python is a very developer-friendly language which means that
anyone and everyone can learn to code it in a couple of hours or
days.
As compared to other object-oriented programming languages like
Java, C, C++, and C#, Python is one of the easiest to learn.
4. Object-Oriented Approach:
One of the key aspects of Python is its object-oriented
approach. This basically means that Python recognizes the
concept of class and object encapsulation thus allowing
programs to be efficient in the long run.
5. Highly Portable:
Suppose you are running Python on Windows and you need to shift
the same to either a Mac or a Linux system, then you can easily
achieve the same in Python without having to worry about
changing the code.
This is not possible in other programming languages, thus making
Python one of the most portable languages available in the
industry.
6. Highly Dynamic
Python is one of the most dynamic languages available in the
industry today. What this basically means is that the type of a
variable is decided at the run time and not in advance.
Due to the presence of this feature, we do not need to specify the
type of the variable during coding, thus saving time and increasing
efficiency.
3
Before starting working with Python, a specific path is to set to set path
follow the steps:
Right click on My Computer--> Properties -->Advanced System
setting -->Environment Variable -->New
In Variable name write path and in Variable value copy path up to C://
Python (i.e., path where Python is installed). Click Ok ->Ok.
Example:
Here is the simple code of Python given in the Python file
demo.py. It contains only single line code of Python which prints
the text “Hello World!” on execution.
So, how you can execute the Python program using the command
prompt. To see this, you have to first open the command
prompt using the ‘window+r’ keyboard shortcut. Now, type the
word ‘cmd’ to open the command prompt.
This opens the command prompt with the screen as given
below. Change the directory location to the location where you
have just saved your Python .py extension file.
We can use the cmd command ‘cd’ to change the directory
location. Use ‘cd..’ to come out of directory and “cd” to come
inside of the directory. Get the file location where you saved your
Python file.
4
2) Interactive Mode to Execute Python Program:
To execute the code directly in the interactive mode. You have to
open the interactive mode. Press the window button and type the
text “Python”. Click the “Python 3.7(32 bit) Desktop app” as given
below to open the interactive mode of Python.
You can type the Python code directly in the Python interactive
mode. Here, in the image below contains the print program of
Python.
Press the enter button to execute the print code of Python. The
output gives the text “Hello World!” after you press the enter
button.
Type any code of Python you want to execute and run directly on
interactive mode.
5
3) Using IDLE (Python GUI) to Execute Python Program:
Another useful method of executing the Python code. Use the
Python IDLE GUI Shell to execute the Python program on
Windows system.
Open the Python IDLE shell by pressing the window button of the
keyboard. Type “Python” and click the “IDLE (Python 3.7 32
bit)” to open the Python shell.
Create a Python file with .py extension and open it with the Python
shell. The file looks like the image given below.
6
It contains the simple Python code which prints the text “Hello
World!”. In order to execute the Python code, you have to open the
‘run’ menu and press the ‘Run Module’ option.
A new shell window will open which contains the output of the
Python code. Create your own file and execute the Python code
using this simple method using Python IDLE.
1.6 DEBUGGING
7
We can Change the flow of execution by using jump, continue
statements.
Example:
age=16
if age>18:
print ("you can vote”) # syntax error because of not using indentation
else
print ("you cannot vote”) #syntax error because of not using
indentation
8
1.6.4 Experimental Debugging:
One of the most important skills you will acquire is debugging.
Although it can be frustrating, debugging is one of the most
intellectually rich, challenging, and interesting parts of
programming.
Debugging is also like an experimental science. Once you have an
idea about what is going wrong, you modify your program and try
again.
For some people, programming and debugging are the same thing.
That is, programming is the process of gradually debugging a
program until it does what you want.
The idea is that you should start with a program that does
something and make small modifications, debugging them as you
go, so that you always have a working program.
Brackets [ ]:
Brackets are used to define mutable data types such as list or list
comprehensions.
9
Example:
To define a list with name as L1 with three elements 10,20 and 30
>>> L1 = [10,20,30]
>>> L1
[10,20,30]
Example:
Lookup the first characters of string
str>>>’mumbai’
>>> str [0]
‘m’
Example: To slice a string
>>> str [1:4]
‘umb’
Braces {}
Curly braces are used in python to define set or dictionary.
Example:
Create a set with three elements 10,20,30.
>>> s1 = {10,20,30}
>>> type(s1)
<class ‘set’>
Example:
Create a dictionary with two elements with keys, ‘rollno’ and ‘name’
>>> d1= {‘rollno’:101, ‘name’:’ Vivek’}
>>> type(d1)
<class ‘dict’>
1.9 SUMMARY
1.10 REFERENCES
www.journaldev.com
www.edureka.com
www.tutorialdeep.com
11
www.xspdf.com
Think Python by Allen Downey 1st edition.
Python Programming for Beginners By Prof. Rahul E. Borate, Dr.
Sunil Khilari, Prof. Rahul S. Navale.
*****
12
2
VARIABLES AND EXPRESSION
Unit Structure
2.0 Objectives
2.1 Introduction
2.2 Values and Types
2.2.1 Variables
2.2.2 Variable Names and Keywords
2.3 Type conversion
2.3.1 Implicit Type Conversion
2.3.2 Explicit Type Conversion
2.4 Operators and Operands
2.5 Expressions
2.6 Interactive Mode and Script Mode
2.7 Order of Operations
2.8 Summary
2.9 References
2.10 Unit End Exercise
2.0 OBJECTIVES
2.1 INTRODUCTION
13
Python is case sensitive, so myVariable is not the same
as Myvariable which in turn is not the same as MyVariable.
With some exceptions, however, the programmer should avoid
assigning names that differ only by case since human readers can
overlook such differences.
A value is one of the basic things a program works with, like a letter or
a number. The values we have seen so far are 1, 2, and 'Hello, World!'.
These values belong to different types: 2 is an integer, and 'Hello,
World!' is a string, so-called because it contains a “string” of letters.
Youcan identify strings because they are enclosed in quotation marks.
If you are not sure what type a value has, the interpreter can tell you.
>>>type ('Hello, World!')
<type ‘str’>
>>> type (17)
<type ‘int’>
Not surprisingly, strings belong to the type str and integers belong to
the type int. Less obviously, numbers with a decimal point belong to a
type called float, because these numbers are represented in a format
called floating-point.
>>> type (3.2)
<type ‘float’>
What about values like '17' and '3.2'? They look like numbers, but they
are in quotation marks like strings.
>>> type (‘17’)
<type ‘str’>
>>> type (‘3.2’)
<type ‘str’>
They are strings.
2.2.1 Variables:
One of the most powerful features of a programming language is the
ability to manipulate variables. A variable is a name that refers to a
value.
An assignment statement creates new variables and gives them values:
>>> message = ‘Welcome to University of Mumbai’
>>> n = 17
>>> pi = 3.1415926535897932
The above example makes three assignments. The first assigns a string
to a new variable named message, the second gives the integer 17 to n,
the third assigns the (approximate) value of π to pi.
14
A common way to represent variables on paper is to write the name
with an arrow pointing to the variable’s value.
>>> type(message)
<type ‘str’>
>>> type(n)
<type ‘int’>
>>> type(pi)
<type ‘float’>
15
Here is a list of the Python keywords. Enter any keyword to get more
help.
False class from or
None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not
You might want to keep this list handy. If the interpreter complains
about one of your variable names and you don’t know why, see if it is
on this list.
The process of converting the value of one data type (integer, string, float,
etc.) to another data type is called type conversion. Python has two types
of type conversion.
Syntax:
<required_datatype>(expression)
17
Example 3: Addition of string and integer using explicit conversion
num_int = 123
num_str = "456"
Example:
4+5=9
Here 4 and 5 are Operands and (+), (=) signs are the operators.
They produce the output 9
Arithmetic Operators:
Operators Description
// Perform Floor division (gives integer value after division)
+ To perform addition
- To perform subtraction
* To perform multiplication
/ To perform division
% To return remainder after division (Modulus)
** Perform exponent (raise to power)
Relational Operators:
Operators Description
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to
19
Relational Operators Examples:
>>> 10<20
True
>>> 10>20
False
>>> 10<=10
True
>>> 20>=15
True
>>> 5==6
False
>>>5!=6
True
Logical Operators:
Operators Description
and Logical AND (When both conditions are true output will
be true)
or Logical OR (If any one condition is true output will be
true
not Logical NOT (Compliment the condition i.e., reverse)
Membership Operators:
Operators Description
20
Membership Operators Examples:
a=10
b=20
list= [10,20,30,40,50]
if (a in list):
print (“a is in given list”)
else:
print (“a is not in given list”)
if (b not in list):
print (“b is not given in list”)
else:
print (“b is given in list”)
Output:
>>>
a is in given list
b is given in list
Identity operators:
Operators Description
is Returns true if identity of two operands are same, else
false
is not Returns true if identity of two operands are not same,
else false.
21
2.5 EXPRESSIONS
The first line assigns a value to miles, but it has no visible effect. The
second line is an expression, so the interpreter evaluates it and displays the
result. So we learn that a marathon is about 42 kilometers.
But if you type the same code into a script and run it, you get no
output at all.
In script mode an expression, all by itself, has no visible effect. Python
actually evaluates the expression, but it doesn’t display the value
unless you tell it to:
miles = 26.2
print (miles * 1.61)
This behavior can be confusing at first.
A script usually contains a sequence of statements. If there is more
than one statement, the results appear one at a time as the statements
execute.
For example
22
print 1
x=2
print x
produces the output
1
2
The assignment statement produces no output.
2.8 SUMMARY
For each of the following expressions, write the value of the expression
and the type (of the value of
the expression).
1. width/2
2. width/2.0
3. height/3
4. 1 + 2 * 5
5. delimiter * 5
24
Use the Python interpreter to check your answers
2.9 REFERENCES
*****
25
3
CONDITIONAL STATEMENTS,
LOOPING, CONTROL STATEMENTS
Unit Structure
3.0 Objectives
3.1 Introduction
3.2 Conditional Statements:
3.2.1 if statement
3.2.2 if-else,
3.2.3 if...elif...else
3.2.4 nested if –else
3.3 Looping Statements:
3.3.1 for loop
3.3.2 while loop
3.3.3 nested loops
3.4 Control statements:
3.4.1 Terminating loops
3.4.2 skipping specific conditions
3.5 Summary
3.6 References
3.7 Unit End Exercise
3.0 OBJECTIVES
3.1 INTRODUCTION
26
The boolean expression after if is called the condition. If it is true,
then the indented statement gets executed. If not, nothing happens.
27
You can chain together only simple statements, like assignments,
prints, and function calls.
3.2.1 if statement:
Syntax
if test expression:
statement(s)
Here, the program evaluates the test expression and will execute
statement(s) only if the test expression is True.
If the test expression is False, the statement(s) is not executed.
In Python, the body of the if statement is indicated by the
indentation. The body starts with an indentation and the first
unindented line marks the end.
Python interprets non-zero values as True. None and 0 are
interpreted as False.
num = -1
if num > 0:
print (num, "is a positive number.")
print ("This is also always printed.")
28
3.2.2 if-else statement:
Syntax
if test expression:
Body of if
else:
Body of else
The if...else statement evaluates test expression and will execute
the body of if only when the test condition is True.
If the condition is False, the body of else is executed. Indentation is
used to separate the blocks.
Example of if...else
# Program checks if the number is positive or negative
# And displays an appropriate message
num = 3
# Try these two variations as well.
# num = -5
# num = 0
if num >= 0:
print ("Positive or Zero")
else:
print ("Negative number")
Output:
Positive or Zero
In the above example, when num is equal to 3, the test expression
is true and the body of if is executed and the body of else is
skipped.
If num is equal to -5, the test expression is false and the body
of else is executed and the body of if is skipped.
If num is equal to 0, the test expression is true and body of if is
executed and body of else is skipped.
Example of if...elif...else:
'''In this program,
we check if the number is positive or
negative or zero and
display an appropriate message'''
num = 3.4
# Try these two variations as well:
# num = 0
# num = -4.5
if num > 0:
print ("Positive number")
elif num == 0:
print("Zero")
else:
print ("Negative number")
30
an appropriate message
This time we use nested if statement'''
num = float (input ("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print ("Positive number")
else:
print ("Negative number")
Output1:
Enter a number: 5
Positive number
Output2:
Enter a number: -1
Negative number
Output3:
Enter a number: 0
Zero
31
Here, val is the variable that takes the value of the item inside the
sequence on each iteration.
Loop continues until we reach the last item in the sequence. The
body of for loop is separated from the rest of the code using
indentation.
Example:
print(range(10))
print(list(range(10)))
print (list (range (2, 8)))
print (list (range (2, 20, 3)))
Output:
range (0, 10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6, 7]
[2, 5, 8, 11, 14, 17]
32
We can use the range () function in for loops to iterate through a
sequence of numbers. It can be combined with the len () function to
iterate through a sequence using indexing. Here is an example.
# Program to iterate through a list using indexing
city = ['pune', 'mumbai', 'delhi']
# iterate over the list using index
for i in range(len(city)):
print ("I like", city[i])
Output:
I like pune
I like mumbai
I like delhi
Example:
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
When you run the program, the output will be:
0
1
5
No items left.
Here, the for loop prints items of the list until the loop exhausts.
When the for-loop exhausts, it executes the block of code in
the else and prints No items left.
This for...else statement can be used with the break keyword to run
the else block only when the break keyword was not executed.
Example:
# program to display student's marks from record
student_name = 'Soyuj'
marks = {'Ram': 90, 'Shayam': 55, 'Sujit': 77}
33
for student in marks:
if student == student_name:
print(marks[student])
break
else:
print ('No entry with that name found.')
Output:
No entry with that name found.
Here, we use a counter variable to print the string Inside loop three
times.
On the fourth iteration, the condition in while becomes False.
Hence, the else part is executed.
Syntax
for iterator in iterable:
for iterator2 in iterable2:
statement(s) of inside for loop
statement(s) of outside for loop
In this first for loop will initiate the iteration and later
second for loop will start its first iteration and till second for loop
complete its all iterations the control will not be given to
first for loop and statements of inside for loop will be executed.
Once all iterations of inside for loop are completed then statements
of outside for loop will be executed and next iteration from
first for loop will begin.
Output:
1 2 3 4 5 6 7 8 9 10 Table of 1
2 4 6 8 10 12 14 16 18 20 Table of 2
3 6 9 12 15 18 21 24 27 30 Table of 3
4 8 12 16 20 24 28 32 36 40 Table of 4
5 10 15 20 25 30 35 40 45 50 Table of 5
6 12 18 24 30 36 42 48 54 60 Table of 6
7 14 21 28 35 42 49 56 63 70 Table of 7
8 16 24 32 40 48 56 64 72 80 Table of 8
36
9 18 27 36 45 54 63 72 81 90 Table of 9
10 20 30 40 50 60 70 80 90 100 Table of 10
Output:
*
**
***
****
*****
******
*******
********
*********
In this first while loop will initiate the iteration and later
second while loop will start its first iteration and till
second while loop complete its all iterations the control will not be
given to first while loop and statements of inside while loop will be
executed.
Once all iterations of inside while loop are completed than
statements of outside while loop will be executed and next iteration
from first while loop will begin.
It is also possible that if first condition in while loop expression is
False then second while loop will never be executed.
Output:
1
22
333
4444
55555
666666
7777777
88888888
999999999
Output:
10
99
888
7777
66666
555555
4444444
33333333
222222222
38
3.4 CONTROL STATEMENTS:
Example:
for num in range (10):
if num > 5:
print ("stop processing.")
break
print(num)
Output:
0
1
2
3
4
5
stop processing.
39
Example of a continue statement:
for num in range (3, 8):
if num == 5:
continue
else:
print(num)
Output:
3
4
6
7
3.5 SUMMARY
3.7 REFERENCES
*****
41
UNIT II
4
FUNCTIONS
Unit Structure
4.0 Objectives
4.1 Introduction
4.2 Function Calls
4.3 Type Conversion Functions
4.4 Math Functions
4.5 Adding New Functions
4.6 Definitions and Uses
4.6.1 Flow of Execution
4.6.2 Parameters and Arguments
4.6.3 Variables and Parameters Are Local
4.6.4 Stack Diagrams
4.7 Fruitful Functions and Void Functions
4.8 Why Functions?
4.9 Importing with from, Return Values, Incremental Development
4.10 Boolean Functions
4.11 More Recursion, Leap of Faith, Checking Types
4.12 Summary
4.13 References
4.14 Unit End Exercise
4.0 OBJECTIVES
4.1 INTRODUCTION
Syntax of Function
def function_name(parameters):
"""docstring"""
statement(s)
Example:
def greeting(name):
"""
This function greets to
the person passed in as
43
a parameter
"""
print ("Hello, " + name + ". Good morning!")
Output:
Data type of num_int: <class 'int'>
Data type of num_str before Type Casting: <class 'str'>
Data type of num_str after Type Casting: <class 'int'>
Sum of num_int and num_str: 579
Data type of the sum: <class 'int'>
Pulling together the code fragments from the previous section, the
whole program looks like this:
def print_lyrics ():
print ("I'm a lumberjack, and I'm okay.")
print ("I sleep all night and I work all day.")
repeat_lyrics ()
In order to ensure that a function is defined before its first use, you
have to know the order in which statements are executed, which is
called the flow of execution.
Execution always begins at the first statement of the program.
Statements are executed one at a time, in order from top to bottom.
Function definitions do not alter the flow of execution of the
program, but remember that statements inside the function are not
executed until the function is called.
A function call is like a detour in the flow of execution. Instead of
going to the next statement, the flow jumps to the body of the
function, executes all the statements there, and then comes back to
pick up where it left off.
When you read a program, you don’t always want to read from top
to bottom. Sometimes it makes more sense if you follow the flow
of execution.
49
Inside the function, the arguments are assigned to variables
called parameters. Here is an example of a user-defined function
that takes an argument.
def print_twice(bruce):
print(bruce)
print(bruce)
This function assigns the argument to a parameter named bruce.
When the function is called, it prints the value of the parameter
twice.
>>> print_twice('Spam')
Spam
Spam
>>> print_twice (17)
17
17
>>> print_twice(math.pi)
3.14159265359
3.14159265359
For example
def cat_twice(part1, part2):
cat = part1 + part2
print_twice(cat)
50
This function takes two arguments, concatenates them, and prints the
result twice. Here is an example that uses it:
>>> line1 = 'Bing tiddle '
>>> line2 = 'tiddle bang.'
>>> cat_twice(line1, line2)
Bing tiddle tiddle bang.
Bing tiddle tiddle bang.
51
Each parameter refers to the same value as its corresponding
argument. So, part1 has the same value as line1, part2 has the same
value as line2, and bruce has the same value as cat.
If an error occurs during a function call, Python prints the name of
the function, and the name of the function that called it, and the
name of the function that called that, all the way back to __main__.
52
4.8 WHY FUNCTIONS?
53
>>> cos(pi)
-1.0
The advantage of importing everything from the math module is
that your code can be more concise.
The disadvantage is that there might be conflicts between names
defined in different modules, or between a name from a module
and one of your variables.
55
Following is an example of a recursive function to find the factorial
of an integer.
Factorial of a number is the product of all the integers from 1 to that
number. For example, the factorial of 6 (denoted as 6!)
is 1*2*3*4*5*6 = 720.
Example of a recursive function
def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
Output:
The factorial of 3 is 6
56
3 * 2 * factorial (1) # 3rd call with 1
3*2*1 # return from 3rd call as number=1
3*2 # return from 2nd call
6 # return from 1st call
4.12 SUMMARY
1. Python provides a built-in function called len that returns the length
of a string, so the value of len('allen') is 5.
Write a function named right_justify that takes a string named s as
a parameter and prints the string with enough leading spaces so that
the last letter of the string is in column 70 of the display.
>>> right_justify('allen')
allen
2. Write a Python function to sum all the numbers in a list. Go to the
editor
Sample List : (8, 2, 3, 0, 7)
Expected Output : 20
3. Write a Python program to reverse a string
Sample String : "1234abcd"
Expected Output : "dcba4321"
4. Write a Python function to calculate the factorial of a number (a
non-negative integer). The function accepts the number as an
argument.
5. Write a Python program to print the even numbers from a given
list.
Sample List: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Expected Result: [2, 4, 6, 8]
57
4.13 REFERENCES
https://www.tutorialsteacher.com/python/math-module
https://greenteapress.com/thinkpython/html/thinkpython004.html
https://beginnersbook.com/
https://www.programiz.com/python-programming/recursion
www.journaldev.com
www.edureka.com
www.tutorialdeep.com
www.xspdf.com
Think Python by Allen Downey 1st edition.
*****
58
5
STRINGS
Unit Structure
5.1 A String is a Sequence
5.2 Traversal with a for Loop
5.3 String Slices
5.4 Strings Are Immutable
5.5 Searching
5.6 Looping and Counting
5.7 String Methods
5.8 The in Operator
5.9 String Comparison
5.10 String Operations
5.11 Summary
5.12 Questions
5.13 References
5.0 OBJECTIVES
>>>food = 'roti'
>>>letter = food[1]
59
in brackets is called an index. The index indicates which character in the
sequence you required.
Example.
‘I want to read book’. This is a string, It has been surrounded in single
quotes.
You can also surround them with triple quotes (groups of 3 single quotes
or double quotes).
“””I want to read book’”””
”’ I want to read book’”’
Or using backslashes.
>> ‘Thank\
Good Morning Sir !’
‘ThanksGood Morning Sir!’
You cannot start a string with a single quote and end it with a double
quote..
But if you surround a string with single quotes and also want to use single
quotes as part of the string, you have to escape it with a backslash (\).
‘Send message to Madam\’s son ’
You can also do this with double-quotes. If you want to ignore escape
sequences, you can create a raw string by using an ‘r’ or ‘R’ prefix with
the string.
>>> str(567)
Output:
‘567’
>>> str('Shri')
Output:
‘Shri’
We have previously seen that the for statement can iterate over the
items of a sequence (a list of names in the case below).
Recall that the loop variable takes on each value in the sequence of
names. The body is performed once for each name. The same was true for
the sequence of integers created by the range function.
Since a string is simply a sequence of characters, the for loop iterates over
each character automatically.
for achar in "Go Spot Go":
print(achar)
61
The loop variable achar is automatically reassigned each character
in the string “Go Spot Go”. We will refer to this type of sequence iteration
as iteration by item. Note that it is only possible to process the characters
one at a time from left to right.
s = "python rocks"
for ch in s:
print("HELLO")
Ans - Yes, there are 12 characters, including the blank.
s = "python rocks"
for ch in s[3:8]:
print("HELLO")
Ans - Yes, The blank is part of the sequence returned by slice
The slicing starts with the start_pos index (included) and ends at
end_pos index (excluded). The step parameter is used to specify the steps
to take from start to end index.
Python String slicing always follows this rule: s[:i] + s[i:] == s for any
index ‘i’.
s = 'HelloWorld'
print(s[:])
print(s[::])
62
Output:
HelloWorld
HelloWorld
Note that since none of the slicing parameters were provided, the substring
is equal to the original string.
Output:
Hello
Llo
Note that index value starts from 0, so start_pos 2 refers to the third
character in the string.
We can reverse a string using slicing by providing the step value as -1.
s = 'HelloWorld'
reverse_str = s[::-1]
print(reverse_str)
Output:
dlroWolleH
Let’s look at some other examples of using steps and negative index
values.
s1 = s[2:8:2]
print(s1)
Output:
loo
63
Output:
lroWoll
You will get a mistake message when you need to change the substance of
the string.
Traceback (latest call last):
Record "/home/ca508dc8fa5ad71190ca982b0e3493a8.py", line 2, in
<module>
name_1[0] = 'T'
TypeError: 'str' object doesn't uphold thing task
Arrangement
One potential arrangement is to make another string object with vital
alterations:
name_1 = "Aarun"
name_2 = "T" + name_1[1:]
print("name_1 = ", name_1, "and name_2 = ", name_2)
64
name_1 = Aarun and name_2 = Tarun
To watch that they are various strings, check with the id() work:
name_1 = "Aarun"
name_2 = "T" + name_1[1:]
print("id of name_1 = ", id(name_1))
print("id of name_2 = ", id(name_2))
Output:
id of name_1 = 2342565667256
id of name_2 = 2342565669888
To see more about the idea of string permanence, think about the
accompanying code:
name_1 = "Aarun"
name_2 = "Aarun"
print("id of name_1 = ", id(name_1))
print("id of name_2 = ", id(name_2))
Output:
id of name_1 = 2342565667256
id of name_1 with new value = 2342565668656
5.5 SEARCHING
Linear Search:
Example
def linear_search(values, search_for):
search_at = 0
search_res = False
65
# Match the value with each data element
while search_at < len(values) and search_res is False:
if values[search_at] == search_for:
search_res = True
else:
search_at = search_at + 1
return search_res
l = [64, 34, 25, 12, 22, 11, 90]
print(linear_search(l, 12))
print(linear_search(l, 91))
Output:
When the above code is executed, it produces the following result −
True
False
Interpolation Search:
Example
There is a specific formula to calculate the middle position which is
indicated in the program below −
def intpolsearch(values,x ):
idx0 = 0
idxn = (len(values) - 1)
while idx0 <= idxn and x >= values[idx0] and x <= values[idxn]:
# Find the mid point
mid = idx0 +\
int(((float(idxn - idx0)/( values[idxn] - values[idx0]))
* ( x - values[idx0])))
# Compare the value at mid point with search value
if values[mid] == x:
66
return "Found "+str(x)+" at index "+str(mid)
if values[mid] < x:
idx0 = mid + 1
return "Searched element not in the list"
l = [2, 6, 11, 19, 27, 31, 45, 121]
print(intpolsearch(l, 2))
Output:
Found 2 at index 0
The following program counts the number of times the letter “r” appears
in a string:
word = 'raspberry'
count = 0
for letter in word:
if letter == 'r':
count = count + 1
print(count)
Output:
The letter t appears 3 times in "peanut butter".
Python has a set of built-in methods that you can use on strings.
Note: All string methods returns new values. They do not change the
original string.
67
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in
a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns the
position of where it was found
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified value and returns the
position of where it was found
isalpha() Returns True if all characters in the string are in the
alphabet
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower
case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isupper() Returns True if all characters in the string are upper
case
join() Joins the elements of an iterable to the end of the string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three
parts
replace() Returns a string where a specified value is replaced with
a specified value
rfind() Searches the string for a specified value and returns the
last position of where it was found
rindex() Searches the string for a specified value and returns the
last position of where it was found
rjust() Returns a right justified version of the string
rsplit() Splits the string at the specified separator, and returns a
list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a
list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
68
swapcase() Swaps cases, lower case becomes upper case and vice
versa
Note: All string methods returns new values. They do not change the
original string.
Here “x” is the element and “y” is the sequence where membership is
being checked.
We can use the “in” operator with Strings and Tuples too because they are
sequences.
>>> name='JournalDev'
>>> 'D' in name
True
>>> 'x' in name
False
>>> primes=(2,3,5,7,11)
>>> 3 in primes
True
>>> 6 in primes
False
It looks like the Python “in” operator looks for the element in the
dictionary keys.
70
3. Comparing two strings using the sorted() method:
If we wish to compare two strings and check for their equality even if the
order of characters/words is different, then we first need to use sorted()
method and then compare two strings.
str1 = input("Enter the first String: ")
str2 = input("Enter the second String: ")
if sorted(str1) == sorted(str2):
print ("First and second strings are equal.")
else:
print ("First and second strings are not the same.")
Output:
Enter the first String: Engineering Discipline
Enter the second String: Discipline Engineering
First and second strings are equal.
Output:
True
Comparision result = False
In the above example, str1 is str3 returns False because object str3 was
created differently.
Example
"Python" or 'Python'
Code
SingleQuotes ='Python in Single Quotes'
DoubleQuotes ="Python in Double Quotes"
print(SingleQuotes)
print(DoubleQuotes)
Output:
Python in Single Quotes
Python in Double Quotes
This function is used for displaying the output or result on the user screen.
Syntax
print('Text or Result') or print("Text or Result')
Indexing in String
It returns a particular character from the given string.
Syntax
getChar = a[index]
message = "Hello, Python!"
If I want to fetch the characters of the 7th index from the given string.
Syntax
print(string[index])
Code
print(message[7])
72
Output:
P
5.11 SUMMARY
5.12 QUESTIONS
73
Sample String given: 'reboot'
1. Write a Python program to change a given string to a new string where
the first and last chars have been exchanged.
2. Write a Python program to count the occurrences of each word in a
given sentence
3. Write Python program to Check all strings are mutually disjoint
4. Write a program to find the first and the last occurence of the letter 'o'
and character ',' in "Good, Morning".
5. Write a program to check if the word 'open' is present in the "This is
open source software".
6. Write a program to check if the letter 'e' is present in the word
'Welcome'.
5.13 REFERENCES
1. https://developers.google.com/edu/python/strings
2. https://docs.python.org/3/library/string.html
3. https://www.programiz.com/python-programming/string
4. http://ww2.cs.fsu.edu/~nienaber/teaching/python/lectures/sequence-
string.html
5. https://www.tutorialsteacher.com/python/python-string
6. https://techvidvan.com/tutorials/python-strings/
7. http://anh.cs.luc.edu/handsonPythonTutorial/objectsummary.html
8. https://docs.python.org/3/library/stdtypes.html
9. https://www.programiz.com/python-programming/methods/string
10. https://www.w3schools.com/python/python_ref_string.asp
11. https://www.tutorialspoint.com/python_text_processing/python_string
_immutability.htm
12. https://web.eecs.utk.edu/~azh/blog/pythonstringsaremutable.html
*****
74
UNIT III
6
LIST
Unit structure
6.1 Objectives
6.2 Values and Accessing Elements
6.3 Lists are mutable
6.4 Traversing a List
6.5 Deleting elements from List
6.6 Built-in List Operators
6.7 Concatenation
6.8 Repetition
6.9 In Operator
6.10 Built-in List functions and methods
611 Summary
6.12 Exercise
6.13 References
6.1 OBJECTIVES
The list is most likely versatile data type available in the Python
which is can be written as a list of comma-separated values between
square brackets. The Important thing about a list is that items in the list
need not be of the same type.
75
Similar to a string indices, A list indices start from 0, and lists can
be sliced, concatenated.
To access values in lists, use the square brackets for slicing along
with the index or indices to obtain value available at that index. For
example –
list1 =['jack','nick',1997,5564];
list2 =[1,2,3,4,5,6,7];
print"list1[0]: ", list1[0]
print"list2[1:5]: ", list2[1:5]
output −
list1[0]: jack
list2[1:5]: [2, 3, 4, 5]
Example:
Output:.
The mostly common way to traverse the elements of list with for loop. The
syntax is the same as for strings:
76
for color in cheeses:
print(color)
This works well if you only need to read the element of list. But if you
want to do write or update the element, you need the indices. A common
way to do that is to combine the functions range and len:
for i in range(len(number)):
output −
red
white
blue
green
To delete a list element, you can use either the del statement, del removes the
item at a specific index, if you know exactly which element(s) you are deleting
or the remove() method if you do not know. For example –
print(list1)
del list[2]
print(list1)
output −.
Example2:
Output:
[50, 70, 80]
77
One other method from removing elements from a list is to take a slice
of the list, which excludes the index or indexes of the item or items
you are trying to remove. For instance, to remove the first two items of
a list, you can do
list = list[2:]
Concatenation
Indexing Repetition
List Operation
Membership
Slicing
Testing
1. Concatenation:
Example:
print(list1 + list2)
Output:
Example:
print(list1 * list2
Output:
3. Membership Operator:
Example:
Output:
False
True
True
False
4. Indexing:
Indexing is nothing but there is an index value for each tem present
in the sequence or list.
79
Example:
print(list1[4])
Output:
50
5. Slicing operator:
Syntax: list1[start:stop:step]
Example:
list1 = [10, 20, 30, 40, 50, 60, 70]
print(list1[3:7])
Output:
6.7 CONCATENATION
print(str(result))
Output:
Naive method:
In the Naive method, a for loop is used to be traverse the second list.
After this, the elements from the second list will get appended to the first
list. The first list of results out to be the concatenation of the first and the
second list.
Example:
for x in list2 :
list1.append(x)
Output:
Before Concatenation:
After Concatenation:
List comprehension:
It uses the for loop to process and traverses a list in the element-wise
fashion. The below inline is for-loop is equivalent to a nested for loop.
81
Example:
Output:
Concatenated list:
Extend() method:
Syntax:
list.extend(iterable)
Example:
list1.extend(list2)
All the elements of the list2 get appended to list1 and thus the list1 gets
updated and results as output.
Output:
‘*’ operator:
Python’s '*' operator can be used for easily concatenate the two lists in
Python.
82
The ‘*’ operator in Python basically unpacks the collection of items at
the index arguments.
The statement *list would replace by the list with its elements on the index
positions. So, it unpacks the items of the lists.
Example:
Output:
Output:
Concatenated list:
Itertools.chain() method:
Example:
import itertools
83
list2 = [20, 30, 42]
Output:
Concatenated list:
6.8 REPETITION
Example:
number = (0,) * 5 # we use the comma to denote that this is a single valued tuple
and not an ‘#’expression
Output
print numbers
(0, 0, 0, 0, 0)
[0] is a tuple with one element, 0. Now repetition of the operator it will
makes 5 copies of this tuple and joins them all together into a single tuple.
Another example using multiple elements in the tuple.
Example:
numbers = (0, 1, 2) * 3
Output
print numbers
(0, 1, 2, 0, 1, 2, 0, 1, 2)
6.9 IN OPERATOR
84
Example:
my_list = [5, 1, 8, 3, 7]
print(8 in my_list)
print(0 in my_list)
Output:
True
False
Note: Note that in operator against dictionary checks for the presence of
key.
Example:
my_dict = {'name': 'TutorialsPoint', 'time': '15 years', 'location': 'India'}
print('name' in my_dict)
Output:
True
1. Built-in function:
85
2. Built-in methods:
6.11 SUMMARY
86
6.12 QUESTIONS
6.13 REFERENCES
1. https://python.plainenglish.io/python-list-operation-summary-
262f40a863c8?gi=a4f7ce4740e9
2. https://howchoo.com/python/how-to-use-list-comprehension-in-python
3. https://intellipaat.com/blog/tutorial/python-tutorial/python-list-
comprehension/
4. https://programmer.ink/think/summary-of-python-list-method.html
5. https://www.geeksforgeeks.org/python-list/
6. https://enricbaltasar.com/python-summary-methods-lists/
7. https://developpaper.com/super-summary-learn-python-lists-just-this-
article-is-enough/
8. https://www.programiz.com/python-programming/methods/list
9. https://www.hackerearth.com/practice/python/working-with-
data/lists/tutorial/
10. https://data-flair.training/blogs/r-list-tutorial/
*****
87
7
TUPLES AND DICTIONARIES
Unit Structure
7.1 Objectives
7.2 Tuples
7.2 Accessing values in Tuples
7.3 Tuple Assignment
7.4 Tuples as return values
7.5 Variable-length argument tuples
7.6 Basic tuples operations
7.7 Concatenation
7.8 Repetition
7.9 In Operator
7.10 Iteration
7.11 Built-in Tuple Functions
7.12 Creating a Dictionary
7.13 Accessing Values in a dictionary
7.14 Updating Dictionary
7.15 Deleting Elements from Dictionary
7.16 Properties of Dictionary keys
7.17 Operations in Dictionary
7.18 Built-In Dictionary Functions
7.19 Built-in Dictionary Methods
7.20 Summary
7.21 Exercise
7.22 References
7.1 OBJECTIVES
88
7.2 TUPLES
Creating a Tuple:
A tuple can have any number of the items and they may be a
different types (integer, float, list, string, etc.).
Example:
# Empty tuple
tuple = ()
print(tuple)
tuple = (1, 2, 3)
print(tuple)
print(tuple)
# nested tuple
print(tuple)
89
Output:
()
(1, 2, 3)
print(tuple)
a, b, c = tuple
print(a) #3
print(b) # 4.6
print(c) # dog
Output:
( 3, 2.6, 'color')
2.6
color
There are various ways in which we can access the elements of a tuple.
1. Indexing:
90
The index must be an integer, so we cannot use float or other
types. This will result in TypeError.
Likewise, nested tuples are accessed using nested indexing, as shown in the
example below.
tuple = ('a','b','c','d','e','f')
print(tuple[0]) # 'a'
print(tuple[5]) # 'f'
# print(tuple[6])
# tuple[2.0]
# nested tuple
# nested index
print(tuple[0][3]) # 'o'
print(tuple[1][1]) #4
Output:
a
2. Negative Indexing:
The index of -1 refers to the last item, -2 to the second last item and so on.
Example:
tuple = ('a','b','c','d','e','f')
91
# Output: 'f'
print(tuple[-1])
# Output: 'a'
print(tuple[-6])
Output:
3. Slicing:
We can access the range of items from the tuple by using the
slicing operator colon:
Example:
tuple = ('a','b','c','d','e','f','g','h','i')
print(tuple[1:4])
print(tuple[:-7])
print(tuple[7:])
# Output: ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i')
print(tuple[:])
Output:
('b', 'c', 'd')
('a', 'b')
92
('h', 'i')
Example:
x, y = tuple
Output:
x
'red'
'blue'
m = [ 'red', 'blue' ]
x = m[0]
y = m[1]
Output:
x
'red'
'blue'
For example, we could write a function that returns both the area and the
circumference of a circle of radius.
Example:
def cirlce_info(r):
c = 2 * 3.14159 * r
a = 3.14159 * r * r
return (c, a)
print(cirlce_info(10))
Output:
(62.8318, 314.159)
print args
The gather parameter can have any name you like, but args is
conventional. Here’s how the function works:
t = (7, 3)
divmod(t)
max(1,2sum(1,2,3)
1. Membership:
We can apply the ‘in’ and ‘not in’ operator on the items. This tells us whether
they belong to the tuple.
'a' in tuple("string")
Output:
False
Output:
True
2. Concatenation:
(1,2,3)+(4,5,6)
Output:
(1, 2, 3, 4, 5, 6)
3. Logical:
(1,2,3)>(4,5,6)
95
Output:
False
(1,2)==('1','2')
Output:
False
4. Identity:
Remember the ‘is’ and ‘is not’ operators we discussed about in our
tutorial on Python Operators? Let’s try that on tuples.
a=(1,2)
(1,2) is a
Output:
That did not make sense, did it? So what really happened? Now, in
Python, two tuples or lists don't have the same identity. In other words,
they are two different tuples or lists. As a result, it returns False.
7.8 CONCATENATION
In our first example, we will use the sum() function to concatenate two
tuples and result in a single tuple.Let us jump to example:
tupleint= (1,2,3,4,5,6)
langtuple = ('C#','C++','Python','Go')
Output:
concatenate of tuples
96
= (1, 2, 3, 4, 5, 6, 'C#', 'C++', 'Python', 'Go')
tupleint= (1,2,3,4,5,6),
langtuple = ('C#','C++','Python','Go'),
Output:
concatenate of tuples
tupleint= (1,2,3,4,5,6)
langtuple = ('C#','C++','Python','Go')
tuples_concatenate = tupleint+langtuple
Output:
This example, we have the two tuple tuple int and lang tuple. Now
We are using the comma(,) end of the each tuple to the concatenate them
97
into a nested tuple. We are concatenating these tuples into a nested tuple
as we can see in the resulting output.
tupleint= (1,2,3,4,5,6),
langtuple = ('C#','C++','Python','Go'),
tuples_concatenate = tupleint+langtuple
Output:
concatenate of tuples
7.9 REPETITION
Syntax:
<tuple_variable_name1> * N
N * <tuple_variable_name1>
Input Parameters:
Example:
data=(1,2,3,'a','b')
98
Output:
7.10 IN OPERATOR
The Python in operator lets you loop through all to the members of
the collection and check if there's a member in the tuple that's equal to the
given item.
Example:
my_tuple = (5, 1, 8, 3, 7)
print(8 in my_tuple)
print(0 in my_tuple)
Output:
True
False
Example:
Output:
True
Example:
print("sample" in string)
Output:
True
It can be uses in the many of other places and how it works in the
those scenarios of varies a lot. This is the how in works in tuples. It start
99
the comparing references of the objects from the first one till it either finds
that the object in the tuple or reaches in the end of the tuple.
7.11 ITERATION
There are many ways to iterate through the tuple object. For
statement in Python has a variant which traverses a tuple till it is
exhausted. It is equivalent to for each statement in Java. Its syntax is –
for var in tuple:
stmt1
stmt2
Example:
T = (10,20,30,40,50)
for var in T:
print (T.index(var),var)
Output:
0 10
1 20
2 30
3 40
4 50
Comparison:
100
If we reached to the end of one of the lists, the longer list is a
"larger." If both are list are same it returns 0.
tuple2 = ('1','2','3')
cmp(tuple1, tuple2)
Out: 1
cmp(tuple2, tuple1)
Out: -1
cmp(tuple1, tuple3)
Out: 0
Tuple Length:
len(tuple1)
Out: 5
Max of a tuple:
The function min returns the item from the tuple with the min value:
min(tuple1)
Out: 'a'
min(tuple2)
Out: '1'
list = [1,2,3,4,5]
tuple(list)
Out: (1, 2, 3, 4, 5)
Tuple concatenation:
tuple1 + tuple2
Creating a Dictionary:
The values can belong to the any of data type and they can repeat,
but the keys are must remain the unique.
To print the dictionary contents, we can use the Python's print() function
and pass the dictionary name as the argument to the function. For
example:
dict_sample = {
"Company": "Toyota",
"model": "Premio",
"year": 2012
}
print(dict_sample)
Output:
{'Company': 'Toyota', 'model': 'Premio', 'year': 2012}
102
7.14 ACCESSING VALUES IN A DICTIONARY
"Company": "Toyota",
"model": "Premio",
"year": 2012
x = dict_sample["model"]
print(x)
Output:
Premio
dict_sample = {
"Company": "Toyota",
"model": "Premio",
"year": 2012
}
dict_sample["year"] = 2014
print(dict_sample)
Output:
In this example you can see that we have updated the value for the key
"year" from the old value of 2012 to a new value of 2014.
103
7.16 DELETING ELEMENTS FROM DICTIONARY
The del keyword can be used to remove the element with the
specified key. For example:
dict_sample = {
"Company": "Toyota",
"model": "Premio",
"year": 2012
del dict_sample["year"]
print(dict_sample)
Output:
Output:
dict_sample = {
"Company": "Toyota",
"model": "Premio",
"year": 2012
dict_sample.pop("year")
print(dict_sample)
"Company": "Toyota",
"model": "Premio",
"year": 2012
dict_sample.popitem()
print(dict_sample)
Output:
The last entry into the dictionary was "year". It has been removed
after calling the popitem() function.
"Company": "Toyota",
"model": "Premio",
"year": 2012
del dict_sample
print(dict_sample)
Output:
The code returns an error. The reason is we are trying to access the
an dictionary which is doesn't exist since it is has been deleted.
105
dict_sample = {
"Company": "Toyota",
"model": "Premio",
"year": 2012
dict_sample.clear()
print(dict_sample)
Output:
{}
The code is returns an empty dictionary since all the dictionary elements
have been removed.
(a)More than one of the entry per key not allowed. Which means that no
duplicate key isallowed. When the duplicate keys are encountered during
the assignment, And, the last assignment wins.
For example:
Output:
dict[‘Name’]: Manni
(b) Keys must be immutable. Which mean by you can use strings, And the
numbers or tuples as dictionary keys but something like [‘key’] is not
allowed. Following is a simple:
106
Output:
x = {}
access an element
x['two']
x.keys()
x.values()
add an entry
x["four"]=4
change an entry
x["one"] = "uno"
delete an entry
del x["four"
make a copy
y = x.copy()
107
x.clear()
number of items
z = len(x)
z = x.has_key("one")
if "two" not in x:
print "Two not found"
if "three" in x:
del x['three']
1. len():
len(dict4)
Output
3
len({})
any({False:False,'':''})
108
2. any():
Output:
False
Output:
any({True:False,"":""})
True
3
. all():
Unlike the any() function, all() returns True only if all the keys in the
dictionary have a Boolean value of True.
Output:
all({1:2,2:'',"":3})
False
4. sorted():
Like it is with lists and tuples, the sorted() function returns a sorted
sequence of the keys in the dictionary. The sorting is in ascending order,
and doesn’t modify the original Python dictionary.
dict4={3:3,1:1,4:4}
Output:
[1, 3, 4]
This function returns the keys in a sorted list. To prove this, let’s see what
the type() function returns.
109
This proves that sorted() returns a list.
{3: 3, 1: 1, 4: 4}
dict4
type(sorted(dict4))
1. keys():
dict_keys([3, 1, 4])
Output:
2. values():
Likewise, the values() method returns a list of values in the dictionary.
Output:
dict_values([3, 1, 4])
3. items()
This method returns a list of key-value pairs.
Output:
dict_items([(3, 3), (1, 1), (4, 4)])
7.20 SUMMARY
Tuples: In Python, tuples are structured and accessed based on
position. A Tuple is a collection of Python objects separated by commas.
In some ways a tuple is similar to a list in terms of indexing, nested
objects and repetition but a tuple is absolute unlike lists that are variable.
In Python it is an unordered collection of data values, used to store data
values like a map, which unlike other data types that hold only single
value as an element. Tuples are absolute lists. Elements of a list can be
modified, but elements in a tuple can only be accessed, not modified. The
110
name tuple does not mean that only two values can be stored in this data
structure.
Dictionaries: Dictionaries in Python are structured and accessed using
keys and values. Dictionaries are defined in Python with curly braces { } .
Commas separate the key-value pairs that make up the dictionary.
Dictionaries are made up of key and/or value pairs. In Python, tuples are
organized and accessed based on position. The location of a pair of keys
and values stored in a Python dictionary is unrelated. Key value is
provided in the dictionary to make it more optimized. A Python
dictionary is basically a hash table. In some languages, they might be
mentioned to an associative arrays. They are indexed with keys, which
can be any absolute type.
7.21 QUESTIONS
1. Let list = [’a’, ’b’, ’c’,’d’, ’e’, ’f’]. Find a) list[1:3] b) t[:4] c) t[3:]
2. State the difference between lists and dictionary
3. What is the benefit of using tuple assignment in Python?
4. Define dictionary with an example
5. Write a Python program to swap two variables
6. Define Tuple and show it is immutable with an example
7. Create tuple with single element
8. How can you access elements from the dictionary
9. Write a Python program to create a tuple with different data types.
10. Write a Python program to unpack a tuple in several variables
7.22 REFERENCES
1. https://www.geeksforgeeks.org/differences-and-applications-of-list-
tuple-set-and-dictionary-in-python/
2. https://problemsolvingwithpython.com/04-Data-Types-and-
Variables/04.05-Dictionaries-and-Tuples/
3. https://problemsolvingwithpython.com/04-Data-Types-and-
Variables/04.05-Dictionaries-and-Tuples/
4. https://ncert.nic.in/textbook/pdf/kecs110.pdf
5. https://python101.pythonlibrary.org/chapter3_lists_dicts.html
6. https://www.programmersought.com/article/26815189338/
7. https://www.javatpoint.com/python-tuples
8. https://cloudxlab.com/assessment/displayslide/873/python-
dictionaries-and-tuples
9. https://medium.com/@aitarurachel/data-structures-with-lists-tuples-
dictionaries-and-sets-in-python-612245a712af
10. https://www.w3schools.com/python/python_tuples.asp
*****
111
8
FILES AND EXCEPTIONS
Unit Structure
8.1 Objective
8.2 Text Files
8.3 The File Object Attributes
8.4 Directories
8.5 Built-in Exceptions
8.6 Handling Exceptions
8.7 Exception with Arguments
8.8 User-defined Exceptions
8.9 Summary
8.10 Exercise
8.11 References
8.1 OBJECTIVE
Now we will learn about various ways to read text files in Python.
The following shows how to read all texts from the readme.txt file into a
string:
with open('readme.txt') as f:
lines = f.readlines()
To read the text file in the Python, you have to follow these steps:
112
Firstly, you have to open the text file for reading by using the
open() method.
Second, you have to read the text from the text file using the file
read(), readline(), or readlines() method of the file object.
Third, you have to close the file using the file close() method.
1) open() function
The open() function has many parameters but you’ll be focusing on the
first two.
open(path_to_file, mode)
The path to the file parameter is specifies the path to the text file.
If the file is in the same folder as is program, you have just need to
specify the file name. Otherwise, you have need to specify the path to the
file.
Specify the path to the file, you have to use the forward-slash ('/')
even if you are working in Windows.
The following table shows available modes for opening a text file:
Mode Description
'r' Open for text file for reading text
'w' Open a text file for writing text
'a' Open a text file for appending text
f = open('the-zen-of-python.txt','r')
The open() function returns a file object which you will use to read
text from a text file.
The file object provides you with three methods for reading text from a
text file:
113
read() – read all text from a file into a string. This method is useful if you
have a small file and you want to manipulate the whole text of that file.
readline() – read the text file line by line and return all the lines as strings.
readlines() – read all the lines of the text file and return them as a list of
strings.
3) close() method:
The file that you open will remain open until you close it using the
close() method.
It’s important to close the file that is no longer in use. If you don’t
close the file, the program may crash or the file would be corrupted.
The following shows how to call the close() method to close the file:
f.close()
The following example illustrates how to use the read() method to read all
the contents of the the-zen-of-python.txt file into a string:
with open('the-zen-of-python.txt') as f:
contents = f.read()
print(contents)
Output:
...
114
The following example uses the readlines() method to read the text file
and returns the file contents as a list of strings:
lines = []
with open('the-zen-of-python.txt') as f:
lines = f.readlines()
count = 0
count += 1
Output:
...
Once a file is opened and you have one file object, you can get
various information related to that file. Here is a list of all attributes
related to file object:
Attribute Description
file.closed Returns true if file is closed, false otherwise.
file.mode Returns access mode with which file was opened.
file.name Returns name of the file.
file.softspace Returns false if space explicitly required with print, true
otherwise.
Example
# Open a file
fo = open(“foo.txt”, “wb”)
115
This produces the following result:
Opening mode : wb
Softspace flag : 0
8.4 DIRECTORIES
To find out which directory in python you are currently in, use the
getcwd() method.
os.getcwd()
Output:
‘C:\\Users\\lifei\\AppData\\Local\\Programs\\Python\\Python36-32’
Cwd is for current working directory in python. This returns the path of
the current python directory as a string in Python.
Output:
b’C:\\Users\\lifei\\AppData\\Local\\Programs\\Python\\Python36-32′
type(os.getcwd())
<class 'str'>
To render it properly, use the Python method with the print statement.
print(os.getcwd())
116
Output:
This takes one argument- the path to the directory to which to change.
Output:
Output:
We can also create new python directories with the mkdir() method. It
takes one argument, that is, the path of the new python directory to create.
os.mkdir('Christmas Photos')
os.listdir()
Output:
os.listdir()
Output:
[‘Adobe Photoshop CS2.lnk’, ‘Atom.lnk’, ‘Burn Book.txt’, ‘Christmas
2017’, ‘desktop.ini’, ‘Documents’, ‘Eclipse Cpp Oxygen.lnk’, ‘Eclipse
117
Java Oxygen.lnk’, ‘Eclipse Jee Oxygen.lnk’, ‘For the book.txt’, ‘Items for
trip.txt’, ‘Papers’, ‘Remember to remember.txt’, ‘Sweet anticipation.png’,
‘Today.txt’, ‘topics.txt’, ‘unnamed.jpg’]
os.chdir('C:\\Users\\lifei\\Desktop\\Christmas 2017')
os.listdir()
Output:
[‘Readme.txt’]
print(dir(locals()['__builtins__']))
follows:
118
MemoryError Raised when an operation runs out of memory.
NameError Raised when a variable is not found in local or
global scope.
NotImplementedError Raised by abstract methods.
OSError Raised when system operation causes system
related error.
OverflowError Raised when the result of an arithmetic
operation is too large to be represented.
ReferenceError Raised when a weak reference proxy is used to
access a garbage collected referent.
RuntimeError Raised when an error does not fall under any
other category.
StopIteration Raised by next() function to indicate that there
is no further item to be returned by iterator.
SyntaxError Raised by parser when syntax error is
encountered.
IndentationError Raised when there is incorrect indentation.
TabError Raised when indentation consists of inconsistent
tabs and spaces.
SystemError Raised when interpreter detects internal error.
SystemExit Raised by sys.exit() function.
TypeError Raised when a function or operation is applied
to an object of incorrect type.
UnboundLocalError Raised when a reference is made to a local
variable in a function or method, but no value
has been bound to that variable.
UnicodeError Raised when a Unicode-related encoding or
decoding error occurs.
UnicodeEncodeError Raised when a Unicode-related error occurs
during encoding.
UnicodeDecodeError Raised when a Unicode-related error occurs
during decoding.
UnicodeTranslateError Raised when a Unicode-related error occurs
during translating.
ValueError Raised when a function gets an argument of
correct type but improper value
ZeroDivisionError Raised when the second operand of division or
modulo operation is zero.
If you have some suspicious code that may raise an exception, you
can defend your program by placing the suspicious code in a try: block.
After the try: block, include an except: statement, followed by a block of
code which handles the problem as elegantly as possible.
Syntax:
Here is simple syntax of try....except...else blocks:
119
try:
......................
except ExceptionI:
except ExceptionII:
......................
else:
You can also provide a generic except clause, which handles any
exception.
The else-block is a good place for code that does not need the try:
block's protection.
Example:
This example opens a file, writes content in the, file and comes out
gracefully because there is no problem at all:
try:
fh = open("testfile", "w")
except IOError:
else:
120
print "Written content in the file successfully"
fh.close()
Example 1:
try:
b = float(100 + 50 / 0)
Output:
division by zero
class MyError(Exception):
# Constructor or Initializer
self.value = value
def __str__(self):
return(repr(self.value))
try:
Output:
'This is the Argument
'Some Error data'
class MyError(Exception):
# Constructor or Initializer
122
self.value = value
def __str__(self):
return(repr(self.value))
try:
raise(MyError(3*2))
Ouput:
8.9 SUMMARY
Files: Python supports file handling and allows users to handle files for
example, to read and write files, along with many other file handling
options, to operate on files. The concept of file handling has justified by
various other languages, but the implementation is either difficult.
Python delights file differently as text or binary and this is significant.
Each line of code includes a sequence of characters and they form text
file. Each line of a file is ended with a special character like comma {,}.
It ends the current line and expresses the interpreter a new one has
started. In Python a file is a contiguous set of bytes used to store data.
This data is organized in a precise format and can be anything as simple as
a text file. In the end, these byte files are then translated into
binary 1 and 0 for simple for processing. In Python, a file operation takes
place in the order like Open a file then Read or write and finally close the
file.
123
8.10 QUESTIONS
8.11 REFERENCES
1. https://www.learnpython.org/
2. https://www.packtpub.com/tech/python
3. https://www.softcover.io/read/e4cd0fd9/conversational-
python/ch6_files_excepts
4. https://docs.python.org/3/library/exceptions.html
5. https://www.tutorialspoint.com/python/python_exceptions.htm
6. https://www.w3schools.com/python/python_try_except.asp
7. https://www.geeksforgeeks.org/python-exception-handling/
8. https://www.analyticsvidhya.com/blog/2020/04/exception-handling-
python/
9. https://www.programiz.com/python-programming/file-operation
10. https://www.geeksforgeeks.org/file-handling-python/
11. https://realpython.com/read-write-files-python/
12. https://www.guru99.com/reading-and-writing-files-in-python.html
*****
124
UNIT IV
9
REGULAR EXPRESSION
Unit Structure
9.0 Objectives
9.1 Introduction
9.2 Concept of regular expression
9.3 Various types of regular expressions
9.4 Using match function.
9.7 Summary
9.8 Bibliography
9.9 Unit End Exercise
9.0 OBJECTIVES
9.1 INTRODUCTION
125
The regular expression language is relatively small and restricted,
so not all possible string processing tasks can be done using regular
expressions. There are also tasks that can be done with regular
expressions, but the expressions turn out to be very complicated. In these
cases, you may be better off writing Python code to do the processing;
while Python code will be slower than an elaborate regular expression, it
will also probably be more understandable.
You may be familiar with searching for text by pressing ctrl-F and
typing in the words you’re looking for.
Regular expressions are huge time-savers, not just for software users but
also for programmers.
Regular expressions, called regexes for short, are descriptions for a pattern
of text.
For example, a \d in a regex stands for a digit character— that is, any
single numeral 0 to 9.
Any other string would not match the \d\d\d-\d\d\d-\d\d \d\d regex.
126
Example:
adding a 3 in curly brackets ({3}) after a pattern is like saying, “Match this
pattern three times.”
Quantifiers :
127
9.3.1 re.search(): Finding Pattern in Text:
re.search() function will search the regular expression pattern and return
the first occurrence. Unlike Python re.match(), it will check all lines of the
input string. The Python re.search() function returns a match object when
the pattern is found and “null” if the pattern is not found
The search() function searches the string for a match, and returns
a Match object if there is a match.
If there is more than one match, only the first occurrence of the
match will be returned:
Example:
Search for the first white-space character in the string:
import re
x = re.search("\s", txt)
output:
The split() function returns a list where the string has been split at each
match:
Example:
x = re.split("\s", txt)
print(x)
output:
[‘The’,‘rain’,‘in’,‘Spain’]
128
9.3.3 re.findall():
Example:
x = re.findall("ai", txt)
print(x)
output:
[‘ai’ , ‘ai’]
The sub() function replaces the matches with the text of your choice:
Replace every white-space character with the number 9:
import re
print(x)
output:
The9rain9in9Spain
You can control the number of replacements by specifying
the count parameter:
Example:
Replace the first 2 occurrences:
129
import re
print(x)
output:
The9rain9inSpain
Example
Do a search that will return a Match Object:
import re
x = re.search("ai", txt)
output:
The Match object has properties and methods used to retrieve information
about the search, and the result:
.span() returns a tuple containing the start-, and end positions of the match.
.string returns the string passed into the function
.group() returns the part of the string where there was a match
Example:
Print the string passed into the function:
import re
x = re.search(r"\bS\w+", txt)
130
print(x.string)
output:
The rain in Spain
Example:
The regular expression looks for any words that starts with an upper case
"S":
import re
x = re.search(r"\bS\w+", txt)
print(x.group())
output:
Spain
validate the Email from file as well from string by using Regular
Expression:
131
9.7 SUMMARY
*****
133
10
CLASSES AND OBJECTS
Unit Structure
10.0 Objectives
10.1 Overview of OOP
10.2 Class Definition, Creating Objects
10.3 Instances as Arguments, Instances as return values
10.4 Built-in Class Attributes
10.5 Inheritance
10.6 Method Overriding
10.7 Data Encapsulation
10.8 Data Hiding
10.9 Summary
10.10 Unit End Exercise
10.11 Bibliography
10.0 OBJECTIVES
134
Polymorphism
Data Abstraction
Encapsulation
Object:
Object is an entity that has state and behavior. It may be anything. It may
be physical and logical. For example: mouse, keyboard, chair, table, pen
etc.
Class:
Class can be defined as a collection of objects. It is a logical entity that has
some specific attributes and methods.
Inheritance:
Inheritance is a feature of object-oriented programming. It specifies that
one object acquires all the properties and behaviors of parent object. By
using inheritance you can define a new class with a little or no changes to
the existing class. The new class is known as derived class or child class
and from which it inherits the properties is alled base class or parent class.
It provides re-usability of the code.
Polymorphism:
Polymorphism is made by two words "poly" and "morphs". Poly means
many and Morphs means form, shape. It defines that one task can be
performed in different ways.
For example:
You have a class animal and all animals talk. But they talk differently.
Here, the "talk" behavior is polymorphic in the sense and totally depends
on the animal. So, the abstract "animal" concept does not actually "talk",
but specific animals (like dogs and cats) have a concrete implementation
of the action "talk".
Encapsulation:
Encapsulation is also the feature of object-oriented programming. It is
used to restrict access to methods and variables. In encapsulation, code
and data are wrapped together within a single unit from being modified by
accident.
Data Abstraction:
Data abstraction and encapsulation both are often used as synonyms. Both
are nearly synonym because data abstraction is achieved through
encapsulation.
Class:
Syntax:
class ClassName:
<statement-1>
.
.
.
<statement-N>
Method:
Object:
Object is an entity that has state and behavior. It may be anything. It may
be physical and logical. For example: mouse, keyboard, chair, table, pen
etc.
Syntax
class ClassName:
self.instance_variable = value #value specific to instance
class_variable = value #value shared across all class instances
#accessing instance variable
class_instance = ClassName()
class_instance.instance_variable
#accessing class variable
ClassName.class_variable
Example
class Car:
wheels = 4 # class variable
def __init__(self, make):
136
self.make = make #instance variable
newCar = Car("Honda")
print ("My new car is a {}".format(newCar.make))
print ("My car, like all cars, has {%d} wheels".format(Car.wheels))
Suppose you have a point object and wish to find the midpoint
halfway between it and some other target point. We would like to write a
method, call it halfway that takes another Point as a parameter and returns
the Point that is halfway between the point and the target.
Example:
class Point:
def __init__(self, initX, initY):
""" Create a new point at the given coordinates. """
self.x = initX
self.y = initY
def getX(self):
return self.x
def getY(self):
return self.y
def distanceFromOrigin(self):
return ((self.x ** 2) + (self.y ** 2)) ** 0.5
def __str__(self):
return "x=" + str(self.x) + ", y=" + str(self.y)
print(mid)
print(mid.getX())
print(mid.getY())
137
The resulting Point, mid, has an x value of 4 and a y value of 8.
We can also use any other methods since mid is a Point object.
When you call an instance method (e.g. func ) from an instance object
(e.g. inst ), Python automatically passes that instance object as the
first argument, in addition to any other arguments that were passed in by
the user.
In the example there are two classes Vehicle and Truck, object of class
Truck is passed as parameter to the method of class Vehicle. In method
main() object of Vehicle is created.
Then the add_truck() method of class Vehicle is called and object of Truck
class is passed as parameter.
Example:
class Vehicle:
def __init__(self):
self.trucks = []
class Truck:
def __init__(self, color):
self.color = color
def __repr__(self):
return "{}".format(self.color)
def main():
v = Vehicle()
for t in 'Red Blue Black'.split():
t = Truck(t)
v.add_truck(t)
print(v.trucks)
if __name__ == "__main__":
main()
138
Sample output of above program:
Every Python class keeps following built-in attributes and they can be
accessed using dot operator like any other attribute −
__dict__ − Dictionary containing the class's namespace.
__doc__ − Class documentation string or none, if undefined.
__name__ − Class name.
__module__ − Module name in which the class is defined. This attribute
is "__main__" in interactive mode.
__bases__ − A possibly empty tuple containing the base classes, in the
order of their occurrence in the base class list.
Example:
For the above class let us try to access all these attributes −
classEmployee:
'Common base class for all employees'
empCount =0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount +=1
def displayCount(self):
print"Total Employee %d"%Employee.empCount
def displayEmployee(self):
print"Name : ",self.name,", Salary: ",self.salary
print"Employee.__doc__:",Employee.__doc__
print"Employee.__name__:",Employee.__name__
print"Employee.__module__:",Employee.__module__
print"Employee.__bases__:",Employee.__bases__
print"Employee.__dict__:",Employee.__dict__
Output:
When the above code is executed, it produces the following result −
Employee.__doc__: Common base class for all employees
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Employee.__dict__: {'__module__': '__main__', 'displayCount':
139
<function displayCount at 0xb7c84994>, 'empCount': 2,
'displayEmployee': <function displayEmployee at 0xb7c8441c>,
'__doc__': 'Common base class for all employees',
'__init__': <function __init__ at 0xb7c846bc>}
10.5 INHERITANCE
What is Inheritance?
The new class is called child class or derived class and the main
class from which it inherits the properties is called base class or parent
class.
The child class or derived class inherits the features from the
parent class, adding new features to it. It facilitates re-usability of code.
140
Python Multiple Inheritances:
141
10.6 METHOD OVERRIDING
Example:
class Parent():
# Constructor
def __init__(self):
self.value = "Inside Parent"
# Constructor
def __init__(self):
self.value = "Inside Child"
# Driver's code
obj1 = Parent()
obj2 = Child()
obj1.show()
obj2.show()
Output:
Inside Parent
Inside Child
# Protected member
self._a = 2
# Calling constructor of
# Base class
Base.__init__(self)
print("Calling protected member of base class: ")
print(self._a)
obj1 = Derived()
obj2 = Base()
Example -
class CounterClass:
__privateCount = 0
145
def count(self):
self.__privateCount += 1
print(self.__privateCount)
counter = CounterClass()
counter.count()
counter.count()
print(counter.__privateCount)
Output:
1
2
Traceback (most recent call last):
File "<string>", line 17, in <module>
AttributeError: 'CounterClass' object has no attribute '__privateCount
10.9 SUMMARY
10.11 BIBLIOGRAPHY
1.https://runestone.academy/runestone/books/published/thinkcspy/Classes
Basics/InstancesasrreturnValues.html
2. https://www.tutorialspoint.com/built-in-class-attributes-in-python
3.https://www.pythonlikeyoumeanit.com/Module4_OOP/Methods.html#:~
:text=When%20y
u%20call%20an%20instance,passed%20in%20by%20the%20user.
4. https://www.geeksforgeeks.org/method-overriding-in-python/
5. https://www.javatpoint.com/data-hiding-in-python.
*****
146
11
MULTITHREADED PROGRAMMING
Unit Structure
11.0 Objectives
11.1 Introduction
11.1 Thread Module
11.2 Creating a thread
11.3 Synchronizing threads
11.4 Multithreaded priority queue
11.5 Summary
11.6 Bibliography
11.7 Unit End Exercise
11.0 OBJECTIVES
To use Multithreading
To achieve Multithreading
To use the threading module to create threads
Address issues or challenges for threads
11.1 INTRODUCTION
147
11.2 THREAD MODULE
Syntax:
thread.start_new_thread ( function_name, args[, kwargs] )
Example:Thread.py
import thread # import the thread module
import time # import time module
Output:
Calculate the square root of the given number
Square is: 16
Square is: 25
Square is: 36
Square is: 49
148
Square is: 4
Calculate the cube of the given number
Cube is: 64
Cube is: 125
Cube is: 216
Cube is: 343
Cube is: 8
Total time taken by threads is: 3.005793809890747
Threads in python are an entity within a process that can be scheduled for
execution. In simpler words, a thread is a computation process that is to be
performed by a computer. It is a sequence of such instructions within a
program that can be executed independently of other codes.
Below has a coding example followed by the code explanation for creating
new threads using
Classinpython.
class thread(threading.Thread):
def __init__(self, thread_name, thread_ID):
threading.Thread.__init__(self)
self.thread_name = thread_name
self.thread_ID = thread_ID
thread1.start()
thread2.start()
149
print("Exit")
Output:
GFG 1000
IDOL 2000
Exit
Example:
from threading import Thread
from time import sleep
if __name__ == "__main__":
thread = Thread(target = threaded_function, args = (10, ))
thread.start()
thread.join()
print("thread finished...exiting")
Output:
running
running
running
running
running
running
running
running
running
running
thread finished...exiting
150
Then we used the threading module to create a thread that invoked the
function as its target.
The release() method of the new lock object is used to release the lock
when it is no longer
required.
import threading
import time
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print "Starting " + self.name
# Get lock to synchronize threads
threadLock.acquire()
print_time(self.name, self.counter, 3)
# Free lock to release next thread
threadLock.release()
def print_time(threadName, delay, counter):
while counter:
time.sleep(delay)
print "%s: %s" % (threadName, time.ctime(time.time()))
counter -= 1
151
threadLock = threading.Lock()
threads = []
# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# Start new Threads
thread1.start()
thread2.start()
# Add threads to thread list
threads.append(thread1)
threads.append(thread2)
# Wait for all threads to complete
for t in threads:
t.join()
print "Exiting Main Thread"
The get() and put() methods are used to add or remove items from
a queue respectively.
If two elements have the same priority, they are served according to their
order in the queue.
Example:
import queue
import threading
import time
thread_exit_Flag = 0
153
queueLock = threading.Lock()
workQueue = queue.Queue(10)
threads = []
threadID = 1
queueLock.release()
Output:
initializing Thread-1
initializing Thread-2initializing Thread-3
Thread-3 processing C
Thread-3 processing D
Thread-2 processing E
Exiting Thread-2
Exiting Thread-1
Exiting Thread-3
Exit Main Thread
154
Advantages of Multithreading:
Disadvantages of Multithreading:
11.6 SUMMARY
11.7 BIBLIOGRAPHY
1. https://www.javatpoint.com/multithreading-in-python-3
2. https://www.geeksforgeeks.org/how-to-create-a-new-thread-in-
python/
155
3. https://www.tutorialspoint.com/multithreaded-priority-queue-in-
python
4. https://www.techbeamers.com/python-multithreading-concepts/
*****
156
12
MODULE
Unit Structure
12.0 Objectives
12.1 Introduction
12.2 Importing module
12.3 Creating and exploring modules
12.4 Math module
12.5 Random module
12.6 Time module
12.7 Summary
12.8 Bibliography
12.9 Unit End Exercise
12.0 OBJECTIVES
12.1 INTRODUCTION
If you quit from the Python interpreter and enter it again, the
definitions you have made(functions and variables) are lost. Therefore,
if you want to write a somewhat longer program, you are better off
using a text editor to prepare the input for the interpreter and running it
with that file as input instead. This is known as creating a script.
156
12.2 IMPORTING MODULE
When the import is used, it searches for the module initially in the
local scope by calling __import__() function.
Example:
import math
print(math.pi)
Output:
3.141592653589793
Example:
from math import pi
# Note that in the above example,
# we used math.pi. Here we have used
# pi directly.
print(pi)
Output:
3.141592653589793
157
Example:
from math import *
print(pi)
print(factorial(6))
Output:
3.141592653589793
720
Example:
import mathematics
print(mathematics.pi)
Output:
Traceback (most recent call last):
File "C:/Users/GFG/Tuples/xxx.py", line 1, in
import mathematics
ImportError: No module named 'mathematics'
result = a + b
return result
158
Here, we have defined a function add() inside a module
named example. The function takes in two numbers and returns their
sum.
Using the module name we can access the function using the
dot . operator. For example:
>>> example.add(4,5.5)
9.5
Python has tons of standard modules. You can check out the
full list of Python standard modules and their use cases. These files are
in the Lib directory inside the location where you installed Python.
This is probably not what you want. It isn’t usual for a module
to generate output when it is imported.
Example
HTML Tutorial
import math
number = 2e-7 # small value of of x
print('log(fabs(x), base) is :', math.log(math.fabs(number), 10))
Output:
log(fabs(x), base) is : -6.698970004336019
<
math.log10()
161
This method returns base 10 logarithm of the given number and
called the standard logarithm.
Example
import math
x=13 # small value of of x
print('log10(x) is :', math.log10(x))
Output:
log10(x) is : 1.1139433523068367
math.exp()
Example
import math
number = 5e-2 # small value of of x
print('The given number (x) is :', number)
print('e^x (using exp() function) is :', math.exp(number)-1)
Output:
The given number (x) is : 0.05
e^x (using exp() function) is : 0.05127109637602412
math.pow(x,y)
Example
import math
number = math.pow(10,2)
print("The power of number:",number)
Output:
The power of number: 100.0
math.floor(x)
This method returns the floor value of the x. It returns the less
than or equal value to x.
Example:
import math
number = math.floor(10.25201)
print("The floor value is:",number)
162
Output:
The floor value is: 10
math.ceil(x)
This method returns the ceil value of the x. It returns the greater than
or equal value to x.
import math
number = math.ceil(10.25201)
print("The floor value is:",number)
Output:
The floor value is: 11
math.fabs(x)
This method returns the absolute value of x.
import math
number = math.fabs(10.001)
print("The floor absolute is:",number)
Output:
The absolute value is: 10.001
math.factorial()
Example
import math
number = math.factorial(7)
print("The factorial of number:",number)
Output:
The factorial of number: 5040
math.modf(x)
This method returns the fractional and integer parts of x. It carries the
sign of x is float.
Example
import math
number = math.modf(44.5)
print("The modf of number:",number)
Output:
The modf of number: (0.5, 44.0)
163
12.5 RANDOM MODULE
This function generates a random float number between 0.0 and 1.0.
random.randint()
Example
Hello Java Program for Beginners
# importing "random” module.
import random
# We are using the choice() function to generate a random number fro
m
# the given list of numbers.
print ("The random number from list is : ",end="")
print (random.choice([50, 41, 84, 40, 31]))
Output:
The random number from list is : 84
random.shuffle()
Output:
The random number between 0 and 1 is : 0.4405576668981033
Operations on Time:
Output:
Seconds elapsed since the epoch are : 1470121951.9536893
Time calculated acc. to given seconds is :
time.struct_time(tm_year=2016, tm_mon=8, tm_mday=2,
tm_hour=7, tm_min=12, tm_sec=31, tm_wday=1,
tm_yday=215, tm_isdst=0)
Output:
Time calculated using asctime() is : Tue Aug 2 07:47:02 2016
Time calculated using ctime() is : Tue Aug 2 07:47:02 2016
166
Python
Python
# Python code to demonstrate the working of
# sleep()
Output:
Start Execution : Tue Aug 2 07:59:03 2016
Stop Execution : Tue Aug 2 07:59:07 2016
12.7 SUMMARY
167
12.8 UNIT END EXERCISE
12.9 BIBLIOGRAPHY
1. https://docs.python.org/3/tutorial/modules.html
2. https://www.geeksforgeeks.org/import-module-python/
3. https://realpython.com/python-modules-packages/#executing-a-
module-as-a-script
4. https://www.programiz.com/python-programming/modules
5. https://www.javatpoint.com/python-math-module
*****
168
UNIT V
13
CREATING THE GUI FORM
AND ADDING WIDGETS
Unit Structure
13.1 Objectives
13.2 Introduction
13.3 Widgets
1.Label
2.Button
3.Entry Textbox
4.Combobox
5.Check Button
6.Radio Button
7.Scroll bar
8.List box
9.Menubutton
10.Spin Box
11.Paned Window
12.Tk Message Box
13.4 Summary
13.5 Questions
13.6 References
13.1 OBJECTIVES
13.2 INTRODUCTION
The setup wizard should have started. Click Next as shown in figure
below
3.5 On the next screen, change the installation path if required. Click on
Next as shown in figure below
170
3.6 On the Next Screen, you can create a desktop shortcut if you want and
click on “Next”
3.7 Choose the start menu folder. Keep selected Jetbrains and click on
“Install”
171
3.8 Wait for the Installation to finish
3.9 Once installation finished, you should receive a message screen that
pycharm is installed. If you want to go ahead and run it, Click the
“Run Pycharm Community edition” box first and click finish.
172
3.10 After you click on “Finish”, the Following screen will appear
173
13.3 WIDGETS
There are various widgets like button, canvas, check button, entry etc. that
are used to build the python GUI application
1 Label
1 A label is a text used to display some message or information about
the other widgets
2 Syntax w= Label(master,options)
3 A list of option are as follows
3 Code:
import tkinter as tk
from tkinter import ttk
#create Instance
win=tk.Tk()
#Add a title
win.title("Label GUI")
#Adding a label
ttk.Label(win, text="A label").grid(column=0,row=0)
#start GUI
win.mainloop()
After executing this program on pycharm using run command, the output
of above code as shown below
2 Button:
1. The button widget is used to add various types of buttons to the python
application. Python allows the look of the button according to our
requirements.
2. Various options can be set or reset depending upon the requirements.
3. We can also associate a method or function with a button which is
called when the button is pressed.
4 Syntax
W=Button(parent,options)
5. A list of possible options is illustrated in table below
175
Sr.No Option Description
1. activebackground It represents the background of the button
when the mouse hover the button.
2. activeforeground It represents the font color of the button
when the mouse hover the button.
3. Bd It represents the border width in pixels.
4. Bg It represents the background color of the
button.
5. Command It is set to the function call which is
scheduled when the function is called.
6. Fg Foreground color of the button.
7. Font The font of the button text
8. Height The height of the button. The height is
represented in the number of text lines for
the textual lines or the number of pixels
for the images.
9. HighlightColor The color of the highlight when the
button has the focus.
10. Image It is set to the image displayed on the
button.
11. justify It illustrates the way by which the
multiple text lines are represented. It is
set to LEFT for left justification, RIGHT
for the right justification, and CENTER
for the center.
12. Padx Additional padding to the button in the
horizontal direction.
13. Pady Additional padding to the button in the
vertical direction.
14. Relief It represents the type of the border. It can
be SUNKEN, RAISED, GROOVE, and
RIDGE.
15. State This option is set to DISABLED to make
the button unresponsive. The ACTIVE
represents the active state of the button.
16. Underline Set this option to make the button text
underlined.
17. Width The width of the button. It exists as a
number of letters for textual buttons or
pixels for image buttons.
18. Wraplength If the value is set to a positive number,
the text lines will be wrapped to fit within
this length.
176
6. Code:
import tkinter as tk
from tkinter import ttk
#create Instance
win=tk.Tk()
#Adding a label that will get modified
a_label=ttk.Label(win,text="A Label")
a_label.grid(column=0,row=0)
#Button click Event Function
def click_me():
action.configure(text="** I have been clicked! **")
a_label.configure(foreground='red')
a_label.configure(text='A Red Label')
#Adding a Button
action=ttk.Button(win, text="Click Me!",command=click_me)
action.grid(column=1,row=0)
#start Gui
win.mainloop()
Here Win is the parent of Button. The output of above code is shown
below
178
6 Code Snippet:
import tkinter as tk
from tkinter import ttk
#create Instance
win=tk.Tk()
#Modified Button Click Function
def click_me():
action.configure(text='Hello' +name.get())
#changing our label
ttk.Label(win,text="Enter a name:").grid(column=0,row=0)
#Start GUI
win.mainloop()
Output
13.4 COMBOBOX
1 code snippet:
179
Ouput
5. Checkbutton:
1. The checkbutton is used to display the checkbutton on the window.
2. It is used to track the user’s choices provided to the application. In
other words, we can say that checkbutton is used to implement the
on/off selections.
3. The checkbutton can obtain the text or images. The checkbutton is
mostly used to provide many choices to the user among which, the
user needs to choose the one. It generally implements many of many
selections.
4. syntax
W=checkbutton(master,options)
5. A list of possible options is given below
180
9. Wraplength If this option is set to an integer
number, the text will be broken in to
the number of pieces.
6. Code Snippet:
Output:
6. Radio Button:
1. The Radiobutton is different from a checkbutton. Here the user is
provided with various options and the user can select only one option
among them.
2. It is used to implement one-of-many selection in the python
application. It shows multiple choices to the user out of which, the user
can select only one out of them.
3. We can associate different methods with each of the radiobutton.
4. We can display the multiple line text or images on the radiobuttons.
Each button displays a single value for that particular variable.
5. Syntax
181
W=Radiobutton(top,options)
6. The list of possible options given below
7. Code snippet:
1. from tkinter import *
2.
3. def selection():
4. selection = "You selected the option " + str(radio.get())
5. label.config(text = selection)
6.
7. top = Tk()
8. top.geometry("300x150")
9. radio = IntVar()
10. lbl = Label(text = "Favourite programming language:")
182
11. lbl.pack()
12. R1 = Radiobutton(top, text="C", variable=radio, value=1,
13. command=selection)
14. R1.pack( anchor = W )
15.
16. R2 = Radiobutton(top, text="C++", variable=radio, value=2,
17. command=selection)
18. R2.pack( anchor = W )
19.
20. R3 = Radiobutton(top, text="Java", variable=radio, value=3,
21. command=selection)
22. R3.pack( anchor = W)
23.
24. label = Label(top)
25. label.pack()
26. top.mainloop()
Output:
13.3.7 Scrollbar:
1 It provides the scrollbar to the user so that the user can scroll the
window up and down.
2 This widget is used to scroll down the content of the other widgets like
listbox, text and canvas. However, we can also create the horizontal
scrollbars to the entry widget.
3 The syntax to use the scrollbar widget is give below
W=Scrollbar(top, options)
4 A list of possible options is given below
183
Sr. No. option Description
1 orient It can be set to HORIZONTAL or
VERTICAL depending upon the orientation
of the scrollbar.
2 jump It is used to control the behavior of the scroll
jump. If it set to 1, then the callback is called
when the user releases the mouse button.
3 repeatdelay This option tells the duration up to which the
button is to be pressed before the slider starts
moving in that direction repeatedly. The
default is 300 ms.
4 takefocus We can tab the focus through this widget by
default. We can set this option to 0 if we don't
want this behavior.
5 troughcolor It represents the color of the trough.
6 width It represents the width of the scrollbar
5. Code snippet:
top = Tk()
sb = Scrollbar(top)
sb.pack(side = RIGHT, fill = Y)
mainloop()
Output:
6. Code Snippet:
from tkinter import *
top = Tk()
top.geometry("200x250")
listbox = Listbox(top)
listbox.insert(1,"India")
listbox.insert(2, "USA")
listbox.insert(3, "Japan")
listbox.insert(4, "Austrelia")
#this button will delete the selected item from the list
185
lbl.pack()
listbox.pack()
btn.pack()
top.mainloop()
output
13.3.9 Menubutton:
1. The menubutton is used to display the menu items to the user.
186
2. It can be defined as the drop-down menu that is shown to the user all
the time. It is used to provide the user a option to select the appropriate
choice exist within the application.
3. The Menubutton is used to implement various types of menus in the
python application. A Menu is associated with the menubutton that can
display the choices of the menubutton when clicked by the user.
4. The syntax to use the python tkinter menubutton is given below
W=Menubutton(Top,options)
5. code snippet
from tkinter import *
top = Tk()
top.geometry("200x250")
menubutton.grid()
menubutton.menu = Menu(menubutton)
menubutton["menu"]=menubutton.menu
menubutton.pack()
top.mainloop()
output
Fig 11 Menubutton
188
13.3.11 PanedWindow:
1 It is like a container widget that contains horizontal or vertical panes.
2 The PanedWindow widget acts like a Container widget which contains
one or more child widgets (panes) arranged horizontally or vertically.
The child panes can be resized by the user, by moving the separator
lines known as sashes by using the mouse.
3 Each pane contains only one widget. The PanedWindow is used to
implement the different layouts in the python applications.
4 The syntax to use the PanedWindow is given below
W=PanedWindow(master,options)
5 Code Snippet
from tkinter import *
def add():
a = int(e1.get())
b = int(e2.get())
leftdata = str(a+b)
left.insert(1,leftdata)
w1 = PanedWindow()
w1.pack(fill = BOTH, expand = 1)
left = Entry(w1, bd = 5)
w1.add(left)
Fig 12 PanedWindow
189
13.3.13. TkMessagebox:
1. This module is used to display the message-box in the desktop based
applications
2. The messagebox module is used to display the message boxes in the
python applications. There are the various functions which are used to
display the relevant messages depending upon the application
requirements.
3. The syntax to use the messagebox is given below.
Messagebox.function_name(title,message,[,options])
4. Parameter explanation
4.1 function_name-It represents an appropriate message box functions
4.2 title-It is a string which is shown as a title of a messagebox
4.3 message-It is the string to be displayed as a message on the
massagebox
4.4 Options- There are various options which can be used to
configure the message dialog box.
5. Code Snippet
from tkinter import *
from tkinter import messagebox
top = Tk()
top.geometry("100x100")
messagebox.askquestion("Confirm","Are you sure?")
top.mainloop()
Output:
Fig 12 Output-Tkmessagebox
190
13.4 SUMMARY
13.6 QUESTIONS
Q1 Design a calculator using widget of python
Q2 Design a pendulum clock
Q3 Design a PingPong game in tkinter
Q4 List down the various options of button widget
Q5 Compare and contrast between the listbox and combobox
13.5 REFERENCES
Useful Links
1. https://www.javatpoint.com/python-tkinter
*****
191
14
LAYOUT MANAGEMENT & LOOK
& FEEL CUSTOMIZATION
Unit structure
14.1 Objectives
14.2 Introduction
14.3 Layout Management-Designing GUI Application with proper layout
Management features
14.4 Look & Feel customization- Enhancing look & feel of GUI using
different appearances of widgets.
14.5 Summary
14.6 Questions
14.7 References
14.1 OBJECTIVES
14.2 INTRODUCTION
192
14.3 LAYOUT MANAGEMENT-DESIGNING GUI
APPLICATION WITH PROPER LAYOUT
MANAGEMENT FEATURES
1.3 We can easily align the labels vertically by changing our code, as
shown below in pseudocode
193
Fig 2 Output of GUI Label Frame
194
Pseudocode for adding space around the labels
1.14 Using the grid layout manager, what happens is that the width of any
given column is determined by the longest name or widget in that
column. This affects all the rows.
1.15 By adding our LabelFrame widget and giving it a title that is longer
than some hardcoded size widget, such as the top-left label and the
text entry below it, we dynamically move those widgets to the center
of column 0, adding space on the left- and right-hand side of those
widgets.
1.16 The following code can be added to Label frame code shown above
and then placed labels in to his frame
1.17 The dynamic behavior of Python and its GUI modules can create a
little bit of a challenge to really get our GUI looking the way we
want. Here, we will embed frames within frames to get more control
of our layout. This will establish a stronger hierarchy among the
different UI elements, making the visual appearance easier to achieve.
1.18 Here, we will create a top-level frame that will contain other frames
and widgets. This will help us get our GUI layout just the way we
want.
1.19 In order to do so, we will have to embed our current controls within a
central frame called ttk.LabelFrame. This frame ttk.LabelFrame is the
child of the main parent window and all controls will be the children
of this ttk.LabelFrame.
1.20 We will only assign LabelFrame to our main window and after that,
we will make this LabelFrame the parent container for all the widgets.
196
In the diagram shown above, win is the variable that holds a
reference to our main GUI tkinter window frame, mighty is the variable
that holds a reference to our LabelFrame and is a child of the main
window frame (win), and Label and all other widgets are now placed into
the LabelFrame container (mighty).
Next, we will modify the following controls to use mighty as the parent,
replacing win. Here is an example of how to do this
197
3 We have to import the Menu class from tkinter. Add the following line
of code to the top of the python module, where the import statement
live as shown below in pseudocode
Next, we will create the menu bar, Add the following code towards the
bottom of the module, just above where we create the main event loop
Next, we will add a second menu item to the first menu that we
added to the menu bar
198
Fig 8 Menu item with Exit option
199
Fig 9 Menu item with Help option
200
Fig 10 Tabbed GUI
Tkinter automatically adds the missing row where we did not specify any
particular row.
202
Fig 13 A error message box
1.6 We still need a title and we definitely want to get rid of this
unnecessary second window. The second window is caused by a
windows event loop. We can get rid of it by suppressing it.
203
Fig 15 Independent Message window got by adding withdraw()
in code
2. How to create the title of a tkinter window form:
1.6 The principle of changing the title of a tkinter main root window is the
same as what discussed in topic presented above.
1.7 Here we create the main root window and give it a title
204
4. Using a Spin box control:
1.10 We will use a spinbox widget and we will also bind the Enter key on
the keyboard to one of our widget.
1.11 We will use tabbed GUI code and will add further a spinbox widget
above the scrolledtext control. This simply requires us to increment
the ScrolledText row value by one and to insert our new spinbox
control in the row above the entry widget.
1.12 First, we add the Spinbox control. Place the following code above
the ScrolledText widget
205
Next, we add another property to customize our widget further, bd is
short-hand notation for the borderwidth property
spin=Spinbox(mighty, from=0, to=0,width-5, bd=8)
206
Fig 22 Spinbox with small border width
207
3.8 Here are the available relief property options that can be set
208
In an object oriented programming (OOP) approach, we create a
new class in our python module. Python allows us to place more than one
class in to same pyhton module and it also enables us to mix-and-match
classes and regular functions in the same module.
After all the necessary tooltip creation code that occirs within the
Tooltip class, we switch over to non-OOP python programming by
creating a function just below it
We could do the same for all of our other GUI widgets in the very
same manner. We just have to pass in a reference to the widget we wish to
have a tooltip, displaying some extra information. For our ScrolledText
widget, we made the scrol variable point to it, so this is what we pass into
the constructor of our tooltip creation function:
209
Fig 25 ToolTip Output
210
Fig 26 Progress Bar
211
Fig 27 Canvas output
14.5 SUMMARY
14.6 QUESTIONS
14.7 REFERENCES
*****
212
15
STORING DATA IN OUR MYSQL
DATABASE VIA OUR GUI
Unit Structure
15.0 Objectives
15.1 Introduction
15.2 Connecting to a MySQL database from Python
15.3 Configuring the MySQL connection, Designing the Python GUI
database
15.4 Using the INSERT command
15.5 Using the UPDATE command
15.6 Using the DELETE command
15.7 Storing and retrieving data from MySQL database.
15.8 Summary
15.9 Questions
15.10 References
15.0 OBJECTIVES
15.1 INTRODUCTION
214
If running the preceding code results in the following output printed to
the console, then we are good.
14. If you are not able to connect to the MySQL server, then something
probably went wrong during the installation. If this is the case, try
uninstalling MySQL, reboot your PC, and then run the MySQL
installation again. Double-check that you downloaded the MySQL
installer to match your version of Python. If you have more than one
version of Python installed, that sometimes leads to confusion as the
one you installed last gets prepended to the Windows path
environmental variable and some installers just use the first Python
version they can find in this location.
15. In order to connect our GUI to a MySQL server, we need to be able to
connect to the server with administrative privileges if we want to
create our own database.
16. If the database already exists, then we just need the authorization
rights to connect, insert, update, and delete data.
215
15.3 CONFIGURING THE MYSQL CONNECTION,
DESIGNING THE PYTHON GUI DATABASE
3. We will use our configuration file to connect to the MySQL server and
then create our own database on the MySQL server.
10. We then import this module and unpack the credentials, as we did
before.
12. Now that we know how to connect to MySQL and have administrator
privileges, we can create our own database by issuing the following
commands:
217
we move up or down the table, but here we use it to create the database
itself.
15. We wrap the Python code into tary…except block and use the built-in
error codes of MySQL to tell us if anything went wrong.
16. We can verify that this block works by executing the database-creating
code twice. The first time, it will create a new database in MySQL,
and the second time it will print out an error message stating that this
database already exists.
19..import mysql.connector
as mysql import
GuiDBConfig as
guiConf
# unpack dictionary credentials
conn = mysql.connect(**guiConf.dbConfig)
cursor = conn.cursor()
cursor.execute("SHOW
DATABASES")
print(cursor.fetchall())
conn.close()
20. Running this code shows us which databases currently exist in our
MySQL server instance. As we can see from the output, MySQL ships
with several built-in databases, such as information_schema , and so
on. We have successfully created our owuidb database, which is
shown in the output. All other databases illustrated come shipped with
MySQL.
Output
1. 2. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",p
asswd = "google")
4. #creating the cursor object
5. cur = myconn.cursor()
6. try:
7. #creating a new database
8. cur.execute("create database PythonDB2")
9. #getting the list of all the databases which will now include the new
database PythonDB
10. dbs = cur.execute("show databases")
11. except:
12. myconn.rollback()
219
13. for x in cur:
14. print(x)
15. myconn.close()
output:
3. Insert Operation:
1. The INSERT INTO statement is used to add a record to the table. In
python, we can mention the format specifier (%s) in place of values.
2. We provide the actual values in the form of tuple in the execute()
method of the cursor
3. Consider the Following example
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",p
asswd = "google",database = "PythonDB")
4. #creating the cursor object
5. cur = myconn.cursor()
6. sql = "insert into Employee(name, id, salary, dept_id, branch_name) v
alues (%s, %s, %s, %s, %s)"
7. #The row values are provided in the form of tuple
221
8. val = ("John", 110, 25000.00, 201, "Newyork")
9. try:
10. #inserting the values into the table
11. cur.execute(sql,val)
12. #commit the transaction
13. myconn.commit()
14. except:
15. myconn.rollback()
16. print(cur.rowcount,"record inserted!")
17. myconn.close()
222
#Create the connection object
except:
myconn.rollback()
myconn.close()
223
15.5 USING THE UPDATE COMMAND
224
15.6 USING THE DELETE COMMAND
The following SQL query is used to delete the employee detail whose id is
110 from the table.
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",pass
wd = "google",database = "PythonDB")
myconn.rollback()
myconn.close()
1. The SELECT statement is used to read the values from the databases.
We can restrict the output of a select query by using various clause in
SQL like where, limit, etc.
2. Python provides the fetchall() method returns the data stored inside the
table in the form of rows. We can iterate the result to get the individual
rows.
import mysql.connector
try:
#Reading the Employee data
cur.execute("select * from Employee")
225
#fetching the rows from the cursor object
result = cur.fetchall()
#printing the result
for x in result:
print(x);
except:
myconn.rollback()
myconn.close()
226
15.8 SUMMARY
15.9 QUESTIONS
15.10 REFERENCES
*****
227