Python Notes Final
Python Notes Final
BASIC TO
ADVANCED
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
ES
UNIT III
SS
6. List 75
A
CL
7. Tuples And Dictionaries 88
8. Files And Exceptions 112
S
R'
UNIT IV
SI
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
Theory Examination Internal
SO
U
RA
V
SI
R'
S
CL
A
SS
ES
UNIT I
1
INTRODUCTION
Unit Structure
1.0 Objectives
1.1 Introduction: The Python Programming Language
1.2 History
1.3 Features
1.4 Installing Python
1.5 Running Python program
1.6 Debugging
1.6.1 Syntax Errors
1.6.2 Runtime Errors
1.6.3 Semantic Errors
1.6.4 Experimental Debugging
1.7 Formal and Natural Languages
1.8 The Difference Between Brackets, Braces, and Parentheses
1.9 Summary
1.10 References
1.11 Unit End Exercise
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
ES
changing the code.
SS
This is not possible in other programming languages, thus making
Python one of the most portable languages available in the
industry. A
CL
6. Highly Dynamic
S
R'
type of the variable during coding, thus saving time and increasing
efficiency.
U
SO
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
ES
demo.py. It contains only single line code of Python which prints
the text “Hello World!” on execution.
SS
So, how you can execute the Python program using the command
A
prompt. To see this, you have to first open the command
CL
prompt using the ‘window+r’ keyboard shortcut. Now, type the
word ‘cmd’ to open the command prompt.
S
Python file.
SO
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.
ES
SS
A
CL
S
R'
SI
V
RA
You can type the Python code directly in the Python interactive
mode. Here, in the image below contains the print program of
U
Python.
SO
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.
ES
SS
A
CL
S
R'
SI
V
RA
U
Create a Python file with .py extension and open it with the Python
SO
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.
ES
A new shell window will open which contains the output of the
Python code. Create your own file and execute the Python code
SS
using this simple method using Python IDLE.
A
CL
S
R'
SI
V
RA
U
SO
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
ES
else
print ("you cannot vote”) #syntax error because of not using
SS
indentation
A
CL
1.6.2 Runtime Errors:
The second type of error is a runtime error, so called because the
S
error does not appear until after the program has started running.
R'
division by zero
performing an operation on incompatible types
U
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.
ES
Natural languages are the languages people speak, such as English,
Spanish, and French. They were not designed by people (although
SS
people try to impose some order on them); they evolved naturally.
A
Formal languages are languages that are designed by people for
CL
specific applications.
For example, the notation that mathematicians use is a formal
S
statement.
Syntax rules come in two flavors, pertaining to tokens and
structure. Tokens are the basic elements of the language, such as
words, numbers, and chemical elements.
The second type of syntax rule pertains to the structure of a
statement; that is, the way the tokens are arranged. The statement
3+ = 3 is illegal because even though + and = are legal tokens, you
can’t have one right after the other.
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]
ES
Example:
SS
Lookup the first characters of string
str>>>’mumbai’
A
CL
>>> str [0]
‘m’
S
‘umb’
V
RA
Braces {}
Curly braces are used in python to define set or dictionary.
U
SO
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’>
ES
z=mul (2,3)
print(x,’*’,y,’=’z)
SS
In the function definition def mul(a,b) formal parameters are
specified using parentheses
A
CL
In the function call z=mul (2,3) actual values are specified using
parenthesis.
S
R'
SI
1.9 SUMMARY
V
Programming Language.
U
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.
ES
print statement.
SS
*****
A
CL
S
R'
SI
V
RA
U
SO
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
ES
2.4 Operators and Operands
2.5 Expressions
SS
2.6 Interactive Mode and Script Mode
2.7 Order of Operations
A
CL
2.8 Summary
2.9 References
S
R'
2.0 OBJECTIVES
V
RA
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’>
ES
>>> type (17)
<type ‘int’>
SS
Not surprisingly, strings belong to the type str and integers belong to
A
the type int. Less obviously, numbers with a decimal point belong to a
CL
type called float, because these numbers are represented in a format
called floating-point.
S
<type ‘float’>
SI
What about values like '17' and '3.2'? They look like numbers, but they
V
<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’>
ES
names with multiple words, such as my_name or
SS
airspeed_of_unladen_swallow.
If you give a variable an illegal name, you get a syntax error:
>>> 76mumbai= 'big city' A
CL
SyntaxError: invalid syntax
>>> more@ = 1000000
S
R'
SO
It turns out that class is one of Python’s keywords. The interpreter uses
keywords to recognize the structure of the program, and they cannot be
used as variable names.
Python has a lot of keywords. The number keeps on growing with the
new features coming in python.
Python 3.7.3 is the current version as of writing this book. There are
35 keywords in Python 3.7.3 release.
We can get the complete list of keywords using python interpreter help
utility.
$ python3.7
>>> help ()
help> keywords
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.
ES
2.3 TYPE CONVERSION
SS
The process of converting the value of one data type (integer, string, float,
A
etc.) to another data type is called type conversion. Python has two types
CL
of type conversion.
S
type to another data type. This process doesn't need any user
V
involvement.
RA
example where Python promotes the conversion of the lower data type
(integer) to the higher data type (float) to avoid data loss.
U
SO
ES
SS
When we run the above program, the output will be:
Data type of num_int: <class 'int'>
Data type of num_str: <class 'str'> A
CL
Traceback (most recent call last):
S
As we can see from the output, we got TypeError. Python is not able to
RA
Syntax:
<required_datatype>(expression)
17
Example 3: Addition of string and integer using explicit conversion
num_int = 123
num_str = "456"
ES
Data type of num_str after Type Casting: <class 'int'>
SS
Sum of num_int and num_str: 579
A
CL
Data type of the sum: <class 'int'>
S
SI
RA
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)
ES
** Perform exponent (raise to power)
SS
Arithmetic Operator Examples:
>>> 10+20
A
CL
30
>>> 20-10
S
R'
10
SI
>>> 10*2
20
V
RA
>>> 10/2
5
U
>>> 10%3
SO
1
>>> 2**3
8
>>> 10//3
3
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:
ES
Operators Description
SS
and Logical AND (When both conditions are true output will
A
be true)
CL
or Logical OR (If any one condition is true output will be
true
S
print(a)
True
U
b=5>4 or 3<2
SO
print(b)
True
c=not(5>4)
print(c)
False
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
ES
b is given in list
SS
A
Identity operators:
CL
Operators Description
S
false
SI
else false.
RA
a=20
SO
b=20
if (a is b):
print (“a, b has same identity”)
else:
print (“a, b is different”)
b=10
if (a is not b):
print (“a, b has different identity”)
else:
print (“a, b has same identity”)
>>>
a, b has same identity
a, b has different identity
21
2.5 EXPRESSIONS
ES
2.6 INTERACTIVE MODE AND SCRIPT MODE:
SS
One of the benefits of working with an interpreted language is that you
A
can test bits of code in interactive mode before you put them in a
CL
script. But there are differences between interactive mode and script
mode that can be confusing.
S
R'
For example, if you are using Python as a calculator, you might type
SI
42.182
RA
U
The first line assigns a value to miles, but it has no visible effect. The
SO
22
print 1
x=2
print x
produces the output
1
2
The assignment statement produces no output.
ES
parentheses are evaluated first,
SS
2 * (3-1) is 4, and (1+1)**(5-2) is 8. You can also use parentheses to
make an expression easier to read, as in (minute * 100) / 60, even if it
doesn’t change the result. A
CL
Exponentiation has the next highest precedence, so 2**1+1 is 3, not 4,
S
than Addition and Subtraction, which also have the same precedence.
V
Operators with the same precedence are evaluated from left to right
(except exponentiation). So, in the expression degrees / 2 * pi, the
U
2.8 SUMMARY
ES
We are more focuses on type conversion of variables in this chapter
SS
basically two types of conversion are implicit type conversion and
explicit type conversion.
A
CL
Also studied types of operators available in python like arithmetic,
logical, relational and membership operators.
S
R'
operations.
V
width = 17
height = 12.0
delimiter = '.'
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
ES
2.9 REFERENCES
SS
Think Python by Allen Downey 1st edition.
A
Python Programming for Beginners By Prof. Rahul E. Borate, Dr.
CL
Sunil Khilari, Prof. Rahul S. Navale.
S
https://learning.rc.virginia.edu/
R'
www.programiz.com
SI
www.itvoyagers.in
V
RA
U
SO
*****
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:
ES
3.3.1 for loop
3.3.2 while loop
SS
3.3.3 nested loops
3.4 Control statements:
A
CL
3.4.1 Terminating loops
3.4.2 skipping specific conditions
S
3.5 Summary
R'
3.6 References
SI
3.0 OBJECTIVES
U
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.
ES
constraint evaluates to true or false. Conditional statements are handled
by IF statements in Python.
SS
Story of Two if’s:
A
CL
Consider the following if statement, coded in a C-like language:
if (p > q)
S
R'
{ p = 1;
SI
q = 2;
}
V
RA
p=1
SO
q=2
what Python adds
what Python removes
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.
ES
Example: Python if Statement
SS
# If the number is positive, we print an appropriate message
num = 3
A
CL
if num > 0:
print (num, "is a positive number.")
S
num = -1
V
if num > 0:
RA
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.
ES
# num = -5
SS
# num = 0
A
CL
if num >= 0:
S
else:
SI
Output:
RA
Positive or Zero
U
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
ES
# Try these two variations as well:
SS
# num = 0
A
# num = -4.5
CL
if num > 0:
S
elif num == 0:
SI
print("Zero")
V
else:
RA
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:
ES
Enter a number: -1
SS
Negative number
A
CL
Output3:
Enter a number: 0
S
Zero
R'
SI
RA
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.
ES
When you run the program, the output will be:
SS
The sum is 48
A
CL
The range () function:
We can generate a sequence of numbers using range
S
numbers).
SI
We can also define the start, stop and step size as range (start,
V
inefficient. So, it remembers the start, stop, step size and generates
SO
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
ES
executed if the items in the sequence used in for loop exhausts.
The break keyword can be used to stop a for loop. In such cases,
SS
the else part is ignored.
A
Hence, a for loop's else part runs if no break occurs.
CL
Example:
S
digits = [0, 1, 5]
R'
for i in digits:
SI
print(i)
V
else:
RA
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.
ES
while test_expression:
SS
Body of while
In the while loop, test expression is checked first. The body of the
A
loop is entered only if the test_expression evaluates to True.
CL
After one iteration, the test expression is checked again. This
S
indentation.
V
The body starts with indentation and the first unindented line marks
RA
the end.
Python interprets any non-zero value as True. None and 0 are
U
interpreted as False.
SO
ES
The while loop can be terminated with a break statement. In such
cases, the else part is ignored. Hence, a while loop's else part runs
SS
if no break occurs and the condition is false.
Example:
A
CL
'''Example to illustrate
the use of else statement
S
R'
counter = 0
V
else:
SO
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:
ES
statement(s) of inside for loop
statement(s) of outside for loop
SS
A
In this first for loop will initiate the iteration and later
CL
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.
S
R'
Once all iterations of inside for loop are completed then statements
SI
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:
*
**
***
****
*****
ES
******
SS
*******
A
********
CL
*********
S
In above situation inside while loop will finish its execution first
V
Syntax
while expression:
U
SO
while expression2:
statement(s) of inside while loop
statement(s) of outside while loop
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
ES
7777777
SS
88888888
999999999
A
CL
Exampleb2: Program to nested while loop
S
x=10
R'
while x>1:
SI
y=10
V
while y>=x:
RA
y-=1
SO
x-=1
print(" ")
Output:
10
99
888
7777
66666
555555
4444444
33333333
222222222
38
3.4 CONTROL STATEMENTS:
ES
if condition:
SS
break
Example:
A
CL
for num in range (10):
if num > 5:
S
R'
break
V
print(num)
RA
Output:
U
0
SO
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
ES
elif-else and nested if-else statements for solving complex
problems in python.
SS
More focuses on loop control in python basically two types of
A
loops available in python like while loop, for loop and nested loop.
CL
Studied how to control the loop using break and continue
statements in order to skipping specific condition and terminating
S
loops.
R'
1
23
456
78910
1112131415
ES
1234
12345
SS
9. Display numbers from -10 to -1 using for loop
10. Print the following pattern
A
CL
*
**
S
***
R'
*****
SI
******
V
3.7 REFERENCES
RA
U
*****
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
ES
4.6.2 Parameters and Arguments
4.6.3 Variables and Parameters Are Local
SS
4.6.4 Stack Diagrams
A
4.7 Fruitful Functions and Void Functions
CL
4.8 Why Functions?
4.9 Importing with from, Return Values, Incremental Development
S
4.12 Summary
V
4.13 References
RA
4.0 OBJECTIVES
SO
4.1 INTRODUCTION
ES
Syntax of Function
SS
def function_name(parameters):
"""docstring""" A
CL
statement(s)
S
R'
components.
V
Example:
def greeting(name):
"""
This function greets to
the person passed in as
43
a parameter
"""
print ("Hello, " + name + ". Good morning!")
ES
Python has two types of type conversion.
1. Implicit Type Conversion
SS
2. Explicit Type Conversion
A
CL
1. Implicit Type Conversion:
In Implicit type conversion, Python automatically converts one
S
R'
data type to another data type. This process doesn't need any user
involvement.
SI
lower data type (integer) to the higher data type (float) to avoid
RA
data loss.
U
num_int = 123
num_float = 1.23
num_new = num_int + num_float
print (“datatype of num_int:”, type(num_int))
print (“datatype of num_float:” type(num_float))
print (“Value of num_new:”, num_new)
print (“datatype of num_new:”, type(num_new))
Output:
datatype of num_int: <class 'int'>
datatype of num_float: <class 'float'>
Value of num_new: 124.23
datatype of num_new: <class 'float'>
44
Example 2: Addition of string(higher) data type and integer(lower)
datatype
num_int = 123
num_str = "456"
ES
In the above program,
SS
We add two variables num_int and num_str.
A
As we can see from the output, we got TypeError. Python is not
CL
able to use Implicit Conversion in such conditions.
S
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'>
ES
Explicit Type Conversion is also called Type Casting, the data
types of objects are converted using predefined functions by the
SS
user.
A
In Type Casting, loss of data may occur as we enforce the object to
CL
a specific data type.
S
For example
U
import math
math.sqrt(4)
Functions in Python Math Module
Pi is a well-known mathematical constant, which is defined as the
ratio of the circumference to the diameter of a circle and its value is
3.141592653589793.
>>> import math
>>>math.pi
3.141592653589793
Another well-known mathematical constant defined in the math
module is e. It is called Euler's number and it is a base of the
natural logarithm. Its value is 2.718281828459045.
>>> import math
>>>math.e
2.718281828459045
46
The math module contains functions for calculating various
trigonometric ratios for a given angle. The functions (sin, cos, tan,
etc.) need the angle in radians as an argument. We, on the other
hand, are used to express the angle in degrees. The math module
presents two angle conversion functions: degrees () and radians (),
to convert the angle from degrees to radians and vice versa.
>>> import math
>>>math.radians(30)
0.5235987755982988
>>>math.degrees(math.pi/6)
29.999999999999996
math.log()
The math.log() method returns the natural logarithm of a given
number. The natural logarithm is calculated to the base e.
>>> import math
ES
>>>math.log(10)
SS
2.302585092994046
math.exp()
A
CL
The math.exp() method returns a float number after raising e to the
S
>>>math.exp(10)
V
22026.465794806718
RA
math.pow()
U
The math.pow() method receives two float arguments, raises the first to
SO
ES
punctuation marks are legal, but the first character can’t be a
number. You can’t use a keyword as the name of a function, and
SS
you should avoid having a variable and a function with the same
A
name.
CL
The empty parentheses after the name indicate that this function
doesn’t take any arguments.
S
The first line of the function definition is called the header; the rest
R'
is called the body. The header has to end with a colon and the body
SI
has to be indented.
V
Single quotes and double quotes do the same thing; most people
SO
use single quotes except in cases like this where a single quote
appears in the string.
Once you have defined a function, you can use it inside another
function. For example, to repeat the previous refrain, we could
write a function called repeat_lyrics:
def repeat_lyrics():
print_lyrics()
print_lyrics()
And then call repeat_lyrics:
>>> repeat_lyrics()
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
48
4.6 DEFINITIONS AND USES
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 ()
ES
executed just like other statements, but the effect is to create
SS
function objects.
The statements inside the function do not get executed until the
A
function is called, and the function definition generates no output.
CL
4.6.1 Flow of Execution:
S
R'
In order to ensure that a function is defined before its first use, you
SI
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
ES
>>> print_twice(math.pi)
SS
3.14159265359
3.14159265359 A
CL
The same rules of composition that apply to built-in functions also
S
Spam SpamSpamSpam
RA
Spam SpamSpamSpam
U
>>> print_twice(math.cos(math.pi))
SO
-1.0
-1.0
The argument is evaluated before the function is called, so in the
examples the expressions 'Spam '*4 and math.cos(math.pi) are only
evaluated once.
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.
ES
To keep track of which variables can be used where, it is
SS
sometimes useful to draw a stack diagram. Like state diagrams,
stack diagrams show the value of each variable, but they also show
the function each variable belongs to.A
CL
Each function is represented by a frame. A frame is a box with the
S
function inside it. The stack diagram for the previous example is
shown in Figure.
SI
V
RA
U
SO
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__.
ES
golden = (math.sqrt(5) + 1) / 2
SS
When you call a function in interactive mode, Python displays
the result:
>>>math.sqrt(5)
A
CL
2.2360679774997898
S
But in a script, if you call a fruitful function all by itself, the return
R'
math.sqrt(5)
V
This script computes the square root of 5, but since it doesn’t store or
RA
some other effect, but they don’t have a return value. If you try to
SO
assign the result to a variable, you get a special value called None.
>>> result = print_twice('Bing')
Bing
Bing
>>> print(result)
None
The value None is not the same as the string 'None'. It is a special
value that has its own type:
>>> print type(None)
<type 'NoneType'>
The functions we have written so far are all void.
52
4.8 WHY FUNCTIONS?
ES
Importing with from:
SS
Python provides two ways to import modules, we have already seen
one:
>>> import math
A
CL
>>> print math
S
3.14159265359
V
RA
If you import math, you get a module object named math. The
module object contains constants like pi and functions
like sin and exp.
U
SO
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.
ES
bool() function returns a boolean value and this function
returns False for all the following values
SS
1. None
2. False A
CL
3. Zero number of any type such as int, float and complex. For
S
example: 0, 0.0, 0j
R'
SI
SO
bool() function returns True for all other values except the values
that are mentioned above.
Example: bool() function
In the following example, we will check the output of bool() function
for the given values. We have different values of different data
types and we are printing the return value of bool() function in the
output.
# empty list
lis = []
print(lis,'is',bool(lis))
# empty tuple
t = ()
print(t,'is',bool(t))
# zero complex number
54
c = 0 + 0j
print(c,'is',bool(c))
num = 99
print(num, 'is', bool(num))
val = None
print(val,'is',bool(val))
val = True
print(val,'is',bool(val))
# empty string
str = ''
print(str,'is',bool(str))
str = 'Hello'
print(str,'is',bool(str))
ES
Output:
SS
[] is False
() is False
A
CL
0j is False
99 is True
S
R'
None is False
SI
True is True
V
is False
RA
Hello is True
U
What is recursion?
Recursion is the process of defining something in terms of itself.
A physical world example would be to place two parallel mirrors
facing each other. Any object in between them would be reflected
recursively.
In Python, we know that a function can call other functions. It is
even possible for the function to call itself. These types of construct
are termed as recursive functions.
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.
ES
Example of a recursive function
SS
def factorial(x):
if x == 1:
SI
return 1
V
RA
else:
U
return (x * factorial(x-1))
SO
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
ES
4.14 UNIT END EXERCISE
SS
1. Python provides a built-in function called len that returns the length
A
of a string, so the value of len('allen') is 5.
CL
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
S
>>> right_justify('allen')
SI
V
allen
RA
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.
*****
ES
SS
A
CL
S
R'
SI
V
RA
U
SO
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
ES
5.11 Summary
SS
5.12 Questions
5.13 References
A
CL
5.0 OBJECTIVES
S
R'
>>>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’”’
ES
Or using backslashes.
SS
>> ‘Thank\
Good Morning Sir !’ A
CL
‘ThanksGood Morning Sir!’
S
R'
You cannot start a string with a single quote and end it with a double
SI
quote..
V
But if you surround a string with single quotes and also want to use single
RA
quotes as part of the string, you have to escape it with a backslash (\).
‘Send message to Madam\’s son ’
U
SO
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’
ES
5.2. TRAVERSAL AND THE FOR LOOP: BY ITEM
SS
A
A lot of computations involve processing a collection one item at a
CL
time. For strings this means that we would like to process one character at
a time. Often we start at the beginning, select each character in turn, do
S
something to it, and continue until the end. This pattern of processing is
R'
called a traversal.
SI
We have previously seen that the for statement can iterate over the
V
"Paris"]:
SO
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.
ES
s = "python rocks"
for ch in s[3:8]:
SS
print("HELLO")
A
Ans - Yes, The blank is part of the sequence returned by slice
CL
5.3. STRING SLICES
S
R'
SI
The slicing starts with the start_pos index (included) and ends at
U
end_pos index (excluded). The step parameter is used to specify the steps
SO
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
ES
Llo
SS
Note that index value starts from 0, so start_pos 2 refers to the third
character in the string.
A
CL
Reverse a String using Slicing
S
We can reverse a string using slicing by providing the step value as -1.
R'
s = 'HelloWorld'
SI
reverse_str = s[::-1]
V
print(reverse_str)
RA
Output:
U
SO
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
ES
SS
There is a common case for when strings in Python are actually
mutable. I will show you an example by inspecting the string object's
A
unique ID using the builtin id() function, which is just the memory
CL
address. The number is different for each object. (Objects can be shared
though, such as with interning.)
S
R'
change its worth all its lifetime. Attempt to execute the accompanying
code:
V
RA
name_1 = "Aarun"
name_1[0] = 'T'
U
SO
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"
ES
print("id of name_1 = ", id(name_1))
SS
print("id of name_2 = ", id(name_2))
Output: A
CL
id of name_1 = 2342565667256
S
5.5 SEARCHING
V
RA
data structure and match it with the value you are searching for.This is
SO
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
ES
False
SS
Interpolation Search:
A
CL
This search algorithm works on the probing position of the
required value. For this algorithm to work properly, the data collection
S
match occurs, then the index of the item is returned. If the middle item is
greater than the item, then the probe position is again calculated in the
V
sub-array to the right of the middle item. Otherwise, the item is searched
RA
in the subarray to the left of the middle item. This process continues on the
sub-array as well until the size of subarray reduces to zero.
U
SO
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'
ES
count = 0
SS
for letter in word:
A
if letter == 'r':
CL
count = count + 1
print(count)
S
R'
time an “r” is found. When the loop exits, count contains the result: the
RA
count = 0
SO
for char in s:
if char == "t":
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
ES
isdigit() Returns True if all characters in the string are digits
SS
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower
case
A
CL
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
S
case
SI
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.
ES
vowels = ['A', 'E', 'I', 'O', 'U']
SS
ch = input('Please Enter a Capital Letter:\n')
if ch in vowels:
A
CL
print('You entered a vowel character')
else:
S
R'
We can use the “in” operator with Strings and Tuples too because they are
V
sequences.
RA
>>> name='JournalDev'
U
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.
ES
str2 = input("Enter the second String: ")
SS
if str1 == str2:
A
print ("First and second strings are equal and same")
CL
else:
S
Output:
SI
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.
ES
4. Comparing two strings using ‘is’ operator
SS
Python is Operator returns True if two variables refer to the same object
instance. A
CL
str1 = "DEED"
S
str2 = "DEED"
R'
print(str1 is str2)
V
RA
Output:
SO
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"
ES
print(SingleQuotes)
SS
print(DoubleQuotes)
A
CL
Output:
Python in Single Quotes
S
R'
print()
U
This function is used for displaying the output or result on the user screen.
SO
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
ES
character of the substring. If the starting and/or ending index is left out
Python uses 0 and the length of the string correspondingly. Python
SS
assumes indices that would be beyond an end of the string essentially say
the end of the string. String formatting is the way we form instructions so
A
that Python can recognize how to integrate data in the creation of strings.
CL
How strings are formatted determines the presentation of this data. The
basis of string formatting is its use of the formatting directives.Logical
S
operators return true or false values. Comparison operators (==, !=, <>, >,
R'
>=, <, <=) compare two values.Any value in Python equates to a Boolean
SI
true or false. A false can be equal to none, a zero of numeric type (0, 0l,
V
0.0), an empty sequence ('', (), []), or an empty dictionary ({}). All other
RA
values are reflected true. Sequences, tuples, lists, and strings can be added
and/or multiplied by a numeric type with the addition and multiplication
U
and dictionaries using the format directives %i, %d, %f, and %e.
Formatting flags should be used with these directives.
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
ES
2. https://docs.python.org/3/library/string.html
SS
3. https://www.programiz.com/python-programming/string
A
4. http://ww2.cs.fsu.edu/~nienaber/teaching/python/lectures/sequence-
CL
string.html
5. https://www.tutorialsteacher.com/python/python-string
S
R'
6. https://techvidvan.com/tutorials/python-strings/
SI
7. http://anh.cs.luc.edu/handsonPythonTutorial/objectsummary.html
V
8. https://docs.python.org/3/library/stdtypes.html
RA
9. https://www.programiz.com/python-programming/methods/string
U
10. https://www.w3schools.com/python/python_ref_string.asp
SO
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
ES
6.9 In Operator
SS
6.10 Built-in List functions and methods
611 Summary
A
CL
6.12 Exercise
6.13 References
S
R'
6.1 OBJECTIVES
SI
V
2. To study usage of the list index to remove, update and add items from
python list.
U
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]
ES
6.3 LISTS ARE MUTABLE:
SS
A
lists is mutable. This means we can change a item in a list by
CL
accessing it directly as part of the assignment pf statement. Using the
indexing operator (square brackets) on the left of side an assignment, we
S
Example:
V
print(color)
U
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
ES
6.5 DELETING ELEMENTS FROM LIST
SS
A
To delete a list element, you can use either the del statement, del removes the
CL
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 –
S
R'
print(list1)
V
del list[2]
RA
print(list1)
SO
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
ES
SS
Indexing Repetition
A
CL
List Operation
S
R'
SI
V
Membership
RA
Slicing
Testing
U
SO
1. Concatenation:
Example:
print(list1 + list2)
Output:
Example:
print(list1 * list2
Output:
3. Membership Operator:
ES
item is a member of any list or not. ‘in’ And ‘not in’ are the operators for
SS
membership operator.
Example: A
CL
list1 = [10, 20, 30]
S
R'
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:
ES
This operator used to slice a particular range of a list or a sequence.
SS
Slice is used to retrieve a subset of values.
A
CL
Syntax: list1[start:stop:step]
S
Example:
R'
print(list1[3:7])
V
RA
Output:
U
SO
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.
ES
SS
Example:
for x in list2 :
V
list1.append(x)
RA
Output:
SO
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:
ES
and add the item to the list, extending the list in a linear fashion.
SS
Syntax:
A
list.extend(iterable)
CL
Example:
S
R'
list1.extend(list2)
U
SO
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:
ES
In the above snippet of code, the statement res = [*list1, *list2]
SS
replaces the list1 and list2 with the items in the given order i.e. elements of
A
list1 after elements of list2. This performs concatenation and results in the
CL
below output.
Output:
S
R'
Concatenated list:
SI
V
Itertools.chain() method:
U
Example:
import itertools
83
list2 = [20, 30, 42]
Output:
Concatenated list:
6.8 REPETITION
ES
Example:
SS
number = (0,) * 5 # we use the comma to denote that this is a single valued tuple
and not an ‘#’expression
A
CL
Output
S
R'
print numbers
SI
(0, 0, 0, 0, 0)
V
[0] is a tuple with one element, 0. Now repetition of the operator it will
RA
makes 5 copies of this tuple and joins them all together into a single tuple.
Another example using multiple elements in the tuple.
U
SO
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'}
ES
print('name' in my_dict)
SS
Output:
1. Built-in function:
RA
1 cmp(list1, list2)
SO
85
2. Built-in methods:
ES
Removes object obj from list
8 list.reverse()
SS
Reverses objects of list in place
A
9 list.sort([func])
CL
Sorts objects of list, use compare func if given
S
6.11 SUMMARY
R'
SI
create lists. In this chapter, we have given some examples of how you can
RA
are more compressed and faster than loops and other functions used such
as, map(), filter(), and reduce().Every Python list can be rewritten in for
loops, but not every complex for loop can be rewritten in Python list
understanding. Writing very long list in one line should be avoided so as
to keep the code user-friendly. So list looks just like dynamic sized
arrays, declared in other languages. Lists need not be homogeneous
always which makes it a most powerful tool in Python. A single list may
contain Datatype’s like Integers, Strings, and Objects etc. List loads all
the elements into memory at one time, when the list is too long, it will
reside in too much memory resources, and we usually only need to use a
few elements. A list is a data-structure that can be used to store multiple
data at once. The list will be ordered and there will be a definite count of
it. The elements are indexed allowing to a sequence and the indexing is
done with 0 as the first index. Each element will have a discrete place in
the sequence and if the same value arises multiple times in the sequence.
86
6.12 QUESTIONS
ES
SS
6.13 REFERENCES
A
CL
1. https://python.plainenglish.io/python-list-operation-summary-
262f40a863c8?gi=a4f7ce4740e9
S
2. https://howchoo.com/python/how-to-use-list-comprehension-in-python
R'
SI
3. https://intellipaat.com/blog/tutorial/python-tutorial/python-list-
comprehension/
V
RA
4. https://programmer.ink/think/summary-of-python-list-method.html
5. https://www.geeksforgeeks.org/python-list/
U
SO
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
ES
7.9 In Operator
SS
7.10 Iteration
7.11 Built-in Tuple Functions
A
CL
7.12 Creating a Dictionary
7.13 Accessing Values in a dictionary
S
7.20 Summary
7.21 Exercise
7.22 References
7.1 OBJECTIVES
88
7.2 TUPLES
Creating a Tuple:
ES
A tuple can have any number of the items and they may be a
SS
different types (integer, float, list, string, etc.).
Example: A
CL
# Different types of tuples
S
R'
# Empty tuple
SI
tuple = ()
V
RA
print(tuple)
U
tuple = (1, 2, 3)
print(tuple)
print(tuple)
# nested tuple
print(tuple)
89
Output:
()
(1, 2, 3)
print(tuple)
a, b, c = tuple
ES
SS
print(a) #3
print(b) # 4.6
A
CL
print(c) # dog
S
R'
Output:
SI
( 3, 2.6, 'color')
V
RA
3
U
2.6
SO
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])
ES
# tuple[2.0]
SS
A
# nested tuple
CL
tuple = ("color", [6, 4, 2], (1, 2, 3))
S
# nested index
R'
print(tuple[0][3]) # 'o'
SI
V
print(tuple[1][1]) #4
RA
Output:
a
U
SO
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:
ES
Example:
SS
# Accessing tuple elements using slicing
tuple = ('a','b','c','d','e','f','g','h','i')
A
CL
# elements 2nd to 4th
S
R'
print(tuple[1:4])
V
RA
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:
ES
x, y = tuple
SS
Output:
x
A
CL
'red'
S
y
R'
SI
'blue'
V
m = [ 'red', 'blue' ]
SO
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)
ES
print(cirlce_info(10))
SS
Output:
A
CL
(62.8318, 314.159)
S
R'
name that begins with the * gather the argument into the tuple. For
RA
example, the print all take any number of the arguments and print them:
U
def printall(*args):
SO
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
ES
they belong to the tuple.
SS
'a' in tuple("string")
A
CL
Output:
S
False
R'
SI
Output:
RA
True
2. Concatenation:
U
SO
(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:
ES
SS
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,
A
they are two different tuples or lists. As a result, it returns False.
CL
7.8 CONCATENATION
S
R'
the python language with code example. We will use ‘+” operator and a
V
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'),
ES
Output:
SS
concatenate of tuples
A
CL
= ((1, 2, 3, 4, 5, 6), ('C#', 'C++', 'Python', 'Go'))
Concatenate tuple Using ‘+’ operator:
S
R'
two tuples and result in a single tuple.In this example we have two tuple
RA
tupleint and langtuple,We are the concatenating these tuples into the single
tuple as we can see in output.
U
SO
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
ES
SS
7.9 REPETITION
A
Now, we are going to explain how to use Python tuple repetition
CL
operator with basic syntax and many examples for better understanding.
S
number of times which is given by the integer value and create a new tuple
SI
values.
V
RA
Syntax:
U
<tuple_variable_name1> * N
SO
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)
ES
print(0 in my_tuple)
SS
Output:
True
A
CL
False
S
R'
key.
V
Example:
RA
Output:
U
SO
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)
ES
for var in T:
SS
print (T.index(var),var)
Output:
A
CL
0 10
S
R'
1 20
SI
2 30
V
3 40
RA
4 50
U
SO
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
ES
Tuple Length:
SS
len(tuple1)
Out: 5
A
CL
Max of a tuple:
S
R'
The function min returns the item from the tuple with the min value:
SI
min(tuple1)
V
Out: 'a'
RA
min(tuple2)
U
SO
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.
ES
dict_sample = {1: 'mango', 2: 'pawpaw'}
SS
A
Creating a dictionary with mixed keys:
CL
dict_sample = {'fruit': 'mango', 1: [4, 6, 8]}
S
method:
SI
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:
ES
Premio
SS
We created a dictionary named dict_sample. A variable named x is
then created and its value is set to be the value for the key "model" in the
dictionary. A
CL
7.15 UPDATING DICTIONARY
S
R'
SI
dict_sample = {
U
"Company": "Toyota",
SO
"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"]
ES
print(dict_sample)
SS
Output:
the square brackets that follow the dictionary name, we passed the key of
R'
the element we need to delete from the dictionary, which in this example
SI
was "year". The entry for "year" in the dictionary was then deleted.
V
and pass the key of the entry to be deleted as the argument to the function.
For example:
U
SO
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:
ES
The last entry into the dictionary was "year". It has been removed
SS
after calling the popitem() function.
A
But what if you want to delete the entire dictionary? It would be
CL
difficult and cumbersome to use one of these methods on every single key.
Instead, you can use the del keyword to delete the entire dictionary. For
S
R'
example:
SI
dict_sample = {
V
"Company": "Toyota",
RA
"model": "Premio",
U
"year": 2012
SO
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.
ES
7.17 PROPERTIES OF DICTIONARY KEYS
SS
Dictionary values have no restrictions. These can be any of
A
erratically Python object, either they standard objects or user-defined
CL
objects. However, similar is not true for the keys.
S
R'
(a)More than one of the entry per key not allowed. Which means that no
RA
duplicate key isallowed. When the duplicate keys are encountered during
the assignment, And, the last assignment wins.
U
SO
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 = {}
ES
x = {"one":1, "two":2, "three":3}
SS
access an element
A
CL
x['two']
S
x.keys()
V
x.values()
U
SO
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")
ES
if "one" in x:
print x['one']
SS
A
if "two" not in x:
print "Two not found"
CL
if "three" in x:
S
del x['three']
R'
SI
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
ES
dictionary have a Boolean value of True.
SS
Output:
A
CL
all({1:2,2:'',"":3})
False
S
R'
4. sorted():
SI
V
Like it is with lists and tuples, the sorted() function returns a sorted
RA
dict4={3:3,1:1,4:4}
SO
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():
ES
dict_keys([3, 1, 4])
SS
The keys() method returns a list of keys in a Python dictionary.
dict4.values() A
CL
Output:
S
R'
2. values():
SI
Output:
RA
dict_values([3, 1, 4])
U
SO
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
ES
3. What is the benefit of using tuple assignment in Python?
SS
4. Define dictionary with an example
5. Write a Python program to swap two variables
A
6. Define Tuple and show it is immutable with an example
CL
7. Create tuple with single element
S
7.22 REFERENCES
1. https://www.geeksforgeeks.org/differences-and-applications-of-list-
U
tuple-set-and-dictionary-in-python/
SO
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
ES
8.9 Summary
8.10 Exercise
SS
8.11 References
A
CL
8.1 OBJECTIVE
S
4. To study creation and use of read and write commands for files.in
RA
python
U
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.
ES
SS
Specify the path to the file, you have to use the forward-slash ('/')
even if you are working in Windows.
A
CL
Example, if the file is in the readme.txt stored in the sample folder
as the program, you have need to specify the path to the file as
S
c:/sample/readme.txt
R'
SI
The following table shows available modes for opening a text file:
U
Mode Description
SO
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()
ES
To close the file automatically without calling the close() method,
you use the with statement like this:
SS
A
with open(path_to_file) as f:
CL
contents = f.readlines()
S
automatically.
SI
The following example illustrates how to use the read() method to read all
SO
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:
ES
line 2: Explicit is better than implicit.
SS
line 3: Simple is better than complex.
...
A
CL
8.3 THE FILE OBJECT ATTRIBUTES
S
R'
Once a file is opened and you have one file object, you can get
SI
Attribute Description
U
# 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
ES
getcwd() method.
SS
os.getcwd()
A
CL
Output:
S
‘C:\\Users\\lifei\\AppData\\Local\\Programs\\Python\\Python36-32’
R'
SI
Cwd is for current working directory in python. This returns the path of
the current python directory as a string in Python.
V
RA
os.getcwdb()
SO
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:
ES
How to Create Python Directory?
SS
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.
A
CL
os.mkdir('Christmas Photos')
S
os.listdir()
R'
SI
Output:
V
RA
Java Oxygen.lnk’, ‘Eclipse Jee Oxygen.lnk’, ‘For the book.txt’, ‘Items for
SO
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’]
ES
SS
Illegal operations can raise exceptions. There are plenty of built-in
exceptions in Python that are raised when corresponding errors occur. We
A
can view all the built-in exceptions using the built-in local() function as
CL
print(dir(locals()['__builtins__']))
S
R'
follows:
SI
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
ES
tabs and spaces.
SystemError Raised when interpreter detects internal error.
SS
SystemExit Raised by sys.exit() function.
TypeError
A
Raised when a function or operation is applied
CL
to an object of incorrect type.
UnboundLocalError Raised when a reference is made to a local
S
during encoding.
UnicodeDecodeError Raised when a Unicode-related error occurs
U
during decoding.
SO
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:
ES
Here are few important points about the above-mentioned syntax −
SS
A single try statement can have multiple except statements. This is
A
useful when the try block contains statements that may throw different
CL
types of exceptions.
S
You can also provide a generic except clause, which handles any
R'
exception.
SI
code in the else-block executes if the code in the try: block does not raise
RA
an exception.
U
SO
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()
ES
types of Exceptions in Python, Variables can be supplied to the Exceptions
to capture the essence of the encountered errors. Same error can occur of
SS
different causes, Arguments helps us identify the specific cause for an
A
error using the except clause.
CL
It can also be used to trap multiple exceptions, by using a variable
to follow the tuple of Exceptions.
S
R'
Example 1:
U
SO
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:
ES
raise(MyError("Some Error Data"))
SS
# Value of Exception is stored in error
A
CL
except MyError as Argument:
Output:
SI
class MyError(Exception):
# Constructor or Initializer
122
self.value = value
def __str__(self):
return(repr(self.value))
try:
raise(MyError(3*2))
Ouput:
ES
8.9 SUMMARY
SS
A
Files: Python supports file handling and allows users to handle files for
CL
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
S
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 {,}.
V
It ends the current line and expresses the interpreter a new one has
RA
a text file. In the end, these byte files are then translated into
SO
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
ES
SS
8.11 REFERENCES
A
CL
1. https://www.learnpython.org/
2. https://www.packtpub.com/tech/python
S
R'
3. https://www.softcover.io/read/e4cd0fd9/conversational-
python/ch6_files_excepts
SI
4. https://docs.python.org/3/library/exceptions.html
V
RA
5. https://www.tutorialspoint.com/python/python_exceptions.htm
6. https://www.w3schools.com/python/python_try_except.asp
U
SO
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
ES
9.0 OBJECTIVES
SS
A
Regular expressions are particularly useful for defining filters.
CL
Regular expressions contain a series of characters that define a
pattern of text to be matched—to make a filter more specialized, or
S
general.
R'
The regular expression ^AL[.]* searches for all items beginning with
SI
AL.
V
9.1 INTRODUCTION
RA
U
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.
ES
processors, such as Microsoft Word or OpenOffice, have find and find-
SS
and-replace features that can search based on regular expressions.
A
Regular expressions are huge time-savers, not just for software users but
CL
also for programmers.
S
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.”
ES
SS
A
CL
S
R'
SI
Quantifiers :
V
RA
U
SO
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:
ES
Search for the first white-space character in the string:
SS
import re
output:
RA
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)
ES
print(x)
SS
output:
[‘ai’ , ‘ai’]
A
CL
For example, here we have a list of e-mail addresses, and we want
S
all the e-mail addresses to be fetched out from the list, we use the method
R'
re.findall() in Python. It will find all the e-mail addresses from the list.
SI
The sub() function replaces the matches with the text of your choice:
Replace every white-space character with the number 9:
U
SO
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
ES
returns null.
SS
Example
Do a search that will return a Match Object:
A
CL
import re
S
x = re.search("ai", txt)
V
output:
U
SO
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)
ES
print(x.group())
SS
output:
Spain A
CL
Email validation example
S
R'
validate the Email from file as well from string by using Regular
SI
Expression:
V
RA
131
ES
SS
A
CL
S
R'
SI
V
RA
U
SO
9.7 SUMMARY
ES
4) Write a code to Validate Email by using regular expressions.
SS
A
CL
*****
S
R'
SI
V
RA
U
SO
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
ES
10.8 Data Hiding
SS
10.9 Summary
10.10 Unit End Exercise
A
CL
10.11 Bibliography
S
10.0 OBJECTIVES
R'
SI
oriented programming
Paradigm, that is, inheritance.
Classes also help in overriding any standard operator
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
ES
and from which it inherits the properties is alled base class or parent class.
It provides re-usability of the code.
SS
Polymorphism:
A
CL
Polymorphism is made by two words "poly" and "morphs". Poly means
many and Morphs means form, shape. It defines that one task can be
S
For example:
V
You have a class animal and all animals talk. But they talk differently.
RA
Here, the "talk" behavior is polymorphic in the sense and totally depends
on the animal. So, the abstract "animal" concept does not actually "talk",
U
but specific animals (like dogs and cats) have a concrete implementation
SO
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>
.
.
.
ES
<statement-N>
SS
Method:
A
CL
Method is a function that is associated with an object. In Python, method
is not unique to class instances. Any object type can have methods.
S
R'
Object:
SI
Object is an entity that has state and behavior. It may be anything. It may
V
be physical and logical. For example: mouse, keyboard, chair, table, pen
RA
etc.
U
methods. All functions have a built-in attribute __doc__, which returns the
doc string defined in the function source code.
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.
ES
Example:
SS
class Point:
A
def __init__(self, initX, initY):
CL
""" Create a new point at the given coordinates. """
self.x = initX
self.y = initY
S
R'
SI
def getX(self):
return self.x
V
RA
def getY(self):
return self.y
U
SO
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.
ES
Then the add_truck() method of class Vehicle is called and object of Truck
SS
class is passed as parameter.
Example: A
CL
class Vehicle:
S
R'
def __init__(self):
self.trucks = []
SI
V
self.trucks.append(truck)
U
class Truck:
SO
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:
ES
For the above class let us try to access all these attributes −
SS
classEmployee:
'Common base class for all employees' A
CL
empCount =0
S
self.name = name
SI
self.salary = salary
V
Employee.empCount +=1
RA
def displayCount(self):
print"Total Employee %d"%Employee.empCount
U
def displayEmployee(self):
SO
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.
ES
The child class or derived class inherits the features from the
SS
parent class, adding new features to it. It facilitates re-usability of code.
A
CL
Python Multilevel Inheritance:
140
ES
SS
A
CL
S
R'
SI
141
ES
SS
10.6 METHOD OVERRIDING
A
CL
Method overriding is an ability of any object-oriented
programming language that allows a subclass or child class to provide a
S
R'
Example:
class Parent():
# Constructor
def __init__(self):
self.value = "Inside Parent"
ES
class Child(Parent):
SS
# Constructor
def __init__(self): A
CL
self.value = "Inside Child"
S
def show(self):
SI
print(self.value)
V
RA
# Driver's code
obj1 = Parent()
U
obj2 = Child()
SO
obj1.show()
obj2.show()
Output:
Inside Parent
Inside Child
ES
class Base:
SS
def __init__(self):
# Protected member A
CL
self._a = 2
S
R'
class Derived(Base):
V
def __init__(self):
RA
# Calling constructor of
U
SO
# Base class
Base.__init__(self)
print("Calling protected member of base class: ")
print(self._a)
obj1 = Derived()
obj2 = Base()
ES
generally used to hide the data information from the user. It includes
internal object details such as data members, internal working. It
SS
maintained the data integrity and restricted access to the class member.
A
The main working of data hiding is that it combines the data and functions
CL
into a single unit to conceal data within a class. We cannot directly access
the data from outside the class.
S
R'
members as private so that no other class can access these data members.
V
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
ES
SS
It allows us to develop applications using an Object-Oriented
approach. In Python, we can easily create and use classes and objects. An
A
object-oriented paradigm is to design the program using classes and
CL
objects. The oops concept focuses on writing the reusable code.
S
R'
4) Write a python code to create animal class and in it create one instance
SO
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
ES
11.7 Unit End Exercise
SS
11.0 OBJECTIVES
A
CL
To use Multithreading
To achieve Multithreading
S
R'
11.1 INTRODUCTION
RA
U
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
ES
def cal_sqre(num): # define the cal_sqre function
SS
print(" Calculate the square root of the given number")
for n in num:
A
CL
time.sleep(0.3) # at each iteration it waits for 0.3 time
print(' Square is : ', n * n)
S
R'
SI
for n in num:
RA
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.
ES
SS
Below is a detailed list of those processes:
Classinpython.
V
RA
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
ES
for i in range(arg):
SS
print("running")
if __name__ == "__main__":
R'
thread.start()
thread.join()
V
print("thread finished...exiting")
RA
Output:
U
running
SO
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.
ES
If blocking is set to 1, the thread blocks and wait for the lock to be
SS
released.
A
The release() method of the new lock object is used to release the lock
CL
when it is no longer
required.
S
R'
import threading
SI
import time
class myThread (threading.Thread):
V
threading.Thread.__init__(self)
U
self.threadID = threadID
SO
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"
ES
When the above code is executed, it produces the following result −
SS
Starting Thread-1
Starting Thread-2
A
CL
Thread-1: Thu Mar 21 09:11:28 2013
Thread-1: Thu Mar 21 09:11:29 2013
S
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
ES
import threading
import time
SS
thread_exit_Flag = 0
A
CL
class sample_Thread (threading.Thread):
def __init__(self, threadID, name, q):
S
threading.Thread.__init__(self)
R'
self.threadID = threadID
SI
self.name = name
V
self.q = q
RA
def run(self):
print ("initializing " + self.name)
U
process_data(self.name, self.q)
SO
153
queueLock = threading.Lock()
workQueue = queue.Queue(10)
threads = []
threadID = 1
queueLock.release()
ES
SS
# Wait for the queue to empty
while not workQueue.empty():
pass
A
CL
# Notify threads it's time to exit
S
thread_exit_Flag = 1
R'
SI
t.join()
RA
Output:
SO
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:
ES
managing threads.
SS
Synchronization is needed to prevent mutual exclusion while
accessing shared resources. It directly leads to more memory and CPU
utilization. A
CL
Multithreading increases the complexity of the program, thus also
S
R'
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/
*****
ES
SS
A
CL
S
R'
SI
V
RA
U
SO
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
ES
12.0 OBJECTIVES
SS
A
Modules are simply a 'program logic' or a 'python script' that can be
CL
used for variety of applications or functions.
We can declare functions, classes etc in a module.
S
R'
The focus is to break down the code into different modules so that
SI
12.1 INTRODUCTION
RA
If you quit from the Python interpreter and enter it again, the
U
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
ES
print(math.pi)
SS
Output:
3.141592653589793
A
CL
12.2.2 import module_name.member_name:
S
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):
ES
File "C:/Users/GFG/Tuples/xxx.py", line 1, in
SS
import mathematics
ImportError: No module named 'mathematics'
A
CL
12.3 CREATING AND EXPLORING MODULES
S
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:
ES
>>> example.add(4,5.5)
9.5
SS
A
Python has tons of standard modules. You can check out the
full list of Python standard modules and their use cases. These files are
CL
in the Lib directory inside the location where you installed Python.
S
ES
If Comrade Napoleon says it, it must be right.
[100, 200, 300]
SS
arg = quux
<__main__.Foo object at 0x02F101D0>
A
CL
Unfortunately, now it also generates output when imported as a
module:
S
>>>
R'
arg = quux
<mod.Foo object at 0x0169AD50>
U
SO
This is probably not what you want. It isn’t usual for a module
to generate output when it is imported.
ES
12.4 MATH MODULE
SS
Python math module is defined as the most famous
A
mathematical functions, which includes trigonometric functions,
CL
representation functions, logarithmic functions, etc. Furthermore, it
also defines two mathematical constants, i.e., Pie and Euler number,
S
etc.
R'
SI
3.141592653589793.
RA
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
ES
print('The given number (x) is :', number)
SS
print('e^x (using exp() function) is :', math.exp(number)-1)
Output:
A
CL
The given number (x) is : 0.05
e^x (using exp() function) is : 0.05127109637602412
S
math.pow(x,y)
R'
SI
raises a ValueError.
RA
Example
U
import math
SO
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)
ES
Output:
The absolute value is: 10.001
SS
math.factorial()
A
CL
This method returns the factorial of the given number x. If x is
not integral, it raises a ValueError.
S
R'
Example
SI
import math
number = math.factorial(7)
V
Output:
U
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()
ES
Example
SS
Hello Java Program for Beginners
A
# importing "random” module.
CL
import random
# We are using the choice() function to generate a random number fro
S
m
R'
Output:
U
random.shuffle()
Output:
The random number between 0 and 1 is : 0.4405576668981033
ES
12.6 TIME MODULE
SS
A
Python has defined a module, “time” which allows us to handle
CL
various operations regarding time, its conversions and representations,
which find its use in various applications in life. The beginning of time
S
is started measuring from 1 January, 12:00 am, 1970 and this very
R'
Operations on Time:
V
RA
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)
ES
3. asctime(“time”) :- This function takes a time attributed string
SS
produced by gmtime() and returns a 24 character string denoting
time.
A
CL
4. ctime(sec) :- This function returns a 24 character time string but
takes seconds as argument and computes time till mentioned
S
ti = time.gmtime()
# using asctime() to display time acc. to time mentioned
print ("Time calculated using asctime() is : ",end="")
print (time.asctime(ti))
# using ctime() to display time string using seconds
print ("Time calculated using ctime() is : ", end="")
print (time.ctime())
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
ES
# Python code to demonstrate the working of
SS
# sleep()
time.sleep(4)
SO
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
ES
1. https://docs.python.org/3/tutorial/modules.html
2. https://www.geeksforgeeks.org/import-module-python/
SS
3. https://realpython.com/python-modules-packages/#executing-a-
module-as-a-script
A
CL
4. https://www.programiz.com/python-programming/modules
S
5. https://www.javatpoint.com/python-math-module
R'
SI
V
RA
*****
U
SO
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
ES
4.Combobox
SS
5.Check Button
6.Radio Button
A
CL
7.Scroll bar
8.List box
S
9.Menubutton
R'
10.Spin Box
SI
11.Paned Window
V
13.4 Summary
U
13.5 Questions
SO
13.6 References
13.1 OBJECTIVES
13.2 INTRODUCTION
ES
The setup wizard should have started. Click Next as shown in figure
SS
below
A
CL
S
R'
SI
V
RA
U
SO
3.5 On the next screen, change the installation path if required. Click on
Next as shown in figure below
170
ES
SS
A
3.6 On the Next Screen, you can create a desktop shortcut if you want and
CL
click on “Next”
S
R'
SI
V
RA
U
SO
3.7 Choose the start menu folder. Keep selected Jetbrains and click on
“Install”
171
ES
SS
3.8 Wait for the Installation to finish
A
CL
S
R'
SI
V
RA
U
SO
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
ES
SS
3.10 After you click on “Finish”, the Following screen will appear
A
CL
S
R'
SI
V
RA
U
SO
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
ES
widget
3 bitmap It is used to set the bitmap to the graphical object
SS
specified so that, the label can represent the
A
graphics instead of text.
CL
4 bd It represents the width of the border. The default
is 2 pixels.
S
the widget.
8 height The height of the widget
U
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
ES
ttk.Label(win, text="A label").grid(column=0,row=0)
#start GUI
SS
win.mainloop()
A
After executing this program on pycharm using run command, the output
CL
of above code as shown below
S
R'
SI
V
RA
2 Button:
SO
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.
ES
10. Image It is set to the image displayed on the
button.
SS
11. justify It illustrates the way by which the
A
multiple text lines are represented. It is
CL
set to LEFT for left justification, RIGHT
for the right justification, and CENTER
S
horizontal direction.
13. Pady Additional padding to the button in the
V
vertical direction.
RA
RIDGE.
SO
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
ES
below
SS
A
CL
S
R'
SI
V
RA
3. Entry TextBox:
SO
1. The Entry widget is used to provide the single line text-box to the user
to accept a value from the user.
2. We can use this widget to accept the text strings from the user. It can
only be used for one line of text from the user.
3. For multiple lines of text, we must use the text widget.
4. Syntax
W=Entry(parent,options)
5. A list of possible options is given below
ES
10. Insertbackground It represents the color to use as
background in the area covered by the
SS
insertion cursor. This color will
A
normally override either the normal
CL
background for the widget.
11. insertbackground It represents the color to use as
S
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)
ES
action.grid(column=1,row=0)
SS
#Start GUI
win.mainloop() A
CL
Output
S
R'
SI
V
13.4 COMBOBOX
SO
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.
ES
4. syntax
W=checkbutton(master,options)
SS
5. A list of possible options is given below
A
CL
Sr.No Option Description
1. bitmap It displays an image (monochrome)
S
on the button.
R'
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:
ES
SS
A
CL
S
R'
SI
V
Output:
RA
U
SO
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
ES
of lines (not pixel).
6. highlightcolor It represents the color of the focus
SS
highlight when the widget has the
focus.
7. state A
It represents the state of the radio
CL
button. The default state of the
Radiobutton is NORMAL.
S
R'
radiobutton unresponsive.
V
radiobutton.
9. Textvariable It is of String type that represents
U
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()
ES
26. top.mainloop()
SS
Output:
A
CL
S
R'
SI
V
RA
U
SO
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
ES
5. Code snippet:
SS
from tkinter import *
A
CL
top = Tk()
sb = Scrollbar(top)
S
mainloop()
Output:
ES
MULTIPLE, EXTENDED.
3 width It represents the width of the widget in
SS
characters.
4 XscrollCommand It is used to let the user scroll the Listbox
A
horizontally.
CL
5 Yscrollcommand It is used to let the user scroll the Listbox
vertically.
S
R'
6. Code Snippet:
SI
top.geometry("200x250")
U
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
ES
SS
A
CL
S
R'
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")
ES
menubutton.grid()
SS
menubutton.menu = Menu(menubutton)
A
CL
menubutton["menu"]=menubutton.menu
S
menubutton.pack()
RA
top.mainloop()
U
SO
output
ES
spin = Spinbox(top, from_= 0, to = 25)
SS
spin.pack()
top.mainloop()
A
CL
S
R'
SI
V
RA
U
SO
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())
ES
b = int(e2.get())
leftdata = str(a+b)
SS
left.insert(1,leftdata)
A
CL
w1 = PanedWindow()
w1.pack(fill = BOTH, expand = 1)
S
R'
left = Entry(w1, bd = 5)
w1.add(left)
SI
V
w1.add(w2)
e1 = Entry(w2)
U
e2 = Entry(w2)
SO
w2.add(e1)
w2.add(e2)
bottom = Button(w2, text = "Add", command = add)
w2.add(bottom)
mainloop()
Output:
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.
ES
SS
5. Code Snippet
from tkinter import *
A
CL
from tkinter import messagebox
top = Tk()
S
top.geometry("100x100")
R'
top.mainloop()
V
RA
Output:
U
SO
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
ES
Q5 Compare and contrast between the listbox and combobox
SS
13.5 REFERENCES
A
CL
1. Python GUI programming Cookbook-Burkahard A Meier, Packt
Publication, 2nd Edition
S
R'
Useful Links
SI
1. https://www.javatpoint.com/python-tkinter
V
RA
U
*****
SO
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
ES
14.7 References
SS
14.1 OBJECTIVES
A
CL
At the end of this unit, the student will be able to
S
Describe about the message box, progress bar, canvas widget etc.
RA
14.2 INTRODUCTION
U
SO
192
14.3 LAYOUT MANAGEMENT-DESIGNING GUI
APPLICATION WITH PROPER LAYOUT
MANAGEMENT FEATURES
ES
SS
A
CL
S
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
ES
better way.
SS
1.5 buttons_frame.grid(column=0,row=7,padx=20,pady=40), with this
statement labelFrame gets some breathing space.
A
CL
S
R'
SI
V
RA
U
SO
194
Pseudocode for adding space around the labels
ES
SS
A
CL
Fig 4 Label Frame widget with Space
S
before the main loop displays them. So, instead of hardcoding values
SI
when we first create a widget, we can work on our layout and then
arrange spacing towards the end of our file, just before the GUI is
V
created.
RA
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
ES
4. Aligning the GUI widgets by embedding frames within frames:
SS
1.17 The dynamic behavior of Python and its GUI modules can create a
A
little bit of a challenge to really get our GUI looking the way we
CL
want. Here, we will embed frames within frames to get more control
of our layout. This will establish a stronger hierarchy among the
S
1.18 Here, we will create a top-level frame that will contain other frames
SI
and widgets. This will help us get our GUI layout just the way we
V
want.
RA
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
U
child of the main parent window and all controls will be the children
SO
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).
ES
SS
A
Next, we will modify the following controls to use mighty as the parent,
CL
replacing win. Here is an example of how to do this
S
R'
SI
V
RA
U
SO
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
ES
SS
A
CL
S
R'
Next, we will add a second menu item to the first menu that we
added to the menu bar
198
ES
SS
A
Fig 8 Menu item with Exit option
CL
Next, we will add a help functionalities to our existing menu
S
R'
SI
V
RA
U
SO
199
Fig 9 Menu item with Help option
ES
SS
A
CL
S
R'
SI
V
RA
200
Fig 10 Tabbed GUI
ES
SS
Tkinter automatically adds the missing row where we did not specify any
A
particular row.
CL
14.4 Look & Feel customization- Enhancing look & feel of
S
1.1 A message box is a pop-up window that gives feedback to the user. It
RA
ES
Fig 11 A Help Message box
SS
Next, transform the above code in to a warning message box pop-up
window, instead.
A
CL
S
R'
SI
V
RA
U
SO
202
Fig 13 A error message box
ES
1.5 So, why would we wish to create an independent message box? One
SS
reason is that we might customize our message boxes and reuse them
in several of our GUIs. Instead of having to copy and paste the same
code in to every python GUI we design.
A
CL
S
R'
SI
V
RA
U
SO
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
ES
same as what discussed in topic presented above.
SS
1.7 Here we create the main root window and give it a title
A
CL
S
R'
SI
V
RA
U
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
ES
SS
A
CL
S
R'
SI
Next, we will reduce the sixe of the spinbox widget, by adding following
code snippet
U
SO
spin=spinbox(mighty, from=0,to=10,width=5)
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)
ES
Fig 20 Spin box with border
SS
Here, we add functionality to the widget by creating a callback and linking
it to the control
A
CL
S
R'
SI
V
RA
U
SO
206
ES
Fig 22 Spinbox with small border width
SS
5. Relief, Sunken and raised appearance of widgets
A
1.10 We can control the appearance of our spinbox widgets by using a
CL
property that makes them appear in different sunken or raised
formats.
S
R'
1.11 We will add one more spinbox control to demonstrate the available
SI
207
3.8 Here are the available relief property options that can be set
ES
SS
A
CL
S
R'
SI
V
RA
208
ES
SS
A
CL
S
new class in our python module. Python allows us to place more than one
SI
can also leave it out, as we did in the AClass code example, because it is
the default for all Python classes.
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
ES
9. Adding a Progressbar to the GUI
SS
7.1 Progressbar is typically used to show the current status of a long-
running process.
A
CL
7.2 Add four buttons in to Label frame and set the label frame text
property to progressbar.
S
R'
7.3 We connect each of our four new buttons to a new callback function,
SI
210
ES
Fig 26 Progress Bar
SS
10. How to use the Canvas Widget:
A
CL
1.11.1 First, we will create a third tab in our GUI in order to isolate our
new code
S
R'
211
ES
SS
Fig 27 Canvas output
A
CL
14.5 SUMMARY
S
R'
bar, grid layout and other layout management and customized GUI
features.
V
RA
14.6 QUESTIONS
SO
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
ES
15.7 Storing and retrieving data from MySQL database.
SS
15.8 Summary
A
15.9 Questions
CL
15.10 References
S
15.0 OBJECTIVES
R'
SI
15.1 INTRODUCTION
ES
5. There is a free MySQL Community Edition available from the official
MySQL website. You can download and install it on your local PC
SS
from h:ttp://dev.mysql.com/downloads/.
A
6. In order to connect to MySQL, we first need to install a special Python
CL
connector driver. This driver will enable us to talk to the MySQL
server from Python.
S
R'
7. The driver is freely available on the MySQL website and comes with a
SI
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.
ES
SS
A
CL
S
R'
SI
V
RA
U
SO
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.
ES
code.
SS
a. # create dictionary to
A
hold connection info
CL
dbConfig = {
b. 'user': <adminName>, # use your admin
S
# IP address of
V
localhost
RA
c. }
U
SO
10. We then import this module and unpack the credentials, as we did
before.
ES
11. import GuiDBConfig
as guiConf # unpack
SS
dictionary credentials
conn =
A
CL
mysql.connect(**guiConf.dbConfig)
print(conn)
S
R'
12. Now that we know how to connect to MySQL and have administrator
SI
commands:
RA
conn =
mysql.connect(**guiConf.dbCon
fig) cursor = conn.cursor()
try:
cursor.execute("CREATE DATABASE {} DEFAULT CHARACTER
SET 'utf8'".
format(GUIDB))
except mysql.Error as err:
print("Failed to create DB: {}".format(err))
conn.close()
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
ES
as mysql import
SS
GuiDBConfig as
guiConf
A
CL
# unpack dictionary credentials
conn = mysql.connect(**guiConf.dbConfig)
S
R'
cursor = conn.cursor()
SI
cursor.execute("SHOW
DATABASES")
V
RA
print(cursor.fetchall())
U
conn.close()
SO
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
ES
SS
A
CL
S
R'
SI
V
1. 2. import mysql.connector
U
SO
output:
ES
SS
A
CL
S
R'
ES
SS
A
CL
S
R'
SI
3. Insert Operation:
1. The INSERT INTO statement is used to add a record to the table. In
U
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()
ES
SS
A
CL
S
R'
SI
V
RA
U
SO
222
#Create the connection object
ES
print(cur.rowcount,"records inserted!")
SS
except:
myconn.rollback()
myconn.close() A
CL
S
R'
SI
V
RA
U
SO
223
15.5 USING THE UPDATE COMMAND
ES
10. except:
SS
11. myconn.rollback()
12. myconn.close()
A
CL
S
R'
SI
V
RA
U
SO
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")
ES
cur.execute("delete from Employee where id = 110")
myconn.commit()
SS
except:
A
CL
myconn.rollback()
myconn.close()
S
R'
MYSQL DATABASE.
V
RA
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
U
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()
ES
asswd = "google",database = "PythonDB")
4. #creating the cursor object
SS
5. cur = myconn.cursor()
6. try:
A
CL
7. #Reading the Employee data
8. cur.execute("select name, id, salary from Employee")
S
R'
14. except:
SO
15. myconn.rollback()
16. myconn.close()
226
15.8 SUMMARY
15.9 QUESTIONS
15.10 REFERENCES
ES
Publication, 2nd Edition.
SS
*****
A
CL
S
R'
SI
V
RA
U
SO
227