0% found this document useful (0 votes)
5 views198 pages

Python Complete Course Material

The document provides an overview of Python, highlighting its popularity and versatility in various applications such as web development, data analysis, and machine learning. It serves as a comprehensive guide for beginners, covering installation, features, programming concepts, and practical examples. The content includes detailed sections on Python's syntax, data types, control flow, and object-oriented programming.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views198 pages

Python Complete Course Material

The document provides an overview of Python, highlighting its popularity and versatility in various applications such as web development, data analysis, and machine learning. It serves as a comprehensive guide for beginners, covering installation, features, programming concepts, and practical examples. The content includes detailed sections on Python's syntax, data types, control flow, and object-oriented programming.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

ABSTRACT

Python is a popular programming language.


Thousands of companies have built their websites
with Python, including Google, Facebook, Dropbox,
Instagram, and Reddit. Python is used for all sorts of
things like building websites, web scraping, data
analysis, machine learning, and natural language
processing. The Python language is designed to be
easy to read without sacrificing power, which makes
it an excellent language for beginners to learn. This

PYTHON Document includes required information for


beginners to learn Python language.

AJITH KUMAR J(Bangalore)


Python Course
1
PYTHON

Introduction to Python...................................................................................................... 8
Installing Python: ..................................................................................................................... 8
Step 1: Download the Python 3 Installer ................................................................................... 8
Step 2: Run the Installer ........................................................................................................... 8
Features of Python: .................................................................................................................. 9
Python- Easy to Learn and Use .................................................................................................................. 9
Python - Expressive Language ................................................................................................................... 9
Python - Interpreted Language.................................................................................................................. 9
Python - Cross-platform Language ............................................................................................................ 9
Python - Free and Open Source ............................................................................................................... 10
Python - Large Standard Library .............................................................................................................. 10
Python - Extensible .................................................................................................................................. 10
Python -GUI Programming Support ......................................................................................................... 10
Python - Object-Oriented Language ........................................................................................................ 10
Python - Dynamically Typed .................................................................................................................... 10

Top 10 Programming Languages: ............................................................................................ 11


Best programming Languages for Beginners: ........................................................................... 11
First Python Program:............................................................................................................. 12
Python Identifiers................................................................................................................... 12
Reserved Words/ Key Words: ................................................................................................. 13
Indentation: ........................................................................................................................... 13
Multi-Line Statements: ........................................................................................................... 14
Quotation in Python ............................................................................................................... 14
Comments in Python .............................................................................................................. 15
Single Line Comment ............................................................................................................................... 15
Multi Line Comment ................................................................................................................................ 15
Multiple Statements on a Single Line ...................................................................................................... 16

Python 3 – Types and Operators ..................................................................................... 17


Assigning Values to Variables ................................................................................................. 17
Multiple Assignment .............................................................................................................. 17
Standard Data Types .............................................................................................................. 18
Python Numbers .................................................................................................................... 18
Python Strings ........................................................................................................................ 20
Python Lists ........................................................................................................................... 21
Python Tuples ........................................................................................................................ 22
Python Dictionary .................................................................................................................. 24
Data Type Conversion............................................................................................................. 25
Implicit Type Conversion: ........................................................................................................................ 25
Explicit Type Conversion .......................................................................................................................... 27

PYTHON AJITH KUMAR J(BANGALORE)


2
PYTHON

Python 3 – Basic Operators ............................................................................................. 28


Python Arithmetic Operators .................................................................................................. 28
Python Comparison Operators ................................................................................................ 29
Python Assignment Operators ................................................................................................ 30
Python Bitwise Operators ....................................................................................................... 31
Python Logical Operators ....................................................................................................... 32
Python Membership Operators .............................................................................................. 32
Python Identity Operators ...................................................................................................... 33
Python Operators Precedence ................................................................................................ 34
Python 3 – Program Flow Control ................................................................................... 36
Conditional blocks using if, else and elif .................................................................................. 36
IF Statement: ........................................................................................................................................... 36
IF…ELSE Statements................................................................................................................................. 37
Elif statement: ......................................................................................................................................... 37
Nested IF Statements .............................................................................................................................. 38
Loops in Python...................................................................................................................... 39
for Loop : ................................................................................................................................................. 39
while Loop : ............................................................................................................................................. 43
Nested Loops: .............................................................................................................................................. 45
Infinite loops: ............................................................................................................................................... 46
Loop Manipulations: .................................................................................................................................... 47
break statement: ..................................................................................................................................... 47
continue statement ................................................................................................................................. 48
pass statement ........................................................................................................................................ 49
pass statement vs comment ............................................................................................................... 49

Python 3 – String, List and Dictionary Manipulations ...................................................... 50


Strings ................................................................................................................................... 50
Creating a String ...................................................................................................................................... 50
Accessing characters in Python ............................................................................................................... 51
Deleting/Updating from a String ............................................................................................................. 52
Escape Sequencing in Python .................................................................................................................. 54
String Formatting Operator(%) ................................................................................................................ 55
Concatenation and repetition ................................................................................................................. 56
The in operator ........................................................................................................................................ 56
The format() Method for Formatting Strings .......................................................................................... 57
Built-in String Methods............................................................................................................................ 58
String capitalize() Method ................................................................................................................... 58
String isalnum() Method ..................................................................................................................... 61
String isalpha() Method....................................................................................................................... 61
String isdigit() Method ........................................................................................................................ 62
String islower() Method ...................................................................................................................... 62
String isnumeric() Method .................................................................................................................. 63
String isspace() Method ...................................................................................................................... 63
String istitle() Method ......................................................................................................................... 64
String join() Method ............................................................................................................................ 64

PYTHON AJITH KUMAR J(BANGALORE)


3
PYTHON

String len() Method ............................................................................................................................. 65


String max() Method ........................................................................................................................... 65
String min() Method ............................................................................................................................ 66
String replace() Method ...................................................................................................................... 66

Lists ....................................................................................................................................... 67
Creating a List .......................................................................................................................................... 67
Adding Elements to a List ........................................................................................................................ 68
Accessing elements from the List ............................................................................................................ 70
Removing Elements from the List ............................................................................................................ 71
Slicing of a List ......................................................................................................................................... 73
Basic List Operations ............................................................................................................................... 74
Built-in List Functions and Methods ........................................................................................................ 75
List len( ) method ................................................................................................................................ 75
List max( ) method .............................................................................................................................. 75
List min( ) method ............................................................................................................................... 76
List list( ) method ................................................................................................................................ 76
List append( ) method ......................................................................................................................... 77
List count( ) method ............................................................................................................................ 77
List extend ( ) method ......................................................................................................................... 78
List index ( ) method............................................................................................................................ 78
List insert ( ) method ........................................................................................................................... 79
List pop( ) method ............................................................................................................................... 79
List remove ( ) method ........................................................................................................................ 80
List reverse ( ) method ........................................................................................................................ 80
List sort ( ) method .............................................................................................................................. 81

Tuples .................................................................................................................................... 82
Creating a Tuple ....................................................................................................................................... 82
Concatenation of Tuples .......................................................................................................................... 83
Slicing of Tuple......................................................................................................................................... 84
Deleting a Tuple ....................................................................................................................................... 85
Built-in tuple Methods ............................................................................................................................. 86
Tuple len( ) method ............................................................................................................................. 86
Tuple max( ) method ........................................................................................................................... 86
Tuple min( ) method ........................................................................................................................... 87
Tuple tuple( ) method ......................................................................................................................... 87

Dictionary .............................................................................................................................. 88
Creating a Dictionary ............................................................................................................................... 88
Adding Elements to a Dictionary ............................................................................................................. 89
Accessing elements from a Dictionary .................................................................................................... 90
Removing Elements from Dictionary ....................................................................................................... 91
Properties of Dictionary Keys .................................................................................................................. 92
Built-in Dictionary Functions & Methods ................................................................................................ 93
Dictionary len() Method ...................................................................................................................... 93
Dictionary str() Method....................................................................................................................... 93
Dictionary copy() Method ................................................................................................................... 94
Dictionary get() Method ...................................................................................................................... 94
Dictionary items() Method .................................................................................................................. 95
Dictionary keys() Method .................................................................................................................... 95
Dictionary update() Method ............................................................................................................... 96
Dictionary values() Method................................................................................................................. 96

PYTHON AJITH KUMAR J(BANGALORE)


4
PYTHON

Python Date and Time ............................................................................................................ 97


Python 3 – Functions, Modules and Packages ............................................................... 103
Functions...................................................................................................................... 103
Types of Functions ............................................................................................................... 103
Python Built-in functions ........................................................................................................................... 103
Python abs() ...................................................................................................................................... 103
Python input() ................................................................................................................................... 103
Python len() ....................................................................................................................................... 105
Python pow() ..................................................................................................................................... 105
Python User-defined Functions ................................................................................................................. 106
Function definition ............................................................................................................................ 106
Calling a function in Python: ............................................................................................................. 107

Scope and Lifetime of variables ............................................................................................ 108


Pass by Reference vs Value ................................................................................................... 109
Function Arguments................................................................................................................................... 109
Required Arguments.............................................................................................................................. 109
Keyword Argument................................................................................................................................ 110
Default Arguments ................................................................................................................................ 110
Variable-length Arguments ................................................................................................................... 111

Modules ....................................................................................................................... 112


Create a Module .................................................................................................................................... 112
Use of Module ....................................................................................................................................... 112
Re-naming a Module ............................................................................................................................. 112
Built – in Modules .................................................................................................................................. 113
Using the dir() Function ......................................................................................................................... 113
Import from Module .............................................................................................................................. 113

Packages ...................................................................................................................... 113


Importing module from a package ........................................................................................................ 114

Files ............................................................................................................................. 116


Opening a file ....................................................................................................................... 116
Closing a file ......................................................................................................................... 117
Writing into files .................................................................................................................. 118
Reading from files ................................................................................................................ 119
Manipulating file pointer using seek() ................................................................................................... 119

Directory in Python ....................................................................................................... 120


Get Current Directory ........................................................................................................... 120
Changing Directory ............................................................................................................... 121
List Directories and Files ....................................................................................................... 121
Making a New Directory ....................................................................................................... 121
Renaming a Directory or a File .............................................................................................. 121
Removing Directory or File ................................................................................................... 122

PYTHON AJITH KUMAR J(BANGALORE)


5
PYTHON

Object Oriented programming - OOPs ........................................................................... 123


Overview of OOP Terminology.............................................................................................. 123
Class: ...................................................................................................................................................... 123
Data member ......................................................................................................................................... 123
Function overloading: ............................................................................................................................ 123
Instance variable ................................................................................................................................... 123
Inheritance: ........................................................................................................................................... 123
Instance: ................................................................................................................................................ 123
Instantiation: ......................................................................................................................................... 123
Method: ................................................................................................................................................. 123
Object: ................................................................................................................................................... 123
Operator overloading ............................................................................................................................ 123

Creating Classes ................................................................................................................... 123


Creating Instance Objects ..................................................................................................... 124
Accessing Attributes ............................................................................................................. 125
Built-in class Attributes ........................................................................................................ 126
Destroying Objects ............................................................................................................... 127
Inheritance .......................................................................................................................... 128
Overriding Methods ............................................................................................................. 130
Method Overloading: NOT SUPPORTED IN PYTHON .............................................................. 131
Overloading Operators ......................................................................................................... 132
Overloading binary + operator in Python .............................................................................................. 132

Data Hiding .......................................................................................................................... 134


Regular Expression ....................................................................................................... 136
match function ..................................................................................................................... 137
search function .................................................................................................................... 138
[Link]() ............................................................................................................................ 140
Search and Replace .............................................................................................................. 140
Regular Expression Patterns ................................................................................................. 141
Regular Expression Examples ................................................................................................ 141
Literal Characters:.................................................................................................................................. 141
Character classes: .................................................................................................................................. 141

Exception Handling....................................................................................................... 142


Standard Exceptions ............................................................................................................. 142
Assertions in Python............................................................................................................. 143
What is Exception? ............................................................................................................... 146
Handling an Exception .......................................................................................................... 146
The except clause with no Exceptions ................................................................................... 148

PYTHON AJITH KUMAR J(BANGALORE)


6
PYTHON

The except clause with multiple exceptions .......................................................................... 149


The try-finally clause ............................................................................................................ 149
Argument of an Exception .................................................................................................... 151
Raising an Exception............................................................................................................. 152
User-Defined Exception ........................................................................................................ 152
Python3 – Database Interaction.................................................................................... 155
SQLite database connection using python ............................................................................. 155
SQLite3 Cursor ....................................................................................................................................... 155

Create Database ................................................................................................................... 155


Create Table......................................................................................................................... 156
Insert into Table ................................................................................................................... 157
Update and Delete Table ...................................................................................................... 158
Select statement .................................................................................................................. 158
Fetch all Data ......................................................................................................................................... 159

Commit and Rollback ........................................................................................................... 160


GUI Programming ........................................................................................................ 161
Tkinter Programming ........................................................................................................... 161
Tkinter Widgets.................................................................................................................... 162
Tkinter Button ....................................................................................................................................... 162
Tkinter Canvas: ...................................................................................................................................... 163
Tkinter Checkbuttton............................................................................................................................. 165
Tkinter Entry .......................................................................................................................................... 166
Tkinter Frame ........................................................................................................................................ 167
Tkinter Label .......................................................................................................................................... 168
Tkinter Listbox ....................................................................................................................................... 169
Tkinter Menubutton .............................................................................................................................. 170
Tkinter Menu ......................................................................................................................................... 171
Tkinter Message .................................................................................................................................... 174
Tkinter Radiobutton .............................................................................................................................. 175
Tkinter Scrollbar .................................................................................................................................... 176
Tkinter Text............................................................................................................................................ 177
Tkinter LabelFrame ................................................................................................................................ 179
Tkinter tkMessageBox ........................................................................................................................... 180
Tkinter Colors ........................................................................................................................................ 181
Tkinter Fonts .......................................................................................................................................... 181

Color Game – Project .................................................................................................... 183


Scenario: .............................................................................................................................. 183
Code: ................................................................................................................................... 183
Catching the Ball Game ................................................................................................ 188
Scenario: .............................................................................................................................. 188

PYTHON AJITH KUMAR J(BANGALORE)


7
PYTHON

Approach: ............................................................................................................................ 188


Code: ................................................................................................................................... 189

PYTHON AJITH KUMAR J(BANGALORE)


8
PYTHON

Introduction to Python

Installing Python:

Step 1: Download the Python 3 Installer

1. Open a browser window and navigate to the Download page for


Windows at [Link].
2. Underneath the heading at the top that says Python Releases for Windows, click on
the link for the Latest Python 3 Release - Python 3.x.x. (As of this writing, the latest
is Python 3.6.5.)
3. Scroll to the bottom and select either Windows x86-64 executable installer for 64-bit
or Windows x86 executable installer for 32-bit.

Step 2: Run the Installer


Once you have chosen and downloaded an installer, simply run it by double-clicking on the
downloaded file. A dialog should appear that looks something like this:

Then just click Install Now. That should be all there is to it. A few minutes later you should
have a working Python 3 installation on your system.

PYTHON AJITH KUMAR J(BANGALORE)


9
PYTHON

Features of Python:

Python- Easy to Learn and Use


Python is very easy to code. Compared to other popular languages like C, C++ and JAVA, it
is easier to code in Python. Anyone can learn Python syntax in a few hours. Although it is
safe, mastering Python requires learning all its advanced concepts, packages and modules. It
takes time. Therefore, it is easy to program.

Python - Expressive Language


Suppose we have two languages, X and Y, and all the programs that can be done in X can be
done in Y using local transformations. However, there are some programs that can be done in
Y, but not in X, using local transformations. So, Y is said to be more expressive than X. Python
provides us with many constructions that help us focus on the solution instead of syntax.

Python - Interpreted Language


If you are familiar with languages like C, C ++ or Java, you must first compile it and then run
it. But in Python it is not necessary to compile it. Internally, the source code becomes an
immediate form called bytecode. Therefore, all you need to do is run your Python code without
worrying about linking to libraries and other things.

By interpretation we mean that the source code is executed line by line, and not all at once.

Python - Cross-platform Language


Let's say you wrote a Python code for your Windows machine. Now, if you want to run it on
Linux, Unix and Macintosh, you do not need to make any changes. In other words, you can

PYTHON AJITH KUMAR J(BANGALORE)


10
PYTHON

take a code and run it on any machine, it is not necessary to write a different code for different
machines. This makes Python a portable language.

Python - Free and Open Source


The Python language is available for free on the official Python website. And it's open source.
Means it’s source code is available to the public. You can download it, change it, use it. That's
why it's open source.

Python - Large Standard Library


Python has a large and extensive library and offers a wide set of modules and functions for
rapid application development.

Python - Extensible
We can write some of our Python codes in other languages such as C, C ++. This makes
Python an extensible language, which means, it can be extended to other languages.

Python -GUI Programming Support


We can develop GUI (Graphical user interfaces) applications using Python.

Python - Object-Oriented Language


It is said that a programming language that can model the real world is object-oriented. Python
focuses on objects and combines data and functions. Python supports procedural and object-
oriented programming, which is one of the key features of Python. It also supports multiple
inheritance, unlike Java.

Python - Dynamically Typed


Python is a dynamically typed language. Means the type for a value is decided at runtime, not
in advance. It is not necessary to specify the type of data when declaring it.

PYTHON AJITH KUMAR J(BANGALORE)


11
PYTHON

Top 10 Programming Languages:

Best programming Languages for Beginners:

PYTHON AJITH KUMAR J(BANGALORE)


12
PYTHON

First Python Program:

print(“Hello Python”)

This produces the following result:

Hello Python

Python Identifiers

A Python identifier is a name used to identify a variable, function, class, module or other object.
An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more
letters, underscores and digits (0 to 9).

Python does not allow punctuation characters such as @, $, and % within identifiers. Python
is a case sensitive programming language. Thus, Newhorizon and newhorizon are two
different identifiers in Python.

Here are naming conventions for Python identifiers-

 Class names start with an uppercase letter. All other identifiers start with a lowercase letter.

 Starting an identifier with a single leading underscore indicates that the identifier is private.

 Starting an identifier with two leading underscores indicates a strong private identifier.

 If the identifier also ends with two trailing underscores, the identifier is a language defined
special name.

PYTHON AJITH KUMAR J(BANGALORE)


13
PYTHON

Reserved Words/ Key Words:

These are reserved words and you cannot use them as constants or variables or any other
identifier names. All the Python keywords contain lowercase letters only.

Indentation:
# Python program showing indentation

college = 'New Horizon'


if college == 'New Horizon ':
print('Welcome to New Horizon
college')
else:
print('retype the college name.')
print('All set !')

This produces the following result:

Welcome to New Horizon college


All set !

PYTHON AJITH KUMAR J(BANGALORE)


14
PYTHON

Multi-Line Statements:
Statements in Python typically end with a new line. Python, however, allows the use of the line
continuation character (\) to denote that the line should continue.
For example:

total = a + \
b+\
c

The statements contained within the [], {}, or () brackets do not need to use the line continuation
character.
For example:

Days = [ 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday' ]

Quotation in Python
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long
as the same type of quote starts and ends the string. The triple quotes are used to span the string
across multiple lines.
For example, all the following are legal:

word = 'word'

sentence = "This is a sentence."

paragraph = """This is a paragraph. It is made up of multiple lines and sentences."""

PYTHON AJITH KUMAR J(BANGALORE)


15
PYTHON

Comments in Python

Single Line Comment


Comments are for developers. They describe parts of the code where necessary to facilitate
the understanding of programmers, including yourself.

To write a comment in Python, simply put the hash mark # before your desired comment:

# This is a comment

Because comments do not execute, when you run a program you will not see any indication of
the comment there. Comments are in the source code for humans to read, not for computers to
execute.

In a “Hello, World!” program, a comment may look like this:

[Link]
# Print “Hello, World!” to console
print("Hello, World!")

Multi Line Comment


Unfortunately, Python doesn’t have a way to write multiline comments as you can in
languages such as C, Java, and Go:

# So you can't
just do this
in python

In the above example, the first line will be ignored by the program, but the other lines will
raise a Syntax Error.

Another thing you can do is use multiline strings by wrapping your comment inside a set of
triple quotes:

"""
If I really hate pressing `enter` and
typing all those hash marks, I could
just do this instead
"""

This is like multiline comments in Java, where everything enclosed in the triple quotes will
function as a comment.

PYTHON AJITH KUMAR J(BANGALORE)


16
PYTHON

Multiple Statements on a Single Line


The semicolon ( ; ) allows multiple statements on a single line given that no statement starts a
new code block. Here is a sample snip using the semicolon.

a = 5; b = 6; print(a); print(b)

PYTHON AJITH KUMAR J(BANGALORE)


17
PYTHON

Python 3 – Types and Operators


Variables are reserved memory locations to store values. It means that when you create a
variable, you reserve some space in the memory.
Based on the data type of a variable, the interpreter allocates memory and decides what can be
stored in the reserved memory. Therefore, by assigning different data types to the variables,
you can store integers, decimals or characters in these variables.

Assigning Values to Variables


Python variables do not need explicit declaration to reserve memory space. The declaration
happens automatically when you assign a value to a variable. The equal sign (=) is used to
assign values to variables. The operand to the left of the = operator is the name of the variable
and the operand to the right of the = operator is the value stored in the variable.
For example-

regNo = 36 # An integer assignment


avg_marks = 96.9 # A floating point
name = "John" # A string
print (regNo)
print (avg_marks)
print (name)

This produces the following result :

36
96.9
John

Multiple Assignment
Python allows you to assign a single value to several variables simultaneously.
For example-

var1 = var2 = var3 = 6

PYTHON AJITH KUMAR J(BANGALORE)


18
PYTHON

You can also assign multiple objects to multiple variables.

regNo, avg_marks, name = 36, 96.9, “John”

Here, one integer object, one floating object with values 36 and 96.9 are assigned to the
variables regNo and avg_marks respectively, and one string object with the value "john" is
assigned to the variable name.

Standard Data Types


The data stored in memory can be of many types. For example, a person's age is stored as a numeric
value and his or her address is stored as alphanumeric characters. Python has various standard data
types that are used to define the operations possible on them and the storage method for each of
them.

Python has five standard data types-

 Numbers

 String

 List

 Tuple

 Dictionary

Python Numbers

Number data types store numeric values. Number objects are created when you assign a value
to them.
For example:

a=1
b=2
c=3

PYTHON AJITH KUMAR J(BANGALORE)


19
PYTHON

You can also delete the reference to a number object by using the del statement. The syntax
of the del statement is –

del var1[,var2[,var3[....,varN]]]]

You can delete a single object or multiple objects by using the del statement.
For example:

del var
del var_a, var_b

Python supports three different numerical types :


 int (signed integers)
 float (floating point real values)
 complex (complex numbers)
All integers in Python 3 are represented as long integers. Hence, there is no separate number
type as long.
Here are some examples of numbers:

Data Type int float complex

Examples 3 6.3 3.69j

Examples -336 -23.9 9.322e-36j

Examples -0x260 -32.54e100 3e+26j

A complex number consists of an ordered pair of real floating-point numbers denoted by


x + yj, where x and y are real numbers and j is the imaginary unit.

PYTHON AJITH KUMAR J(BANGALORE)


20
PYTHON

Python Strings

Strings in Python are identified as a contiguous set of characters represented in the quotation
marks. Python allows either pair of single or double quotes. Subsets of strings can be taken
using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string
and working their way from -1 to the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition
operator.

str = 'Hello World!'


print (str) # Prints complete string
print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting from 3rd to 5th
print (str[2:]) # Prints string starting from 3rd character
print (str * 2) # Prints string two times
print (str + "TEST") # Prints concatenated string

This produces the following result :

Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

PYTHON AJITH KUMAR J(BANGALORE)


21
PYTHON

Python Lists

Lists are the most versatile of Python's compound data types. A list contains items separated
by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays
in C. One of the differences between them is that all the items belonging to a list can be of
different data type.
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes
starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is
the list concatenation operator, and the asterisk (*) is the repetition operator.
For example:

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]


tinylist = [123, 'john']
print (list) # Prints complete list
print (list[0]) # Prints first element of the list
print (list[1:3]) # Prints elements starting from 2nd till 3rd
print (list[2:]) # Prints elements starting from 3rd element
print (tinylist * 2) # Prints list two times
print (list + tinylist) # Prints concatenated lists

This produces the following result :

['abcd', 786, 2.23, 'john', 70.200000000000003]


abcd
[786, 2.23]
[2.23, 'john', 70.200000000000003]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john']

PYTHON AJITH KUMAR J(BANGALORE)


22
PYTHON

Python Tuples

A tuple is another sequence data type that is similar to the list. A tuple consists of a number of
values separated by commas. Unlike lists, however, tuples are enclosed within parenthesis.
The main difference between lists and tuples is- Lists are enclosed in brackets ( [ ] ) and their
elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot
be updated. Tuples can be thought of as read-only lists.
For example:

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )


tinytuple = (123, 'john')
print (tuple) # Prints complete tuple
print (tuple[0]) # Prints first element of the tuple
print (tuple[1:3]) # Prints elements starting from 2nd till 3rd
print (tuple[2:]) # Prints elements starting from 3rd element
print (tinytuple * 2) # Prints tuple two times
print (tuple + tinytuple) # Prints concatenated tuple

This produces the following result :

('abcd', 786, 2.23, 'john', 70.200000000000003)


abcd (786, 2.23)
(2.23, 'john', 70.200000000000003)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john')
['abcd', 786, 2.23, 'john', 70.200000000000003]

PYTHON AJITH KUMAR J(BANGALORE)


23
PYTHON

The following code is invalid with tuple, because we attempted to update a tuple, which is not
allowed. Similar case is possible with lists :

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )


list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list[2] = 1000 # Valid syntax with list

PYTHON AJITH KUMAR J(BANGALORE)


24
PYTHON

Python Dictionary

Python's dictionaries are kind of hash-table type. They work like associative arrays or hashes
found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type,
but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python
object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using
square braces ([]).
For example:

dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print (dict['one']) # Prints value for 'one' key
print (dict[2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print ([Link]()) # Prints all the keys
print ([Link]()) # Prints all the values

This produces the following result :

This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']

Dictionaries have no concept of order among the elements. It is incorrect to say that the
elements are "out of order"; they are simply unordered.

PYTHON AJITH KUMAR J(BANGALORE)


25
PYTHON

Data Type Conversion


Sometimes, you may need to perform conversions between the built-in types. To convert
between types, you simply use the type-name as a function.
There are several built-in functions to perform conversion from one data type to another.
These functions return a new object representing the converted value.

Functions Description
float(x) Converts x to a floating-point number
str(x) Converts object x to a string representation.
tuple(s) Converts s to a tuple.
list(s) Converts s to a list.
hex(x) Converts an integer to a hexadecimal string.

The process of converting the value of one data type (integer, string, float, etc.) to another
data type is called type conversion. Python has two types of type conversion.

1. Implicit Type Conversion


2. Explicit Type Conversion

Implicit Type Conversion:

In Implicit type conversion, Python automatically converts one data type to another data type.
This process doesn't need any user involvement.

Let's see an example where Python promotes conversion of lower datatype (integer) to higher
data type (float) to avoid data loss.

num_int = 123
num_flo = 1.23
num_new = num_int + num_flo
print("datatype of num_int:",type(num_int))
print("datatype of num_flo:",type(num_flo))
print("Value of num_new:",num_new)
print("datatype of num_new:",type(num_new))

PYTHON AJITH KUMAR J(BANGALORE)


26
PYTHON

This produces the following result :

datatype of num_int: <class 'int'>


datatype of num_flo: <class 'float'>
Value of num_new: 124.23

datatype of num_new: <class 'float'>

Let's see another example where Python Addition of string(higher) data type and integer(lower)
datatype

num_int = 123
num_str = "456"
print("Data type of num_int:",type(num_int))
print("Data type of num_str:",type(num_str))
print(num_int+num_str)

This produces the following result :

Data type of num_int: <class 'int'>


Data type of num_str: <class 'str'>
Traceback (most recent call last):
File "[Link]", line 5, in <module>
print(num_int+num_str)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

PYTHON AJITH KUMAR J(BANGALORE)


27
PYTHON

Explicit Type Conversion

In Explicit Type Conversion, users convert the data type of an object to required data type. We
use the predefined functions like int(), float(), str(), etc to perform explicit type conversion.

This type conversion is also called typecasting because the user casts (change) the data type of
the objects.

Syntax :

(required_datatype)(expression)

Let's see an example where Python Addition of string and integer using explicit conversion.

num_int = 123
num_str = "456"
print("Data type of num_int:",type(num_int))
print("Data type of num_str before Type Casting:",type(num_str))
num_str = int(num_str)
print("Data type of num_str after Type Casting:",type(num_str))
num_sum = num_int + num_str
print("Sum of num_int and num_str:",num_sum)
print("Data type of the sum:",type(num_sum))

This produces the following result:

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'>

PYTHON AJITH KUMAR J(BANGALORE)


28
PYTHON

Python 3 – Basic Operators


Operators are the constructs, which can manipulate the value of operands. Consider the
expression 3 + 6 = 9. Here, 3 and 6 are called operands and + is called the operator.
Types of Operator
Python language supports the following types of operators-
 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators

Python Arithmetic Operators

Example:

a = 21; b = 10; c = 0; Output:


c=a+b

print ("Line 1 - Value of c is ", c) Line 1 - Value of c is 31


c=a-b

print ("Line 2 - Value of c is ", c ) Line 2 - Value of c is 11


c=a*b

print ("Line 3 - Value of c is ", c) Line 3 - Value of c is 210


c=a/b

print ("Line 4 - Value of c is ", c ) Line 4 - Value of c is 2.1


c=a%b

print ("Line 5 - Value of c is ", c) Line 5 - Value of c is 1


a = 2; b = 3; c = a**b;

print ("Line 6 - Value of c is ", c) Line 6 - Value of c is 8


a = 9; b = 2; c = a//b

print ("Line 7 - Value of c is ", c) Line 7 - Value of c is 4.0

PYTHON AJITH KUMAR J(BANGALORE)


29
PYTHON

Python Comparison Operators

These operators compare the values on either side of them and decide the relation among

them. They are also called Relational operators.

Example:

a = 21; b = 10; Output:


if ( a == b ):

print ("Line 1 - a is equal to b")

else: Line 1 - a is not equal to b


print ("Line 1 - a is not equal to b")

if ( a != b ):

print ("Line 2 - a is not equal to b")

else:

print ("Line 2 - a is equal to b") Line 2 - a is not equal to b

if ( a < b ):

print ("Line 3 - a is less than b" )

else:

print ("Line 3 - a is not less than b") Line 3 - a is not less than b

if ( a > b ):

print ("Line 4 - a is greater than b")

else: Line 4 - a is greater than b


print ("Line 4 - a is not greater than b")

PYTHON AJITH KUMAR J(BANGALORE)


30
PYTHON

#values of a and b swapped. a becomes 10, b becomes 21


a,b=b,a

if ( a <= b ): Output:
print ("Line 5 - a is either less than or equal to b")

else: Line 5 - a is either less than or


print ("Line 5 - a is neither less than nor equal to b") equal to b

if ( b >= a ):

print ("Line 6 - b is either greater than or equal to b")

else:

print ("Line 6 - b is neither greater than nor equal to b") Line 6 - b is either greater than
or equal to b

Python Assignment Operators

a = 21;b = 10;c = 0 Output:


c=a+b

print ("Line 1 - Value of c is ", c) Line 1 - Value of c is 31


c += a

print ("Line 2 - Value of c is ", c ) Line 2 - Value of c is 52


c *= a

print ("Line 3 - Value of c is ", c ) Line 3 - Value of c is 1092


c /= a

print ("Line 4 - Value of c is ", c ) Line 4 - Value of c is 52.0


c=2

c %= a

print ("Line 5 - Value of c is ", c) Line 5 - Value of c is 2


c **= a

print ("Line 6 - Value of c is ", c) Line 6 - Value of c is 2097152


c //= a

print ("Line 7 - Value of c is ", c) Line 7 - Value of c is 99864

PYTHON AJITH KUMAR J(BANGALORE)


31
PYTHON

Python Bitwise Operators

Bitwise operator works on bits and performs bit-by-bit operation. Pyhton's built-in function bin() can
be used to obtain binary representation of an integer number.

Example:

a = 60 # 60 = 0011 1100 Output:


b = 13 # 13 = 0000 1101

print ('a=',a,':',bin(a),'b=',b,':',bin(b)) a= 60 : 0b111100 b= 13 : 0b1101


c=0

c = a & b; # 12 = 0000 1100

print ("result of AND is ", c,':',bin(c)) result of AND is 12 : 0b1100

c = a | b; # 61 = 0011 1101

print ("result of OR is ", c,':',bin(c)) result of OR is 61 : 0b111101

c = a ^ b; # 49 = 0011 0001

print ("result of EXOR is ", c,':',bin(c)) result of EXOR is 49 : 0b110001

c = ~a; # -61 = 1100 0011

print ("result of COMPLEMENT is ", c,':',bin(c)) result of COMPLEMENT is -61 :

-0b111101
c = a << 2; # 240 = 1111 0000

print ("result of LEFT SHIFT is ", c,':',bin(c)) result of LEFT SHIFT is 240 :
0b11110000

c = a >> 2; # 15 = 0000 1111

print ("result of RIGHT SHIFT is ", c,':',bin(c)) result of RIGHT SHIFT is 15 :


0b111

PYTHON AJITH KUMAR J(BANGALORE)


32
PYTHON

Python Logical Operators

The following logical operators are supported by Python language.


Assume variable a holds True and variable b holds False then :
Operator Description Example
and Logical AND If both the operands are true (a and b) is False.
then condition becomes true.
or Logical OR If any of the two operands are (a or b) is True
non-zero then condition
becomes true. (a or b)
not Logical NOT Used to reverse the Not(a and b) is True.
logical state of its operand.

Python Membership Operators

Python’s membership operators test for membership in a sequence, such as strings, lists,

or tuples.

Operator Description Example


in Evaluates to true, if it finds a x in y, here in results in a 1 if x is
variable in the specified a member of sequence y.
sequence and false otherwise.

not in Evaluates to true, if it does not x not in y, here not in results in


find a variable in the specified a 1 if x is not a member of
sequence and false otherwise. sequence y.

Example:

a = 10;b = 20 Output:

list = [1, 2, 3, 4, 5 ]

if ( a in list ):

print ("Line 1 - a is available in the given list") Line 1 - a is not available in the
given list
else:

print ("Line 1 - a is not available in the given list")

if ( b not in list ):

print ("Line 2 - b is not available in the given list")


Line 2 - b is not available in the
else: given list
print ("Line 2 - b is available in the given list")

PYTHON AJITH KUMAR J(BANGALORE)


33
PYTHON

Python Identity Operators

Identity operators compare the memory locations of two objects.


Operator Description Example
is Evaluates to true if the variables x is y, here is results in 1 if id(x)
on either side of the operator equals id(y).
point to the same object and
false otherwise.
is not Evaluates to false if the x is not y, here is not results in 1
variables on either side of the if id(x) is not equal to id(y).
operator point to the same
object and true otherwise.

Example:
Output:

a = 20;b = 20;
Line 1 a= 20 : 1594701888 b= 20 :
print ('Line 1','a=',a,':',id(a), 'b=',b,':',id(b)) 1594701888

if ( a is b ):
print ("Line 2 - a and b have same identity") Line 2 - a and b have same identity

else:
print ("Line 2 - a and b do not have same identity")
if ( id(a) == id(b) ):
print ("Line 3 - a and b have same identity")
else: Line 3 - a and b have same identity

print ("Line 3 - a and b do not have same identity")


b = 30
print ('Line 4','a=',a,':',id(a), 'b=',b,':',id(b))
if ( a is not b ): Line 4 a= 20 : 1594701888 b= 30 :
1594702048
print ("Line 5 - a and b do not have same identity")
else:
print ("Line 5 - a and b have same identity")
Line 5 - a and b do not have same identitylist

PYTHON AJITH KUMAR J(BANGALORE)


34
PYTHON

Python Operators Precedence

The following table lists all the operators from highest precedence to the lowest.

Operator precedence affects the evaluation of an an expression.


For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because the operator * has higher
precedence than +, so it first multiplies 3*2 and then is added to 7.
Here, the operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom.

PYTHON AJITH KUMAR J(BANGALORE)


35
PYTHON

Example: Output:

a = 20;b = 10;c = 15;d = 5

print ("a:%d b:%d c:%d d:%d" % (a,b,c,d )) a:20 b:10 c:15 d:5

e = (a + b) * c / d #( 30 * 15 ) / 5

print ("Value of (a + b) * c / d is ", e)


Value of (a + b) * c / d is 90.0

e = ((a + b) * c) / d # (30 * 15 ) / 5

print ("Value of ((a + b) * c) / d is ", e)


Value of ((a + b) * c) / d is 90.0
e = (a + b) * (c / d) # (30) * (15/5)

print ("Value of (a + b) * (c / d) is ", e) Value of (a + b) * (c / d) is 90.0

e = a + (b * c) / d # 20 + (150/5)
Value of a + (b * c) / d is 50.0
print ("Value of a + (b * c) / d is ", e)

PYTHON AJITH KUMAR J(BANGALORE)


36
PYTHON

Python 3 – Program Flow Control


We often come across situations in which we need to divert or change the usual sequential flow
of execution. The flow control statements can be classified into Conditional Statements and
Iteration Statements.
The Conditional Statements selects a particular set of statements for execution depending upon
a specified condition.
While the Iteration Statements repeatedly executes a block of statements with respect to some
condition.

Conditional blocks using if, else and elif

IF Statement:

The IF statement is similar to that of other languages. The if statement contains a logical
expression using which the data is compared and a decision is made based on the result of the
comparison.

Syntax:

If the boolean expression evaluates to TRUE, then the block of


if expression: statement(s) inside the if statement is executed. In Python,
statement(s) statements in a block are uniformly indented after the : symbol.
If boolean expression evaluates to FALSE, then the first set of
code after the end of block is executed.

Example:
Let’s try a guess-a-number program. The computer picks a random number, the player tries to
guess, and the program tells them if they are correct. To see if the player’s guess is correct,
we need something new, called an if statement.

from random import randint


num = randint(1,10)
guess = int(input('Enter your guess: '))
if guess==num:
print('You got it!')

PYTHON AJITH KUMAR J(BANGALORE)


37
PYTHON

IF…ELSE Statements

An else statement can be combined with an if statement. An else statement contains a block
of code that executes if the conditional expression in the if statement resolves to 0 or a
FALSE value.

Syntax:

if expression:

statement(s)

else:

statement(s)

The guess-a-number game works, but it is pretty simple. If the player guesses wrong,
nothing happens. We can add else to the if statement as follows:
Example : Guessing a num:

from random import randint


num = randint(1,10)
guess = int(input('Enter your guess: '))
if guess==num:
print('You got it!')
else:
print('Sorry. The number is ', num)

Elif statement:

The elif statement allows you to check multiple expressions for TRUE and execute a block of
code as soon as one of the conditions evaluates to TRUE.

PYTHON AJITH KUMAR J(BANGALORE)


38
PYTHON

Syntax: Example:

if expression: grade = int(input('Enter your score: '))


statement(s) if grade>=90:
elif expression2: print('A')

statement(s) elif grade>=80:

elif expression3: print('B')


elif grade>=70:
statement(s)
print('C')
else:
elif grade>=60:
statement(s)
print('D'):
else:
print('F')

Nested IF Statements

There may be a situation when you want to check for another condition after a condition
resolves to true. In such a situation, you can use the nested if construct. In a nested if
construct, you can have an if...elif...else construct inside another if...elif...else construct.
Syntax: Example:

if expression1: if num%2==0:
statement(s) if num%3==0:
if expression2: print ("Divisible by 3 and 2")
statement(s) else:
elif expression3: print ("divisible by 2 not divisible by 3")
statement(s) else:
else: if num%3==0:
statement(s) print ("divisible by 3 not divisible by 2")
elif expression4: else:
statement(s) print ("not Divisible by 2 not divisible by 3")
else:
statement(s)

PYTHON AJITH KUMAR J(BANGALORE)


39
PYTHON

Loops in Python

A loop statement allows us to execute a statement or group of statements multiple times.


There are two types of loops in Python, for and while.

for Loop :

The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable
objects. Iterating over a sequence is called traversal.
Syntax:

for iterating_var in sequence:


statements(s)

Example:

# Program to find the sum of all numbers


stored in a list

# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
sum = 0
The sum is 48
# iterate over the list
for val in numbers:
sum = sum+val

# Output: The sum is 48


print("The sum is", sum)

PYTHON AJITH KUMAR J(BANGALORE)


40
PYTHON

# Program to illustrate
Output:
#Iterating over a list
print("List Iteration")
l = ["New", "Horizon", "BCA"] List Iteration
for i in l: New
Horizon
print(i) BCA
--------------------------------------------------------------- ---
# Iterating over a tuple (immutable)
print("\nTuple Iteration")
t = ("New", "Horizon", "BCA") Tuple Iteration
for i in t:
New
print(i) Horizon
BCA
---------------------------------------------------------------
# Iterating over a String
print("\nString Iteration")
s = "BCA"
String Iteration
for i in s :
B
print(i) C
# Iterating over dictionary A

print("\nDictionary Iteration")
d = dict()
d['xyz'] = 123
d['abc'] = 345
for i in d :
print("%s %d" %(i, d[i])) Dictionary Iteration

abc 345
xyz 123

# Python program to illustrate


# Iterating by index
list = ["New", "Horizon", "BCA"]
for index in range(len(list)): New
Horizon
print (list[index] ) BCA

# Python program to illustrate

PYTHON AJITH KUMAR J(BANGALORE)


41
PYTHON

# combining else with for Python


list = ["Python", "Is", "Best"] Is
Best
for index in range(len(list)):
print (list[index] ) Inside Else Block

else:
print ("Inside Else Block")

# Python program to illustrate


# Iterating list
my_list = ['one', 'two', 'three', 'four', 'five']
my_list_len = len(my_list) one
two
for i in range(0, my_list_len): three
four
print(my_list[i]) five

Python's range() Parameters


The range() function has two sets of parameters, as follows:
1) range(stop)
 stop: Number of integers (whole numbers) to generate, starting from zero.
Example: range(3) = [0, 1, 2].

2) range([start], stop[, step])


 start: Starting number of the sequence.
 stop: Generate numbers up to, but not including this number.
 step: Difference between each number in the sequence.
Note that:
 All parameters must be integers.
 All parameters can be positive or negative.
 range() (and Python in general) is 0-index based, meaning list indexes start at 0, not 1.
Example:
The syntax to access the first element of a list is mylist[0].
Therefore the last integer generated by range() is up to, but not including, stop.
For example range(0, 5) generates integers from 0 up to, but not including, 5.

PYTHON AJITH KUMAR J(BANGALORE)


42
PYTHON

Python's range() Function Examples:


0
# One parameter 1
for i in range(5): 2
3
print(i) 4
# Two parameters 3
for i in range(3, 6): 4
5
print(i)
4
# Three parameters 6
for i in range(4, 10, 2): 8

print(i)
# Going backwards 0
for i in range(0, -10, -2): -2
-4
print(i) -6
-8

Classical example : 99 Bottles of Beer on the Wall...


for i in range(99, 0, -1):
if i == 1:
print('1 bottle of beer on the wall, 1 bottle of beer!')
print('So take it down, pass it around, no more bottles of beer on the wall!')
elif i == 2:
print('2 more bottles of beer on the wall, 2 more bottles of beer!')
print('So take one down, pass it around, 1 more bottle of beer on the wall!')
else:
print('{0} bottles of beer on the wall, {0} bottles of beer!'.format(i))
print('So take it down, pass it around, {0} more bottles of beer on the
wall!'.format(i - 1))

99 bottles of beer on the wall, 99 bottles of beer!


So take it down, pass it around, 98 more bottles of beer on the wall!
98 bottles of beer on the wall, 98 bottles of beer!
So take it down, pass it around, 97 more bottles of beer on the wall!
. . . . .
3 bottles of beer on the wall, 3 bottles of beer!
So take it down, pass it around, 2 more bottles of beer on the wall!
2 more bottles of beer on the wall, 2 more bottles of beer!
So take one down, pass it around, 1 more bottle of beer on the wall!
1 bottle of beer on the wall, 1 bottle of beer!
So take it down, pass it around, no more bottles of beer on the wall!

PYTHON AJITH KUMAR J(BANGALORE)


43
PYTHON

while Loop :

A while loop statement in Python programming language repeatedly executes a target


statement as long as a given condition is true.
All the statements indented by the same number of character spaces after a programming
construct are considered to be a part of a single block of code.

Syntax:

while expression:
statement(s)

Example:

# Python program to illustrate


# while loop
count = 0 Hello Pyhton
Hello Pyhton
while (count < 3):
Hello Pyhton
count = count + 1
print("Hello Python")

Using else statement with while loops:


while loop executes the block until a condition is satisfied. When the condition becomes
false, the statement immediately after the loop is executed.
The else clause is only executed when your while condition becomes false. If you break out
of the loop, or if an exception is raised, it won’t be executed.

If else like this:

if condition:
# execute these statements
else:
# execute these statements

PYTHON AJITH KUMAR J(BANGALORE)


44
PYTHON

while loop like this are similar

while condition:
# execute these statements
else:
# execute these statements
Combining else with while

#Python program to illustrate combining else with while


count = 0
while (count < 3): Hello Python
Hello Python
count = count + 1 Hello Python
print("Hello Python") In Else Block

else:
print("In Else Block")

#Python program to illustrate combining if and else with while


temp = 0
while temp!=-1000:
temp = eval(input('Enter a temperature (-1000 to quit): '))
if temp!=-1000:
print('In Fahrenheit that is', 9/5*temp+32)
else:
print('Bye!')

Enter a temperature (-1000 to quit): 36


In Fahrenheit that is 96.8
Enter a temperature (-1000 to quit): 99
In Fahrenheit that is 210.20000000000002
Enter a temperature (-1000 to quit): -1000
Bye!

PYTHON AJITH KUMAR J(BANGALORE)


45
PYTHON

In Example : Guess a num we wrote a program that played a simple random number guessing
game. The problem with that program is that the player only gets one guess.
We can, in a sense, replace the if statement in that program with a while loop to create a
program that allows the user to keep guessing until they get it right.

#Python program to illustrate combining random with while


from random import randint
Guess the secret number: 3
secret_num = randint(1,10) Guess the secret number: 6
Guess the secret number: 8
guess = 0
Guess the secret number: 2
while guess != secret_num: You finally got it!

guess = int(input('Guess the secret number: '))


print('You finally got it!')

Nested Loops:

Python programming language allows to use one loop inside another loop. Following section
shows few examples to illustrate the concept.
Syntax :

for iterator_var in sequence: while expression:


for iterator_var in sequence: while expression:
statements(s) statement(s)
statements(s) statement(s)

# Python program to illustrate nested for loops in Python


for i in range(1, 5):
for j in range(i): 1
2 2
print(i, end=' ') 3 3 3
4 4 4 4
print()

PYTHON AJITH KUMAR J(BANGALORE)


46
PYTHON

Infinite loops:

When working with while loops, sooner or later will accidentally send Python into a never
ending loop.
Example 1:
i=0
while i<10:
print(i)

Example 2:
while True:
num = int(input("Enter an integer: "))
print("The double of",num,"is",2 * num)

Example 3:
List_words = ['the', 'end', 'is', 'never']
for word in List_words:
print(word)
List_words.append(word)

PYTHON AJITH KUMAR J(BANGALORE)


47
PYTHON

Loop Manipulations:

The Loop control statements change the execution from its normal sequence.

break statement:
The break statement is used for premature termination of the current loop. It brings control out of
the current loop. The break statement can be used to break out of a for or while loop before the
loop is finished.

# Python program to illustrate break with for loop in Python


for letter in 'Python':

if letter == 'h': Current Letter : P


Current Letter : y
break Current Letter : t

print ('Current Letter :', letter)

#Program that allows the user to enter up to 10 numbers.


#The user can stop early by entering a negative number.

for i in range(10):

num = int(input('Enter number: ')) Enter number: 3


Enter number: 6
if num<0: Enter number: 9
Enter number: -5
break

This could also be accomplished with a while loop.


i=0 Enter number: 2
num=1 Enter number: 6
Enter number: 8
while i<10 and num>0: Enter number: -7

num = int(input('Enter a number: '))

#Program to accomplish loop break using break


fruits = ["apple", "banana", "cherry"]

for x in fruits: apple


banana
print(x)

if x == "banana":

break

PYTHON AJITH KUMAR J(BANGALORE)


48
PYTHON

continue statement

The continue statement in Python returns the control to the beginning of the current loop. When
encountered, the loop starts next iteration without executing the remaining statements in the
current iteration. The continue statement is used to skip the rest of the code inside a loop for the
current iteration only. Loop does not terminate but continues with the next iteration.

# Python program to illustrate continue with for loop in Python


for letter in 'Python':

if letter == 'h': Current Letter : P


Current Letter : y
continue Current Letter : t
Current Letter : o
print ('Current Letter :', letter) Current Letter : n

# program to display only odd numbers


for num in [20, 11, 9, 66, 4, 89, 44]:
11
# Skipping the iteration when number is even 9
89
if num%2 == 0:

continue

# This statement will be skipped for all even numbers

print(num)

--------------------------------------------------------------------------------

# Program which doesn’t print banana


fruits = ["apple", "banana", "cherry"]

for x in fruits:
apple
if x == "banana": cherry

continue

print(x)

PYTHON AJITH KUMAR J(BANGALORE)


49
PYTHON

pass statement
It is used when a statement is required syntactically but you do not want any command or
code to execute. The pass statement is a null operation; nothing happens when it executes.
The pass statement acts as a placeholder and usually used when there is no need of code but
a statement is still required to make a code syntactically correct. For example, we want to
declare a function in our code but we want to implement that function in future, which means
we are not yet ready to write the body of the function. In this case we cannot leave the body
of function empty as this would raise error because it is syntactically incorrect, in such cases
we can use pass statement which does nothing but makes the code syntactically correct.

pass statement vs comment


You may be wondering that a python comment works like the pass statement as it does
nothing so we can use comment in place of pass statement.
Well, it is not the case, a comment is not a placeholder and it is completely ignored by the
Python interpreter while on the other hand pass is not ignored by interpreter, it says the
interpreter to do nothing.

# An empty loop
for letter in 'New Horion College':
Last Letter : e
pass
print ('Last Letter :', letter )

#If the number is even we are doing nothing and if it is odd then we are
displaying.
for num in [20, 11, 9, 66, 4, 89, 44]:
if num%2 == 0:
11
pass 9
89
else:
print(num)

# pass is just a placeholder for


# functionality to be added later.
sequence = {'p', 'a', 's', 's'}
for val in sequence:
pass

PYTHON AJITH KUMAR J(BANGALORE)


50
PYTHON

Python 3 – String, List and Dictionary Manipulations

Strings
A string is a sequence of characters. Python does not have a character data type, a single character is
simply a string with a length of 1. Square brackets can be used to access elements of the string.

Strings in Python can be created using single quotes or double quotes or even triple quotes.

Creating a String
# Python Program for Creation of String
# Creating a String with single Quotes
String1 = 'Welcome to the Python World'
print("String with the use of Single Quotes: ")
print(String1)

# Creating a String with double Quotes


String1 = "I'm a Programmer"
print("\nString with the use of Double Quotes: ")
print(String1)

# Creating a String with triple Quotes


String1 = '''I'm a Programmer and I live in a world of "Programming"'''
print("\nString with the use of Triple Quotes: ")
print(String1)

# Creating String with triple Quotes allows multiple lines


String1 = '''Programming
Is My
Life'''
print("\nCreating a multiline String: ")
print(String1)

PYTHON AJITH KUMAR J(BANGALORE)


51
PYTHON

Accessing characters in Python


In Python, individual characters of a String can be accessed by using the method of Indexing,
to access a range of characters in the String, method of slicing is used. Slicing in a String is
done by using a Slicing operator (colon). Indexing allows negative address references to
access characters from the back of the String, e.g. -1 refers to the last character, -2 refers to
the second last character and so on.

# Python Program to Access characters of String


String1 = "Hello World"
Initial String:
print("Initial String: ") Hello World
print(String1)

# Printing First character


print("\nFirst character of String is: ") First character of String is:
H
print(String1[0])

# Printing Last character


print("\nLast character of String is: ")
Last character of String is:
print(String1[-1]) d

# Printing 3rd to 9th character


print("\nSlicing characters from 3 to 9: ")
Slicing characters from 3 to 9:
print(String1[3:9]) lo Wor

# Printing characters between


#3rd and 3rd last character
print("\nSlicing characters between " +
Slicing characters between 3rd and 3rd
"3rd and 3rd last character: ") last character:
print(String1[2:-3]) llo Wo

PYTHON AJITH KUMAR J(BANGALORE)


52
PYTHON

Deleting/Updating from a String


In Python, Updating or deletion of characters from a String is not allowed. This will cause an
error because item assignment or item deletion from a String is not supported. Although
deletion of entire String is possible with the use of a built-in del keyword. This is because
Strings are immutable, hence elements of a String cannot be changed once it has been
assigned. Only new strings can be reassigned to the same name.

# Python Program to Update character of a String

String1 = "Hello, I'm a Programmer"


Initial String:
print("Initial String: ") Hello, I'm a Programmer

print(String1)

# Updating a character of the String Traceback (most recent call last):


File "[Link]", line 10, in <module>
String1[2] = 'p' String1[2] = 'p'
print("\n Updating character at 2nd Index: ") TypeError: 'str' object does not support
item assignment
print(String1)

# Python Program to Update entire String

String1 = "Hello, I'm a Programmer"


Initial String:
print("Initial String: ") Hello, I'm a Programmer
140403497794704
print(String1)
print(id(String1))

# Updating a String

String1 = "Welcome to the Python"


print("\n Updated String: ")
Updated String:
print(String1) Welcome to the Python
140403497843136
print(id(String1))

PYTHON AJITH KUMAR J(BANGALORE)


53
PYTHON

We can "update" an existing string by (re)assigning a variable to another string. The new
value can be related to its previous value or to a completely different string altogether.

var1 = 'Hello World!' Updated String :- Hello Python

print ("Updated String :- ", var1[:6] + 'Python')

# Python Program to Delete characters from a String

String1 = "Hello, I'm a Programmer "


print("Initial String: ")
print(String1) Hello, I'm a Programmer
Traceback (most recent call last):
File "[Link]", line 10, in <module>
del String1[2]
# Deleting a character of the String TypeError: 'str' object doesn't support
item deletion
del String1[2]
print("\nDeleting character at 2nd Index: ")
print(String1)

Deletion of entire string is possible with the use of del keyword. Further, if we try to print the
string, this will produce an error because String is deleted and is unavailable to be printed.

# Python Program to Delete entire String

String1 = "Hello, I'm a Programmer"


Initial String:
print("Initial String: ") Hello, I'm a Programmer
print(String1) Deleting entire String:
Traceback (most recent call last):
File "[Link]", line 12, in <module>
# Deleting a String with the use of del print(String1)
NameError: name 'String1' is not defined
del String1
print("\nDeleting entire String: ")
print(String1)

PYTHON AJITH KUMAR J(BANGALORE)


54
PYTHON

Escape Sequencing in Python

 While printing Strings with single and double quotes in it causes SyntaxError
because String already contains Single and Double Quotes and hence cannot be
printed with the use of either of these. Hence, to print such a String either Triple
Quotes are used or Escape sequences are used to print such Strings.
 Escape sequences start with a backslash and can be interpreted differently. If single
quotes are used to represent a string, then all the single quotes present in the string
must be escaped and same is done for Double Quotes.
 To ignore the escape sequences in a String, r or R is used, this implies that the string
is a raw string and escape sequences inside it are to be ignored.
# Python Program for Escape Sequencing in String

# Initial String
Initial String with use of Triple Quotes:
String1 = '''I'm a "Programmer"''' I'm a "Programmer"
print("Initial String with use of Triple Quotes: ")
print(String1)

# Escaping Single Quote

String1 = 'I\'m a "Programmer"' Escaping Single Quote:


I'm a "Programmer"
print("\nEscaping Single Quote: ")
print(String1)

# Escaping Doule Quotes


Escaping Double Quotes:
String1 = "I'm a \"Programmer\"" I'm a "Programmer"
print("\nEscaping Double Quotes: ")
print(String1)

# Printing Paths with the

# use of Escape Sequences

String1 = "C:\\Python\\Programmer\\" Escaping Backslashes:


C:\Python\Programmer\
print("\nEscaping Backslashes: ")
print(String1)

PYTHON AJITH KUMAR J(BANGALORE)


55
PYTHON

# Printing Hello in HEX


Printing in HEX with the use
String1 = "This is \x48\x45\x4C\x4C\x4F in \x48\x45\x58"
of Escape Sequences:
print("\nPrinting in HEX with the use of Escape Sequences: ") This is HELLO in HEX

print(String1)

# Using raw String to

# ignore Escape Sequences Printing Raw String in HEX


Format:
String1 = r"This is \x48\x45\x4C\x4C\x4F in \x48\x45\x58" This is \x48\x45\x4C\x4C\x4F
in \x48\x45\x58
print("\nPrinting Raw String in HEX Format: ")
print(String1)

String Formatting Operator(%)

This operator is unique to strings and it is similar to printf() function of C language.


Consider the following example,%s and %d is replaced by 'Kumar' and 90000.
print ("My first name is %s and my salary is %d" % ('Kumar', 90000))

My first name is Kumar and my salary is 90000

PYTHON AJITH KUMAR J(BANGALORE)


56
PYTHON

Concatenation and repetition


The operators + and * can be used on strings. The + operator combines two strings. This
operation is called concatenation. The * repeats a string a certain number of times.

# Using + and *
str1 + str2 = HelloWorld!
str1 = 'Hello'
str2 ='World!'
# using +

print('str1 + str2 = ', str1 + str2)


# using *

print('str1 * 3 =', str1 * 3)


str1 * 3 = HelloHelloHello

An example that repeatedly asks the user to enter a letter and builds up a string consisting of only
the vowels that the user entered.

s = '' Enter 9 letters


Enter a letter: q
num=9 Enter a letter: w
Enter a letter: e
print('Enter',num,'letters') Enter a letter: r
Enter a letter: t
for i in range(num): Enter a letter: y
Enter a letter: u
t = input('Enter a letter: ') Enter a letter: i
Enter a letter: o
if t=='a' or t=='e' or t=='i' or t=='o' or t=='u':
s=s+t euio
print(s)

The in operator
The in operator is used to tell if a string contains something.
#Using in

string="Hai";
if 'a' in string:
print('Your string contains the letter a.')
Your string contains the letter a.
else:
print('Your string does not contains the letter a.')

PYTHON AJITH KUMAR J(BANGALORE)


57
PYTHON

#Using not in

You can combine in with the not operator to tell if a string does not contain something:
string="Hello";
if 'e' not in string:
print('Your string does not contains the letter e.')
else: Your string contains the letter e.
print('Your string contains the letter e.')

In the previous topic we had the long if condition


if t=='a' or t=='e' or t=='i' or t=='o' or t=='u':
Using the in operator, we can replace that statement with the following:
if t in 'aeiou':

The format() Method for Formatting Strings

The format() method that is available with the string object is very versatile and powerful in
formatting strings. Format strings contains curly braces {} as placeholders or replacement
fields which gets replaced.
# default(implicit) order

default_order = "{}, {} and {}".format('John','Bill','Sean')


--Default Order--
print('\n--- Default Order ---') John, Bill and Sean

print(default_order)

# order using positional argument

positional_order = "{1}, {0} and {2}".format('John','Bill','Sean')


--Positional Order--
print('\n--- Positional Order ---') Bill, John and Sean

print(positional_order)

# order using keyword argument

keyword_order = "{s}, {b} and {j}".format(j='John',b='Bill',s='Sean')


print('\n--- Keyword Order ---')
--Keyword Order--
print(keyword_order) Sean, Bill and John

PYTHON AJITH KUMAR J(BANGALORE)


58
PYTHON

Built-in String Methods

Strings come with a ton of methods, functions that return information about the string or
return a new string that is a modified version of the original.
String capitalize() Method
It returns a copy of the string with only its first character capitalized.

Syntax:

[Link]()

Example:
str = "this is string example....wow!!!"
print ("[Link]() : ", [Link]())

[Link]() : This is string example....wow!!!

String count() Method

The count() method returns the number of occurrences of substring sub in the range [start,
end]. Optional arguments start and end are interpreted as in slice notation.
Syntax:
[Link](sub, start= 0,end=len(string))
Parameters
 sub - This is the substring to be searched.
 start - Search starts from this index. First character starts from 0 index. By default
search starts from 0 index.
 end - Search ends from this index. First character starts from 0 index. By default
search ends at the last index.

Example:
str="this is string example....wow!!!"
[Link]('i') : 3
sub='i'
[Link]('exam', 10, 40) : 1
print ("[Link]('i') : ", [Link](sub))
sub='exam'
print ("[Link]('exam', 10, 40) : ", [Link](sub,10,40))

PYTHON AJITH KUMAR J(BANGALORE)


59
PYTHON

String endswith() Method

It returns True if the string ends with the specified suffix, otherwise return False optionally
restricting the matching with the given indices start and end.
Syntax:
[Link](suffix[, start[, end]])

Parameters
 suffix - This could be a string or could also be a tuple of suffixes to look for.
 start - The slice begins from here.
 end - The slice ends here.

Return Value
TRUE if the string ends with the specified suffix, otherwise FALSE.
Example:
Str='this is string example....wow!!!'
suffix='!!'
print ([Link](suffix))
True
print ([Link](suffix,20)) True
False
suffix='exam' True

print ([Link](suffix))
print ([Link](suffix, 0, 19))

String index() Method

The index() method determines if the string str occurs in string or in a substring of string, if
the starting index beg and ending index end are given. This method is same as find(), but
raises an exception if sub is not found.
Syntax:
[Link](str, beg=0 end=len(string))

Parameters
 str - This specifies the string to be searched.
 beg - This is the starting index, by default its 0.
 end - This is the ending index, by default its equal to the length of the string.
Return Value
Index if found otherwise raises an exception if str is not found.

PYTHON AJITH KUMAR J(BANGALORE)


60
PYTHON

Example:
str1 = "this is string example....wow!!!" 15
str2 = "exam"; 15
Traceback (most recent call last):
print ([Link](str2)) File "[Link]", line 5, in <module>
print ([Link](str2, 40))
print ([Link](str2, 10)) ValueError: substring not found
print ([Link](str2, 40))

String find() Method

The find() method determines if the string str occurs in string, or in a substring of string if the
starting index beg and ending index end are given.
Syntax:
[Link](str, beg=0 end=len(string))

Parameters
 str - This specifies the string to be searched.
 beg - This is the starting index, by default its 0.
 end - This is the ending index, by default its equal to the length of the string.
Return Value
Index if found and -1 otherwise.

Example:
str1 = "this is string example....wow!!!"
str2 = "exam"; 15
15
print ([Link](str2))
-1
print ([Link](str2, 10))
print ([Link](str2, 40))

PYTHON AJITH KUMAR J(BANGALORE)


61
PYTHON

String isalnum() Method

The isalnum() method checks whether the string consists of alphanumeric characters.
Syntax:
str.isa1num()

Parameters
 NA.
Return Value
This method returns true if all the characters in the string are alphanumeric and there is at
least one character, false otherwise.
Example:
str = "this2016" # No space in this string
True
print ([Link]()) False
str = "this is string example....wow!!!"

print ([Link]())

String isalpha() Method


The isalpha() method checks whether the string consists of alphabetic characters only.
Syntax:
[Link]()

Parameters
 NA.
Return Value
This method returns true if all the characters in the string are alphabetic and there is at least
one character, false otherwise.
Example:
str = "this"; # No space & digit in this string
True
print ([Link]())
False
str = "this is string example....wow!!!"
print ([Link]())

PYTHON AJITH KUMAR J(BANGALORE)


62
PYTHON

String isdigit() Method


The method isdigit() checks whether the string consists of digits only.
Syntax:
[Link]()

Parameters
 NA.
Return Value
This method returns true if all characters in the string are digits and there is at least one
character, false otherwise.
Example:
str = "123456"; # Only digit in this string
True
print ([Link]())
False
str = "this is string example....wow!!!"
print ([Link]())

String islower() Method


The islower() method checks whether all the case-based characters (letters) of the string are
lowercase.
Syntax:
[Link]()

Parameters
 NA.
Return Value
This method returns true if all cased characters in the string are lowercase and there is at least
one cased character, false otherwise.
Example:
str = "THIS is string example....wow!!!"
False
print ([Link]()) True

str = "this is string example....wow!!!"


print ([Link]())

PYTHON AJITH KUMAR J(BANGALORE)


63
PYTHON

String isnumeric() Method


The isnumeric() method checks whether the string consists of only numeric characters.
Syntax:
[Link]()

Parameters
 NA.
Return Value
This method returns true if all characters in the string are numeric, false otherwise.
Example:
str = "this2016"
False
print ([Link]()) True

str = "23443434"
print ([Link]())

String isspace() Method


The isspace() method checks whether the string consists of whitespace.
Syntax:
[Link]()

Parameters
 NA.
Return Value
This method returns true if there are only whitespace characters in the string and there is at
least one character, false otherwise.
Example:
str = " "
print ([Link]()) True
False
str = "This is string example....wow!!!"
print ([Link]())

PYTHON AJITH KUMAR J(BANGALORE)


64
PYTHON

String istitle() Method


The istitle() method checks whether all the case-based characters in the string following non-
casebased letters are uppercase and all other case-based characters are lowercase.
Syntax:
[Link]()

Parameters
 NA.
Return Value
This method returns true if the string is a title cased string and there is at least one character,
for example uppercase characters may only follow uncased characters and lowercase
characters only cased ones. It returns false otherwise.
Example:
str = "This Is String Example...Wow!!!"
print ([Link]()) True
False
str = "This is string example....wow!!!"
print ([Link]())

String join() Method


The join() method returns a string in which the string elements of sequence have been joined
by str separator.
Syntax:
[Link](sequence)

sequence - This is a sequence of the elements to be joined

Return Value
This method returns a string, which is the concatenation of the strings in the sequence seq.
The separator between elements is the string providing this method.
Example:
s = "-"
seq = ("a", "b", "c") # This is sequence of strings. a-b-c
print ([Link]( seq ))

PYTHON AJITH KUMAR J(BANGALORE)


65
PYTHON

String len() Method


The len() method returns the length of the string.
Syntax:
[Link]()

Parameters
 NA.
Return Value
This method returns the length of the string.
Example:
str = "Ajith" Length of the string: 5
print ("Length of the string: ", len(str))

String max() Method


The max() method returns the max alphabetical character from the string str.
Syntax:
max(str)

str - This is the string from which max alphabetical character needs to be returned.

Return Value
This method returns the max alphabetical character from the string str.
Example:
str = "this is a string example....really!!!"
Max character: y
print ("Max character: " + max(str)) Max character: x
str = "this is a string example....wow!!!"
print ("Max character: " + max(str))

PYTHON AJITH KUMAR J(BANGALORE)


66
PYTHON

String min() Method


The min() method returns the min alphabetical character from the string str.
Syntax:
min(str)

str - This is the string from which min alphabetical character needs to be returned.

Return Value
This method returns the min alphabetical character from the string str.
Example:
str = "[Link]"
Min character: .
print ("Min character: " + min(str))
Min character: H
str = "Hello"
print ("Min character: " + min(str))

String replace() Method


The replace() method returns a copy of the string in which the occurrences of old have been
replaced with new, optionally restricting the number of replacements to max.
Syntax:
[Link](old, new[, max])

Parameters
 old - This is old substring to be replaced.
 new - This is new substring, which would replace old substring.
 max - If this optional argument max is given, only the first count occurrences are
 replaced.
Return Value
This method returns a copy of the string with all occurrences of substring old replaced by
new. If the optional argument max is given, only the first count occurrences are replaced.
Example:
str = "this is string example....wow!!! this is really string"
print ([Link]("is", "was"))
print ([Link]("is", "was", 3))

thwas was string example....wow!!! thwas was really string


thwas was string example....wow!!! thwas is really string

PYTHON AJITH KUMAR J(BANGALORE)


67
PYTHON

Lists

Lists are just like the arrays, declared in other languages. Lists need not be homogeneous
always which makes it a most powerful tool in Python.
Lists are a useful tool for preserving a sequence of data and further iterating over it.

Creating a List

Lists in Python can be created by just placing the sequence inside the square brackets [ ]. A list may
contain duplicate values with their distinct positions and hence, multiple distinct or duplicate values
can be passed as a sequence at the time of list creation.

# Python program to demonstrate Creation of List

# Creating a List Intial blank List:


List = [] []

print("Intial blank List: ")


print(List)

# Creating a List with

# the use of a String

List = ['Python']
print("\nList with the use of String: ") List with the use of String:
['Python']
print(List)

# Creating a List with

# the use of multiple values

List = ["Hello", "World"]


print("\nList containing multiple values: ")
List containing multiple values:
print(List[0])
Hello
print(List[1]) World

PYTHON AJITH KUMAR J(BANGALORE)


68
PYTHON

# Creating a Multi-Dimensional List


Multi-Dimensional List:
# (By Nesting a list inside a List) [['Hi', 'Hello'], ['GM']]
List = [['Hi', 'Hello'] , ['GM']]
print("\nMulti-Dimensional List: ")
print(List)

# Creating a List with

# the use of Numbers

# (Having duplicate values)


List with the use of Numbers:
List = [1, 2, 4, 4, 3, 3, 3, 6, 5] [1, 2, 4, 4, 3, 3, 3, 6, 5]
print("\nList with the use of Numbers: ")
print(List)

# Creating a List with

# mixed type of values

# (Having numbers and strings)

List = [1, 2, 'Hello', 4, 'how', 6, 'ru'] List with the use of Mixed Values:
[1, 2, 'Hello', 4, 'how', 6, 'ru']
print("\nList with the use of Mixed Values: ")
print(List)

Adding Elements to a List


Elements can be added to the List by using built-in append() function. Only one element at a
time can be added to the list by using append() method, for addition of multiple elements
with the append() method, loops are used.
Lists can also be added to the existing list with the use of append() method.
append() method only works for addition of elements at the end of the List, for addition of
element at the desired position, insert() method is used. Unlike append() which takes only one
argument, insert() method requires two arguments(position, value). Other
than append() and insert() methods, there’s one more method for Addition of
elements, extend(), this method is used to add multiple elements at the same time at the end of
the list.

Note – append() and extend() methods can only add elements at the end.

PYTHON AJITH KUMAR J(BANGALORE)


69
PYTHON

# Python program to demonstrate Addition of elements in a List


# Creating a List
Intial blank List:
List = [] []
print("Intial blank List: ")
print(List)

# Addition of Elements in the List


[Link](1)
[Link](2)
List after Addition of Three elements:
[Link](4) [1, 2, 4]
print("\nList after Addition of Three elements: ")
print(List)

# Adding elements to the List using Iterator


for i in range(1, 4):
[Link](i)
List after Addition of elements from 1-3:
print("\nList after Addition of elements from 1-3: ")
[1, 2, 4, 1, 2, 3]
print(List)

# Adding Tuples to the List


[Link]((5, 6))
print("\nList after Addition of a Tuple: ") List after Addition of a Tuple:
[1, 2, 4, 1, 2, 3, (5, 6)]
print(List)

# Addition of List to a List


List2 = ['Hello', 'World'] List after Addition of a List:
[Link](List2) [1, 2, 4, 1, 2, 3, (5, 6), ['Hello', 'World']]

print("\nList after Addition of a List: ")


print(List)

PYTHON AJITH KUMAR J(BANGALORE)


70
PYTHON

# Addition of Element at specific Position (using insert())


[Link](3, 12)
[Link](0, 'Python')
print("\nList after performing Insert Operation: ")
print(List)

# Addition of multiple elements to the List


#at the end (using Extend Method)
[Link]([8, 'First', 'Program'])
print("\nList after performing Extend Operation: ")
print(List)
List after performing Insert Operation:
[1, 2, 4, 12, 1, 2, 3, (5, 6), ['Python', 'Hello', 'World']]

List after performing Extend Operation:


[1, 2, 4, 12, 1, 2, 3, (5, 6), ['Python', 'Hello', 'World'], 8, 'First', 'Program']

Accessing elements from the List

In order to access the list items refer to the index [Link] the index operator [ ] to access
an item in a [Link] index must be an [Link] list are accessed using nested indexing.

# Python program to demonstrate accessing of element from list


# Creating a List with the use of multiple values
List = ["Hello", "World", "Program"] Accessing a element from the list
# accessing a element from the list using index number Hello
Program
print("Accessing a element from the list")
print(List[0])
print(List[2])

# Creating a Multi-Dimensional List (By Nesting a list inside a List)


List = [['Hello', 'World'] , ['Program']]

PYTHON AJITH KUMAR J(BANGALORE)


71
PYTHON

# Accessing a element from the Multi-Dimensional List using index number


print("Acessing a element from a Multi-Dimensional list")
print(List[0][1]) Acessing a element from a Multi-Dimensional list
World
print(List[1][0])
Program

List = [1, 2, 'Hello', 4, 'World', 6, 'Program']


# Accessing a element using negative indexing
print("Acessing element using negative indexing")
# print the last element of list Acessing element using negative indexing
print(List[-1]) Program

# print the third last element of list World


print(List[-3])

Removing Elements from the List


Elements can be removed from the List by using built-in remove() function but an Error
arises if element doesn’t exist in the set. Remove() method only removes one element at a
time, to remove range of elements, iterator is used.
To remove a list element, you can use either the del statement if you know exactly which
element(s) you are deleting.
List, index of the element is passed as an argument to the pop() method.
Note – Remove method in List will only remove the first occurrence of the searched element.

# Python program to demonstrate Removal of elements in a List


# Creating a List
List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
print("Intial List: ")
Intial List:
print(List) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

# Removing elements from List


# using Remove() method
[Link](5) List after Removal of two elements:
[1, 2, 3, 4, 7, 8, 9, 10, 11, 12]
[Link](6)
print("\nList after Removal of two elements: ")
PYTHON AJITH KUMAR J(BANGALORE)
72
PYTHON

print(List)
# Removing elements from List using iterator method
for i in range(1, 5): List after Removing a range of elements:
[7, 8, 9, 10, 11, 12]
[Link](i)
print("\nList after Removing a range of elements: ")
print(List)

# Removing element from the


# List using the pop() method
[Link]()
List after popping an element:
print("\nList after popping an element: ") [7, 8, 9, 10, 11]
print(List)

# Removing element at a
# specific location from the
# List using the pop() method
[Link](2) List after popping a specific element:
[7, 8, 10, 11]
print("\nList after popping a specific element: ")
print(List)

#Deleting using del statement


list = ['Electrial', 'Electronics', 'Biology', 2000]
print (list)
['Electrial', 'Electronics', 'Biology', 2000]
del list[2] After deleting value at index 2 :
['Electrial', 'Electronics', 2000]
print ("After deleting value at index 2 : ")
print (list)

PYTHON AJITH KUMAR J(BANGALORE)


73
PYTHON

Slicing of a List
To print a specific range of elements from the list, we use Slice operation. Slice operation is
performed on Lists with the use of colon(:). To print elements from beginning to a range use
[:Index], to print elements from end use [:-Index], to print elements from specific Index till the
end use [Index:], to print elements within a range, use [Start Index:End Index] and to print
whole List with the use of slicing operation, use [:]. Further, to print whole List in reverse
order, use [::-1].
Note – To print elements of List from rear end, use Negative Indexes.

# Python program to demonstrate


# Removal of elements in a List
Intial List:
# Creating a List ['H', 'E', 'L', 'L', 'O', 'W', 'O', 'R', 'L', 'D']
List = ['H','E','L','L','O','W','O','R','L','D']
print("Intial List: ")
print(List)

# Print elements of a range


# using Slice operation
Sliced_List = List[3:8]
Slicing elements in a range 3-8:
print("\nSlicing elements in a range 3-8: ") ['L', 'O', 'W', 'O', 'R']

print(Sliced_List)

# Print elements from beginning


# to a pre-defined point using Slice
Sliced_List = List[:-6]
Elements sliced till 6th element from last:
print("\nElements sliced till 6th element from last: ")
['H', 'E', 'L', 'L']
print(Sliced_List)

PYTHON AJITH KUMAR J(BANGALORE)


74
PYTHON

# Print elements from a


# pre-defined point to end Elements sliced from 5th element till the end:
['W', 'O', 'R', 'L', 'D']
Sliced_List = List[5:]
print("\nElements sliced from 5th "
"element till the end: ")
print(Sliced_List)

# Printing elements from


# beginning till end
Sliced_List = List[:]
print("\nPrinting all elements using slice operation: ") Printing all elements using slice operation:
['H', 'E', 'L', 'L', 'O', 'W', 'O', 'R', 'L', 'D']
print(Sliced_List)

# Printing elements in reverse


# using Slice operation
Sliced_List = List[::-1]
Printing List in reverse:
print("\nPrinting List in reverse: ") ['D', 'L', 'R', 'O', 'W', 'O', 'L', 'L', 'E', 'H']
print(Sliced_List)

Basic List Operations

Lists respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new list, not a string.
Example:
Python Expression Result
len([1, 2, 3]) 3
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6]
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!']
3 in [1, 2, 3] True
for x in [1,2,3] : 123
print (x,end=' ')

PYTHON AJITH KUMAR J(BANGALORE)


75
PYTHON

Built-in List Functions and Methods

Python3 includes the following list of functions

List len( ) method


The len() method returns the number of elements in the list..
Syntax:
len(list)

Parameters
 list - This is a list for which, number of elements are to be counted.
Return Value
This method returns the number of elements in the list.
Example:
list1 = ['physics', 'chemistry', 'maths']
3
print (len(list1)) 5
list2 = list(range(5)) #creates list of numbers between 0-4
print (len(list2))

List max( ) method


The max() method returns the elements from the list with maximum value.
Syntax:
max(list)

Parameters
 list - This is a list from which max valued element are to be returned..
Return Value
This method returns the elements from the list with maximum value.
Example:
list1, list2 = ['C++','Java', 'Python'], [456, 700, 200] Max value element : Python
Max value element : 700
print ("Max value element : ", max(list1))
print ("Max value element : ", max(list2))

PYTHON AJITH KUMAR J(BANGALORE)


76
PYTHON

List min( ) method


The min() method returns the elements from the list with minimum value.
Syntax:
min(list)

Parameters
 list - This is a list from which min valued element are to be returned..
Return Value
This method returns the elements from the list with minimum value.
Example:
list1, list2 = ['C++','Java', 'Python'], [456, 700, 200] Max value element : C++
Max value element : 200
print ("Max value element : ", max(list1))
print ("Max value element : ", max(list2))

List list( ) method


The list() method takes sequence types and converts them to lists. This is used to convert a
given tuple into list.
Syntax:
list(seq)

Parameters
 seq - This is a tuple or string to be converted into list.
Return Value
This method returns the list.
Example:
aTuple = (123, 'C++', 'Java', 'Python')
list1 = list(aTuple)
print ("List elements : ", list1)
str="Hello World"
List elements : [123, 'C++', 'Java', 'Python']
list2=list(str)
List elements : ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
print ("List elements : ", list2)

PYTHON AJITH KUMAR J(BANGALORE)


77
PYTHON

Python includes the following list methods

List append( ) method


The append() method appends a passed obj into the existing list.
Syntax:
[Link](obj)

Parameters
 obj - This is the object to be appended in the list.
Return Value
This method does not return any value but updates existing list..
Example:
list1 = ['C++', 'Java', 'Python']
[Link]('C#') updated list : ['C++', 'Java', 'Python', 'C#']

print ("updated list : ", list1)

List count( ) method


The count() method returns count of how many times obj occurs in list..
Syntax:
[Link](obj)

Parameters
 obj - This is the object to be counted in the list.
Return Value
This method returns count of how many times obj occurs in list.
Example:
aList = [123, 'xyz', 'zara', 'abc', 123];
Count for 123 : 2
print ("Count for 123 : ", [Link](123)) Count for zara : 1
print ("Count for zara : ", [Link]('zara'))

PYTHON AJITH KUMAR J(BANGALORE)


78
PYTHON

List extend ( ) method


The extend() method appends the contents of seq to list.
Syntax:
[Link](seq)

Parameters
 seq - This is the list of elements.
Return Value
This method does not return any value but adds the content to an existing list.
Example:
list1 = ['physics', 'chemistry', 'maths']
#creates list of numbers between 0-4
list2=list(range(5))
Extended List : ['physics', 'chemistry', 'maths', 0, 1, 2, 3, 4]
[Link](list2)
print ('Extended List :',list1)

List index ( ) method


The index() method returns the lowest index in list that obj appears.
Syntax:
list. index (obj)

Parameters
 obj - This is the object to be find out.
Return Value
This method returns index of the found object otherwise raises an exception indicating that
the value is not found.
Example:
list1 = ['physics', 'chemistry', 'maths']
print ('Index of chemistry', [Link]('chemistry'))
Index of chemistry 1
print ('Index of C++', [Link]('C++'))
Traceback (most recent call last):
File "[Link]", line 3, in <module>
print ('Index of C++', [Link]('C++'))
ValueError: 'C++' is not in list

PYTHON AJITH KUMAR J(BANGALORE)


79
PYTHON

List insert ( ) method


The insert() method inserts object obj into list at offset index.
Syntax:
[Link](index, obj)

Parameters
 index - This is the Index where the object obj need to be inserted.
 obj - This is the Object to be inserted into the given list.
Return Value
This method does not return any value but it inserts the given element at the given index.
Example:
list1 = ['physics', 'chemistry', 'maths']
[Link](1, 'Biology')
Final list : ['physics', 'Biology', 'chemistry', 'maths']
print ('Final list : ', list1)

List pop( ) method


The pop() method removes and returns last object or obj from the list.
Syntax:
[Link](obj=list[-1])

Parameters
 obj - This is an optional parameter, index of the object to be removed from the list.
Return Value
This method returns the removed object from the list.
Example:
list1 = ['physics', 'Biology', 'chemistry', 'maths']
[Link]()
print ("list now : ", list1)
list now : ['physics', 'Biology', 'chemistry']
[Link](1) list now : ['physics', 'chemistry']
print ("list now : ", list1)

PYTHON AJITH KUMAR J(BANGALORE)


80
PYTHON

List remove ( ) method


The remove () method removes an item from the list.
Syntax:
[Link](obj)

Parameters
 obj - This is the object to be removed from the list.
Return Value
This method does not return any value but removes the given object from the list.
Example:
list1 = ['physics', 'Biology', 'chemistry', 'maths']
[Link]('Biology')
print ("list now : ", list1)
list now : ['physics', 'chemistry', 'maths']
[Link]('maths') list now : ['physics', 'chemistry']

print ("list now : ", list1)

List reverse ( ) method


The reverse() method reverses objects of list in place.
Syntax:
[Link]()

Parameters
 NA
Return Value
This method does not return any value but reverse the given object from the list.
Example:
list1 = ['physics', 'Biology', 'chemistry', 'maths']
[Link]()
list now : ['maths', 'chemistry', 'Biology', 'physics']
print ("list now : ", list1)

PYTHON AJITH KUMAR J(BANGALORE)


81
PYTHON

List sort ( ) method


The sort() method sorts objects of list, use compare function if given.
Syntax:
[Link]([func])

Parameters
 NA
Return Value
This method does not return any value but reverses the given object from the list.
Example:
list1 = ['physics', 'Biology', 'chemistry', 'maths']
[Link]() list now : ['Biology', 'chemistry', 'maths', 'physics']
print ("list now : ", list1)

PYTHON AJITH KUMAR J(BANGALORE)


82
PYTHON

Tuples

Tuple is a collection of Python objects much like a list. The sequence of values stored in a
tuple can be of any type, and they are indexed by integers. The important difference between
a list and a tuple is that tuples are immutable.

Creating a Tuple
Tuples are created by placing sequence of values separated by ‘comma’ with or without the
use of parentheses for grouping of data sequence. Tuples can contain any number of elements
and of any datatype (like strings, integers, list, etc.).
Note – Creation of Python tuple without the use of parentheses is known as Tuple Packing.
# Python program to demonstrate creating Tuples

# Creating an empty tuple

Tuple1 = () Initial empty Tuple:


()
print("Initial empty Tuple: ")
print (Tuple1)
# Creating a Tuple with the use of Strings

Tuple1 = ('Hello', 'World')


print("\nTuple with the use of String: ")
print(Tuple1) Tuple with the use of String:
# Creating a Tuple with the use of list ('Hello', 'World')

list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1)) Tuple using List:
(1, 2, 4, 5, 6)
# Creating a Tuple with the use of loop

Tuple1 = ('Python')
n=5
print("\nTuple with a loop")
Tuple with a loop
for i in range(int(n)): ('Python',)
Tuple1 = (Tuple1,) (('Python',),)
((('Python',),),)
print(Tuple1) (((('Python',),),),)
((((('Python',),),),),)

PYTHON AJITH KUMAR J(BANGALORE)


83
PYTHON

# Creating a Tuple with the use of built-in function

Tuple1 = tuple('Python')
Tuple with the use of function:
print("\nTuple with the use of function: ") ('P', 'y', 't', 'h', 'o', 'n')

print(Tuple1)
# Creating a Tuple with Mixed Datatypes

Tuple1 = (5, 'Welcome', 7, 'Python')


print("\nTuple with Mixed Datatypes: ") Tuple with Mixed Datatypes:
print(Tuple1) (5, 'Welcome', 7, 'Python')

# Creating a Tuple with nested tuples

Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python', 'Programmer')
Tuple3 = (Tuple1, Tuple2)
Tuple with nested tuples:
print("\nTuple with nested tuples: ") ((0, 1, 2, 3), ('python', 'Programmer'))
print(Tuple3)
# Creating a Tuple with repetition

Tuple1 = ('Python',) * 3
print("\nTuple with repetition: ") Tuple with repetition:
('Python', 'Python', 'Python')
print(Tuple1)

Concatenation of Tuples
Concatenation of tuple is the process of joining of two or more Tuples. Concatenation is done
using ‘+’ operator. Concatenation of tuples is done always from the end of the original tuple.
Other arithmetic operations do not apply on Tuples.
Note- Only same datatypes can be combined with concatenation, an error arises if a list and a
tuple are combined.
Tuple 1 Tuple 2
1 2 3 4
Hello World !!!

Concatenated Tuple 3
1 2 3 4 Hello World !!!

PYTHON AJITH KUMAR J(BANGALORE)


84
PYTHON

# Concatenaton of tuples

Tuple1 = (0, 1, 2, 3)
Tuple2 = ('Hello', 'World','!!!')

Tuple3 = Tuple1 + Tuple2

# Printing first Tuple


Tuple 1:
print("Tuple 1: ")
(0, 1, 2, 3)
print(Tuple1)

Tuple2:
# Printing Second Tuple
('Hello', 'World', '!!!')
print("\nTuple2: ")
print(Tuple2)

# Printing Final Tuple Tuples after Concatenation:


(0, 1, 2, 3, 'Hello', 'World', '!!!')
print("\nTuples after Concatenation: ")
print(Tuple3)

Slicing of Tuple

Slicing of a Tuple is done to fetch a specific range or slice of sub-elements from a Tuple.
Note- Negative Increment values can also be used to reverse the sequence of Tuples

PYTHON AJITH KUMAR J(BANGALORE)


85
PYTHON

# Slicing of a Tuple
Tuple1 = tuple('HELLO WORLD')

# Removing First element Removal of First Element:


('E', 'L', 'L', 'O', ' ', 'W', 'O', 'R', 'L', 'D')
print("Removal of First Element: ")
print(Tuple1[1:])

# Reversing the Tuple


Tuple after sequence of Element is reversed:
print("\nTuple after sequence of Element is reversed: ") ('D', 'L', 'R', 'O', 'W', ' ', 'O', 'L', 'L', 'E', 'H')
print(Tuple1[::-1])

# Printing elements of a Range


Printing elements between Range 4-9:
print("\nPrinting elements between Range 4-9: ") ('O', ' ', 'W', 'O', 'R')
print(Tuple1[4:9])

Deleting a Tuple
Tuples are immutable and hence they do not allow deletion of a part of it. Entire tuple gets
deleted by the use of del() method.
Note- Printing of Tuple after deletion results to an Error.

# Deleting a Tuple
Tuple1 = (0, 1, 2, 3, 4) (0, 1, 2, 3, 4)
After Deletion
print(Tuple1) Traceback (most recent call last):
File "[Link]", line 5, in <module>
del Tuple1 print(Tuple1)
print("After Deletion") NameError: name 'Tuple1' is not defined

print(Tuple1)

PYTHON AJITH KUMAR J(BANGALORE)


86
PYTHON

Built-in tuple Methods

Python3 includes the following tuple functions

Tuple len( ) method


The len() method returns the number of elements in the tuple.
Syntax:
len(tuple)

Parameters
 tuple - This is a tuple for which, number of elements are to be counted.
Return Value
This method returns the number of elements in the tuple.
Example:
tuple1, tuple2 = (123, 'xyz', 'zara'), (456, 'abc')
First tuple length : 3
print ("First tuple length : ", len(tuple1))
Second tuple length : 2
print ("Second tuple length : ", len(tuple2))

Tuple max( ) method


The max() method returns the elements from the tuple with maximum value.
Syntax:
max (tuple)

Parameters
 tuple - This is a tuple from which max valued element to be returned.
Return Value
This method returns the elements from the tuple with maximum value..
Example:
tuple1, tuple2 = ('maths', 'che', 'phy', 'bio'), (456, 700, 200)
print ("Max value element : ", max(tuple1)) Max value element : phy
Max value element : 700
print ("Max value element : ", max(tuple2))

PYTHON AJITH KUMAR J(BANGALORE)


87
PYTHON

Tuple min( ) method


The min() method returns the elements from the tuple with minimum value.
Syntax:
min (tuple)

Parameters
 tuple - This is a tuple from which min valued element is to be returned.
Return Value
This method returns the elements from the tuple with minimum value.
Example:
tuple1, tuple2 = ('maths', 'che', 'phy', 'bio'), (456, 700, 200)
print ("Max value element : ", min (tuple1)) Max value element : bio
Max value element : 200
print ("Max value element : ", min (tuple2))

Tuple tuple( ) method


The tuple() method converts a list of items into tuples.
Syntax:
tuple (seq)

Parameters
 seq - This is a tuple to be converted into tuple
Return Value
This method returns the tuple
Example:
list1= ['maths', 'che', 'phy', 'bio']
print(list1)
print(type(list1))
['maths', 'che', 'phy', 'bio']
tuple1=tuple(list1) <class 'list'>
<class 'tuple'>
print(type(tuple1)) tuple elements : ('maths', 'che',
'phy', 'bio')
print ("tuple elements : ", tuple1)

PYTHON AJITH KUMAR J(BANGALORE)


88
PYTHON

Dictionary

Dictionary in Python 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, Dictionary
holds key:value pair. Key value is provided in the dictionary to make it more optimized. Each
key-value pair in a Dictionary is separated by a colon :, whereas each key is separated by a
‘comma’.
Keys of a Dictionary must be unique and of immutable data type such as Strings, Integers
and tuples, but the key-values can be repeated and be of any type.

Creating a Dictionary

Dictionary can be created by placing sequence of elements within curly {} braces, separated
by ‘comma’. Dictionary holds a pair of values, one being the Key and the other corresponding
pair element being its Key:value. Values in a dictionary can be of any datatype and can be
duplicated, whereas keys can’t be repeated and must be immutable.
Dictionary can also be created by the built-in function dict(). An empty dictionary can be
created by just placing to curly braces{}.
# Creating an empty Dictionary
Dict = {}
Empty Dictionary:
print("Empty Dictionary: ") {}
print(Dict)

# Creating a Dictionary
# with Integer Keys
Dict = {1: 'Apple', 2: 'Bat', 3: 'Cat'}
Dictionary with the use of Integer Keys:
print("\nDictionary with the use of Integer Keys: ") {1: 'Apple', 2: 'Bat', 3: 'Cat'}

print(Dict)

# Creating a Dictionary
# with Mixed keys
Dict = {'Name': 'Ajith', 1: [1, 2, 3, 4]} Dictionary with the use of Mixed Keys:
print("\nDictionary with the use of Mixed Keys: ") {'Name': 'Ajith', 1: [1, 2, 3, 4]}

print(Dict)

PYTHON AJITH KUMAR J(BANGALORE)


89
PYTHON

# Creating a Dictionary
# with dict() method Dictionary with the use of dict():
Dict = dict({1: 'Apple', 2: 'Bat', 3:'Cat'}) {1: 'Apple', 2: 'Bat', 3: 'Cat'}

print("\nDictionary with the use of dict(): ")


print(Dict)

# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'Apple'), (2, 'Bat')])
print("\nDictionary with each item as a pair: ") Dictionary with each item as a pair:
{1: 'Apple', 2: 'Bat'}
print(Dict)

Adding Elements to a Dictionary

Addition of elements can be done in multiple ways. One value at a time can be added to a
Dictionary by defining value along with the key e.g. Dict[Key] = ‘Value’. Updating an existing
value in a Dictionary can be done by using the built-in update()method.
Note- While adding a value, if the key value already exists, the value gets updated otherwise
a new Key with the value is added to the Dictionary.

# Creating an empty Dictionary


Dict = {} Empty Dictionary:
{}
print("Empty Dictionary: ")
print(Dict)

# Adding elements one at a time


Dict[0] = 'Hello'
Dict[2] = 'World'
Dict[3] = 1
print("\nDictionary after adding 3 elements: ") Dictionary after adding 3 elements:
{0: 'Hello', 2: 'World', 3: 1}
print(Dict)

PYTHON AJITH KUMAR J(BANGALORE)


90
PYTHON

# Adding set of values


# to a single Key
After adding Value_set to existing Dictionary:
Dict['Value_set'] = 2, 3, 4 {0: 'Hello', 2: 'World', 3: 1, 'Value_set': (2, 3, 4)}

print("\n After adding Value_set to Dictionary: ")


print(Dict)

# Updating existing Key's Value


Updated key value:
Dict[2] = 'Welcome' {0: 'Hello', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4)}
print("\nUpdated key value: ")
print(Dict)

# Adding Nested Key value to Dictionary


Adding a Nested Key:
Dict[5] = {'Nested' :{'1' : 'Python', '2' : 'Hello'}} {0: 'Hello', 2: 'Welcome', 3: 1, 5: {'Nested': {'2': 'Hello',
'1': 'Python'}}, 'Value
print("\nAdding a Nested Key: ") _set': (2, 3, 4)}
print(Dict)

Accessing elements from a Dictionary

In order to access the items of a dictionary refer to its key [Link] can be used inside
square [Link] is also a method called get() that will also help in acessing the element
from a dictionary.
# Python program to demonstrate accessing a element from a Dictionary
# Creating a Dictionary
Dict = {1: 'Hello', 'name': 'For', 3: 'Python'}

# accessing a element using key


print("Acessing a element using key:") Acessing a element using key:
For
print(Dict['name'])
# accessing a element using key
print("Acessing a element using key:") Acessing a element using key:
Hello
print(Dict[1])

PYTHON AJITH KUMAR J(BANGALORE)


91
PYTHON

# accessing a element using get() method Acessing a element using get:


Python
print("Acessing a element using get:")
print([Link](3))

Removing Elements from Dictionary

In Python Dictionary, deletion of keys can be done by using the del keyword. Using del
keyword, specific values from a dictionary as well as whole dictionary can be deleted. Other
functions like pop() and popitem()can also be used for deleting specific values and arbitrary
values from a Dictionary. All the items from a dictionary can be deleted at once by
using clear()method. Items in a Nested dictionary can also be deleted by using del keyword
and providing specific nested key and particular key to be deleted from that nested Dictionary.

Note- del Dict will delete the entire dictionary and hence printing it after deletion will raise
an Error.
# Initial Dictionary
Dict = { 5 : 'Welcome', 6 : 'To', 7 : 'Python',
'A' : {1 : 'Hello', 2 : 'World', 3 : 'Program'},
'B' : {1 : 'Hello', 2 : 'Students'}}
print("Initial Dictionary: ") Initial Dictionary:
{'B': {1: 'Hello', 2: 'Students'}, 'A': {1: 'Hello', 2:
print(Dict) 'World', 3: 'Program'}, 5: 'Welcome', 6: 'To', 7:
'Python'}

# Deleting a Key value


del Dict[6] Deleting a specific key:
print("\nDeleting a specific key: ") {'B': {1: 'Hello', 2: 'Students'}, 'A': {1: 'Hello', 2:
'World', 3: 'Program'}, 5: 'Welcome', 7: 'Python'}
print(Dict)

# Deleting a Key from


# Nested Dictionary
Deleting a key from Nested Dictionary:
del Dict['A'][2] {'B': {1: 'Hello', 2: 'Students'}, 'A': {1: 'Hello', 3:
'Program'}, 5: 'Welcome', 7: 'Python'}
print("\nDeleting a key from Nested Dictionary: ")
print(Dict)

PYTHON AJITH KUMAR J(BANGALORE)


92
PYTHON

# Deleting a Key
Popping specific element:
# using pop() {'B': {1: 'Hello', 2: 'Students'}, 'A': {1: 'Hello',
3: 'Program'}, 7: 'Python'}
[Link](5)
print("\nPopping specific element: ")
print(Dict)

# Deleting an arbitrary Key-value pair


Pops an arbitrary key-value pair:
# using popitem() {'A': {1: 'Hello', 3: 'Program'}, 7: 'Python'}

[Link]()
print("\nPops an arbitrary key-value pair: ")
print(Dict)

# Deleting entire Dictionary


[Link]()
Deleting Entire Dictionary:
print("\nDeleting Entire Dictionary: ") {}

print(Dict)

Properties of Dictionary Keys

Dictionary values have no restrictions. They can be any arbitrary Python object, either
standard objects or user-defined objects. However, same is not true for the keys. There are
two important points to remember about dictionary keys-

1. More than one entry per key is not allowed. This means no duplicate key is allowed.
When duplicate keys are encountered during assignment, the last assignment wins.
For example-
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}
print ("dict['Name']: ", dict['Name'])

When the above code is executed, it produces the following result:

dict['Name']: Manni

PYTHON AJITH KUMAR J(BANGALORE)


93
PYTHON

2. Keys must be immutable. This means you can use strings, numbers or tuples as
dictionary keys but something like ['key'] is not allowed.
For example-
dict = {['Name']: 'Zara', 'Age': 7}
print ("dict['Name']: ", dict['Name'])
When the above code is executed, it produces the following result:

Traceback (most recent call last):


File "[Link]", line 1, in <module>
dict = {['Name']: 'Zara', 'Age': 7}
TypeError: unhashable type: 'list'

Built-in Dictionary Functions & Methods

Python includes the following dictionary functions


Dictionary len() Method
The method len() gives the total length of the dictionary. This would be equal to the number
of items in the dictionary.
Syntax:
len(dict)

Parameters
 dict - This is the dictionary, whose length needs to be calculated.
Return Value
This method returns the length.
Example:
dict = {'Name': 'Manni', 'Age': 7, 'Class': 'First'}
Length : 3
print ("Length : %d" % len (dict))

Dictionary str() Method


The method str() produces a printable string representation of a dictionary.
Syntax:
str(dict)

PYTHON AJITH KUMAR J(BANGALORE)


94
PYTHON

Parameters
 dict - This is the dictionary.
Return Value
This method returns string representation.
Example:
dict = {'Name': 'Manni', 'Age': 7, 'Class': 'First'}
Equivalent String : {'Age': 7, 'Name': 'Manni', 'Class': 'First'}
print ("Equivalent String : %s" % str (dict))

Python includes the following dictionary methods

Dictionary copy() Method


The method copy() returns a copy of the dictionary.
Syntax:
[Link]()

Parameters
 NA
Return Value
This method returns a copy of the dictionary..
Example:
dict1 = {'Name': 'Manni', 'Age': 7, 'Class': 'First'}
dict2 = [Link]() New Dictionary : {'Age': 7, 'Class': 'First', 'Name': 'Manni'}
print ("New Dictionary : ",dict2)

Dictionary get() Method


The method get() returns a value for the given key. If the key is not available then returns
default value None.
Syntax:
[Link](key, default=None)

Parameters
 key - This is the Key to be searched in the dictionary.
 default - This is the Value to be returned in case key does not exist

PYTHON AJITH KUMAR J(BANGALORE)


95
PYTHON

Return Value
This method returns a value for the given key. If the key is not available, then returns default
value as None.
Example:
dict = {'Name': 'Zara', 'Age': 27}
Value : 27
print ("Value : %s" % [Link]('Age')) Value : NA
print ("Value : %s" % [Link]('Gender', "NA"))

Dictionary items() Method


The method items() returns a list of dict's (key, value) tuple pairs.
Syntax:
[Link]()

Parameters
 NA
Return Value
This method returns a list of tuple pairs.
Example:
dict = {'Name': 'Zara', 'Age': 7} Value : dict_items([('Name', 'Zara'), ('Age', 7)])
print ("Value : %s" % [Link]()))

Dictionary keys() Method


The method keys() returns a list of all the available keys in the dictionary.
Syntax:
dict. keys()

Parameters
 NA
Return Value
This method returns a list of all the available keys in the dictionary.
Example:
dict = {'Name': 'Zara', 'Age': 7} Value : dict_keys(['Name', 'Age'])
print ("Value : %s" % dict. keys())

PYTHON AJITH KUMAR J(BANGALORE)


96
PYTHON

Dictionary update() Method


The method update() adds dictionary dict2's key-values pairs in to dict. This function does not return
anything.

Syntax:
[Link](dict2)

Parameters
 NA
Return Value
This method returns a list of all the available keys in the dictionary.

Example:
dict = {'Name': 'Zara', 'Age': 7}

dict2 = {'Sex': 'female' }


updated dict : {'Name': 'Zara', 'Sex': 'female', 'Age': 7}
[Link](dict2)

print ("updated dict : ", dict)

Dictionary values() Method


The method values() returns a list of all the values available in a given dictionary.
Syntax:
dict. values()

Parameters
 NA
Return Value
This method returns a list of all the values available in a given dictionary.
Example:
dict = {'Sex': 'female', 'Age': 7, 'Name': 'Zara'}

print ("Values : ", list([Link]()))


Values : ['Zara', 7, 'female']

PYTHON AJITH KUMAR J(BANGALORE)


97
PYTHON

Python Date and Time

Python has a module named datetime to work with dates and times.

Example 1: Get Current Date and Time


import datetime
datetime_object = [Link]()
2019-08-06 18:02:58.853048
print(datetime_object)
One of the classes defined in the datetime module is datetime class. We then used now() method
to create a datetime object containing the current local date and time.

Example 2: Get Current Date


import datetime
date_object = [Link]() 2019-08-06

print(date_object)
In the Eg2 , we have used today() method defined in the date class to get a date object
containing the current local date.

Example 3: Date object to represent a date


import datetime
#from datetime import date
d = [Link](2019, 4, 13)
2019-04-13
print(d)
date() in the above example is a constructor of the date class. The constructor takes three
arguments: year, month and day.
The variable d is a date object.

Example 4: Get current date


from datetime import date
Current date = 2019-08-06
today = [Link]()
print("Current date =", today)

PYTHON AJITH KUMAR J(BANGALORE)


98
PYTHON

Example 5: Print today's year, month and day


We can get year, month, day, day of the week etc. from the date object easily.

from datetime import date


# date object of today's date
today = [Link]()
print("Current year:", [Link]) Current year: 2019
Current month: 8
print("Current month:", [Link]) Current day: 6

print("Current day:", [Link])

[Link]

A time object instantiated from the time class represents the local time.
Example 6: Time object to represent time

from datetime import time

# time(hour = 0, minute = 0, second = 0)

a = time()

print("a =", a)

# time(hour, minute and second)

b = time(11, 34, 56)

print("b =", b)

# time(hour, minute and second)


a = 00:00:00
c = time(hour = 11, minute = 34, second = 56) b = 11:34:56
c = 11:34:56
print("c =", c) d = 11:34:56.234566
# time(hour, minute, second, microsecond)

d = time(11, 34, 56, 234566)

print("d =", d)

PYTHON AJITH KUMAR J(BANGALORE)


99
PYTHON

Example 7: Print hour, minute, second and microsecond


Once you create a time object, you can easily print its attributes such as hour, minute etc.

from datetime import time


a = time(11, 34, 56)
hour = 11
print("hour =", [Link]) minute = 34
print("minute =", [Link]) second = 56
microsecond = 0
print("second =", [Link])
print("microsecond =", [Link])

Note: we haven't passed microsecond argument. Hence, its default value 0 is printed.

[Link]
The datetime module has a class named dateclass that can contain information from
both date and time objects.
Example 8: Python datetime object
from datetime import datetime
#datetime(year, month, day)
2018-11-28 00:00:00
a = datetime(2018, 11, 28)
2017-11-28 23:55:59.342380
print(a)
# datetime(year, month, day, hour, minute, second, microsecond)
b = datetime(2017, 11, 28, 23, 55, 59, 342380)
print(b)

The first three arguments year, month and day in the datetime() constructor are mandatory.

Example 9: Print year, month, hour, minute


from datetime import datetime
a = datetime(2017, 11, 28, 23, 55)
print("year =", [Link])
year = 2017
print("month =", [Link]) month = 11
hour = 23
print("hour =", [Link])
minute = 55
print("minute =", [Link])

PYTHON AJITH KUMAR J(BANGALORE)


100
PYTHON

[Link]
A timedelta object represents the difference between two dates or times.
Example 10-: Difference between two dates and times
from datetime import datetime, date
t1 = date(year = 2018, month = 7, day = 12)
t2 = date(year = 2017, month = 12, day = 23)
t3 = t1 - t2
print("t3 =", t3)
t4 = datetime(year = 2018, month = 7, day = 12, hour = 7, minute = 9, second = 33)
t5 = datetime(year = 2019, month = 6, day = 10, hour = 5, minute = 55, second = 13)
t6 = t4 - t5 t3 = 201 days, 0:00:00
print("t6 =", t6) t6 = -333 days, 1:14:20
type of t3 = <class '[Link]'>
print("type of t3 =", type(t3)) type of t6 = <class '[Link]'>

print("type of t6 =", type(t6))

Example 11: Time duration in seconds


You can get the total number of seconds in a timedelta object using total_seconds() method.
from datetime import timedelta
t = timedelta(days = 5, hours = 1, seconds = 33, microseconds = 233423)
print("total seconds =", t.total_seconds())
total seconds = 435633.233423

PYTHON AJITH KUMAR J(BANGALORE)


101
PYTHON

Python format datetime


The way date and time is represented may be different in different places, organizations etc.
It's more common to use mm/dd/yyyy in the US, whereas dd/mm/yyyy is more common in
the UK.
Python has strftime() and strptime() methods to handle this.

Example 12: Format date using strftime()


from datetime import datetime
# current date and time
now = [Link]()
t = [Link]("%H:%M:%S")
print("time:", t)
s1 = [Link]("%m/%d/%Y, %H:%M:%S") time: 13:08:08
s1: 08/07/2019, 13:08:08
# mm/dd/YY H:M:S format
s2: 07/08/2019, 13:08:08
print("s1:", s1)
s2 = [Link]("%d/%m/%Y, %H:%M:%S")
# dd/mm/YY H:M:S format
print("s2:", s2)

Here, %Y, %m, %d, %H etc. are format codes. The strftime() method takes one or more
format codes and returns a formatted string based on it.

Python strptime() - string to datetime


The strptime() method creates a datetime object from a given string (representing date and
time).
Example 13: strptime()
from datetime import datetime date_string = 21 June, 2018
date_object = 2018-06-21 00:00:00
date_string = "21 June, 2018"
print("date_string =", date_string)
date_object = [Link](date_string, "%d %B, %Y")
print("date_object =", date_object)

PYTHON AJITH KUMAR J(BANGALORE)


102
PYTHON

The strptime() method takes two arguments:


1. a string representing date and time
2. format code equivalent to the first argument
By the way, %d, %B and %Y format codes are used for day, month(full name)
and year respectively.

Getting calendar for a month


The calendar module gives a wide range of methods to play with yearly and monthly
calendars.
Example 14: To Print the specific calendar
import calendar
cal = [Link](2019, 8)
print ("Here is the calendar:")
print (cal)

PYTHON AJITH KUMAR J(BANGALORE)


103
PYTHON

Python 3 – Functions, Modules and Packages

Functions
A function is a set of statements that take inputs, do some specific computation and produces
output. The idea is to put some commonly or repeatedly done task together and make a
function, so that instead of writing the same code again and again for different inputs, we can
call the function.
Functions help break our program into smaller and modular chunks. As our program grows
larger and larger, functions make it more organized and manageable.

Types of Functions
Basically, we can divide functions into the following two types:
1. Built-in functions - Functions that are built into Python.
2. User-defined functions - Functions defined by the users themselves.

Python Built-in functions

The Python interpreter has many functions that are always available for use. These functions
are called built-in functions. For example, print() function prints the given object to the
standard output device (screen).

Python abs()
The abs() method returns the absolute value of the given number. If the number is a complex
number, abs() returns its magnitude.
#random integer number
num1 = -20
print('Absolute value of -20 is:', abs(integer))

#random floating number


num2 = -30.33
print('Absolute value of -30.33 is:', abs(floating))

Python input()
The input() method reads a line from input, converts into a string and returns it.
# get input from user
inputString = input('Enter a string:')
print('The inputted string is:', inputString)

PYTHON AJITH KUMAR J(BANGALORE)


104
PYTHON

print("Please choice operation -\n"


"1. Add\n"
"2. Subtract\n"
"3. Multiply\n"
"4. Divide\n")

# Take input from the user


choice = input("choose operations form 1, 2, 3, 4 :")

number_1 = int(input("Enter first number: "))


number_2 = int(input("Enter second number: "))

if choice == '1':
print(number_1, "+", number_2, "=",
(number_1 + number_2))

elif choice == '2':


print(number_1, "-", number_2, "=",
(number_1 - number_2))

elif choice == '3':


print(number_1, "*", number_2, "=",
(number_1 * number_2))

elif choice == '4':


print(number_1, "/", number_2, "=",
(number_1 / number_2))
else:
print("Invalid input")

PYTHON AJITH KUMAR J(BANGALORE)


105
PYTHON

Python len()
The len() function returns the number of items (length) in an object.

# len() works with tuples, lists and range also


testList = []
print(testList, 'length is', len(testList)) [] length is 0

testList = [1, 2, 3]
[1, 2, 3] length is 3
print(testList, 'length is', len(testList))

testTuple = (1, 2, 3)
(1, 2, 3) length is 3
print(testTuple, 'length is', len(testTuple))

testRange = range(1, 10)


print('Length of', testRange, 'is', len(testRange)) Length of range(1, 10) is 9

Python pow()
The pow() method returns x to the power of y. If the third argument (z) is given, it returns x
to the power of y modulus z, i.e. pow(x, y) % z.
# positive x, positive y (x**y)
4
print(pow(2, 2))

4
# negative x, positive y
print(pow(-2, 2))

# positive x, negative y (x**-y) 0.25


print(pow(2, -2))

# negative x, negative y
print(pow(-2, -2)) 0.25

PYTHON AJITH KUMAR J(BANGALORE)


106
PYTHON

Python User-defined Functions

Functions that we define ourselves to do certain specific task are referred as user-defined
functions.
Function definition
Syntax:
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]

Above shown is a function definition which consists of following components.


1. Keyword def marks the start of function header.
2. A function name to uniquely identify it. Function naming follows the same rules of
writing identifiers in Python.
3. Parameters (arguments) through which we pass values to a function. They are
optional.
4. A colon (:) to mark the end of function header.
5. Optional documentation string (docstring) to describe what the function does.
6. One or more valid python statements that make up the function body. Statements must
have same indentation level (usually 4 spaces).
7. An optional return statement to return a value from the function.

Example of a function:
def greet(name):
"""This function greets to
the person passed in as
parameter"""
print("Hello, " + name + ". Good morning!")

PYTHON AJITH KUMAR J(BANGALORE)


107
PYTHON

Calling a function in Python:


Defining a function gives it a name, specifies the parameters that are to be included in the
function and structures the blocks of code.
Once we have defined a function, we can call it from another function, program or even the
Python prompt. To call a function we simply type the function name with appropriate
parameters.

# Function definition is here


def greet(name):
"""This function greets to
the person passed in as
parameter"""
print("Hello, " + name + ". Good morning!")

# Now you can call greet function


greet('Ajith') Hello, Ajith. Good morning!
Hello, Rajan. Good morning!
greet('Rajan')

Docstring

The first string after the function header is called the docstring and is short for documentation
string. It is used to explain in brief, what a function does.
Although optional, documentation is a good programming practice.
In the above example, we have a docstring immediately below the function header. We
generally use triple quotes so that docstring can extend up to multiple lines.

The return statement


The return statement is used to exit a function and go back to the place from where it was
called.
Syntax of return
return [expression_list]
This statement can contain expression which gets evaluated and the value is returned. If there
is no expression in the statement or the return statement itself is not present inside a function,
then the function will return the None object.

PYTHON AJITH KUMAR J(BANGALORE)


108
PYTHON

Example of return
def absolute_value(num):
"""This function returns the absolute
value of the entered number"""
if num >= 0:
return num
else:
return -num
print(absolute_value(2)) 2
4
print(absolute_value(-4))

Scope and Lifetime of variables


Scope of a variable is the portion of a program where the variable is recognized. Parameters
and variables defined inside a function is not visible from outside. Hence, they have a local
scope.
Lifetime of a variable is the period throughout which the variable exits in the memory. The
lifetime of variables inside a function is as long as the function executes.
They are destroyed once we return from the function. Hence, a function does not remember
the value of a variable from its previous calls.

def my_func():
x = 10
print("Value inside function:",x)

x = 20 Value inside function: 10


Value outside function: 20
my_func()
print("Value outside function:",x)

PYTHON AJITH KUMAR J(BANGALORE)


109
PYTHON

Pass by Reference vs Value


All parameters (arguments) in the Python language are passed by reference. It means if you
change what a parameter refers to within a function, the change also reflects back in the
calling function.
#Function Definition
def changeme( mylist ):
"This changes a passed list into this function"
print ("Values inside the function before change: ", mylist) Values inside the function before change:
[10, 20, 30]
mylist[2]=50
Values inside the function after change:
print ("Values inside the function after change: ", mylist) [10, 20, 50]
return

# Now you can call changeme function


mylist = [10,20,30]
changeme( mylist ) #Function Call
print ("Values outside the function: ", mylist)
Values outside the function: [10, 20, 50]

Function Arguments

Functions which are passed as arguments are called Function Arguments.


Function can be called by using the following types of formal arguments:
 Required arguments
 Keyword arguments
 Default arguments
 Variable-length arguments

Required Arguments
Required arguments are the arguments passed to a function in correct positional order.
To call the function square( ), user need to pass one argument, else it gives a syntax error as
follows:-
# Function definition is here
def square(x):
y = x ** 2
return y

PYTHON AJITH KUMAR J(BANGALORE)


110
PYTHON

# Now you can call square function

result = square( )
print(result)

When the above code is executed, it produces the following result:-


Traceback (most recent call last):
File "C:\Users \Python37-32\Python Files\[Link]", line 7, in <module>
result = square()
TypeError: square() missing 1 required positional argument: 'x'

Keyword Argument
Keyword arguments are related to the function calls. When you use keyword arguments in a
function call, the caller identifies the arguments by the parameter name.
# Function definition is here
def square(x):
y = x ** 2
return y

# Now you can call square function

result = square(x = 5 )
print(result)

When the above code is executed, it produces the following result:-


25

Default Arguments
A default argument is an argument that assumes a default value if a value is not provided in
the function call for that argument.
# Function definition is here
def square(x=3):
y = x ** 2
return y
PYTHON AJITH KUMAR J(BANGALORE)
111
PYTHON

# Now you can call square function


result1 = square(x = 5 )
print(result1)
result2 = square()
print(result2)

When the above code is executed, it produces the following result:-


25
9

Variable-length Arguments
You may need to process a function for more arguments than you specified while defining
the function. These arguments are called variable-length arguments.
In Python, the single-asterisk form of *args can be used as a parameter to send a non-
keyworded variable-length argument list to functions. It is worth noting that the asterisk (*) is
the important element here.

Example 1: Example 2: Error as the number of arguments are more while calling
def multiply(x, y): def multiply(x, y):
print (x * y) print (x * y)

multiply(5, 4) multiply(5, 4, 3)

Output: Output:
20 TypeError: multiply() takes 2 positional arguments but 3 were give

Example 3: Solution
def multiply(*args):
z=1
for num in args:
z *= num
print(z)

PYTHON AJITH KUMAR J(BANGALORE)


112
PYTHON

multiply(4, 5)
20
multiply(10, 9) 90
24
multiply(2, 3, 4)
900
multiply(3, 5, 10, 6)

Modules
A module allows you to logically organize your Python code. Grouping related code into a
module makes the code easier to understand and use.
Consider a module to be the same as a code library. A file containing a set of functions you
want to include in your application.
Python modules are .py files that consist of Python code. Any Python file can be referenced
as a module.

Create a Module
To create a module just save the code you want in a file with the file extension .py
Example: [Link]
def mul(x, y):
print (x * y)

Use of Module
Now we can use the module we just created, by using the import statement:
Example:
import Multiplication
[Link](3,6)

Re-naming a Module
You can create an alias when you import a module, by using the as keyword:
Example:
import Multiplication as Mu
[Link](3,9)

PYTHON AJITH KUMAR J(BANGALORE)


113
PYTHON

Built – in Modules
There are several built-in modules in Python, which you can import depending on the
requirement.
Example: Import and use the platform module
import platform
x = [Link]()
Windows
print(x) # help('modules')

Using the dir() Function


The dir() built-in function returns a sorted list of strings containing the names defined by a
module.
Example: Import built-in module math
import math ['acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'cos', 'cosh', 'degrees', 'e',
'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot',
x = dir(math) 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10',, 'log2', 'modf',
'nan', 'pi', 'pow', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
print(x)

Import from Module


You can choose to import only parts from a module, by using the from keyword.
from random import randint
Guess the secret number: 3
secret_num = randint(1,10) Guess the secret number: 6
Guess the secret number: 8
guess = 0
Guess the secret number: 2
while guess != secret_num: You finally got it!

guess = int(input('Guess the secret number: '))


print('You finally got it!')

Packages
We don't usually store all our files in our computer in the same location. We use a well-
organized hierarchy of directories for easier access
Python has packages for directories and modules for files.
As our application program grows larger in size with a lot of modules, we place similar
modules in one package and different modules in different packages. This makes a project
(program) easy to manage and conceptually clear.

PYTHON AJITH KUMAR J(BANGALORE)


114
PYTHON

Similar, as a directory can contain sub-directories and files, a Python package can have sub-
packages and modules.
A directory must contain a file named __init__.py in order for Python to consider it as a
package. This file can be left empty but we generally place the initialization code for that
package in this file.

Here is an example. Suppose we are developing a game, one possible organization of


packages and modules could be as shown in the figure below.

Importing module from a package

We can import modules from packages using the dot (.) operator.

For example, if want to import the start module in the above example, it is done as follows
import [Link]

Now if this module contains a function named select_difficulty(), we must use the full name
to reference it.
[Link].select_difficulty(2)
If this construct seems lengthy, we can import the module without the package prefix as
follows.
from [Link] import start
We can now call the function simply as follows.
start.select_difficulty(2)

PYTHON AJITH KUMAR J(BANGALORE)


115
PYTHON

Yet another way of importing just the required function (or class or variable) form a module
within a package would be as follows.
from [Link] import select_difficulty
Now we can directly call this function.
select_difficulty(2)

PYTHON AJITH KUMAR J(BANGALORE)


116
PYTHON

Files
File is a named location on disk to store related information. It is used to permanently store
data in a non-volatile memory (e.g. hard disk).
When we want to read from or write to a file we need to open it first. When we are done, it
needs to be closed, so that resources that are tied with the file are freed.
Hence, in Python, a file operation takes place in the following order.
1. Open a file
2. Read or write (perform operation)
3. Close the file

Opening a file

Python has a built-in function open() to open a file. This function returns a file object, also
called a handle, as it is used to read or modify the file accordingly.
f = open("[Link]") # open file in current directory
f = open("C:/Python33/[Link]") # specifying full path

We can specify the mode while opening a file. In mode, we specify whether we want to
read 'r', write 'w' or append 'a' to the file. We also specify if we want to open the file in text
mode or binary mode.
The default is reading in text mode. In this mode, we get strings when reading from the file.
On the other hand, binary mode returns bytes and this is the mode to be used when dealing
with non-text files like image or exe files.

Mode Description

'r' Open a file for reading. (default)

Open a file for writing. Creates a new file if it does not exist or truncates the file
'w' if it exists.

'x' Open a file for exclusive creation. If the file already exists, the operation fails.

Open for appending at the end of the file without truncating it. Creates a new file
'a' if it does not exist.

PYTHON AJITH KUMAR J(BANGALORE)


117
PYTHON

't' Open in text mode. (default)

'b' Open in binary mode.

'+' Open a file for updating (reading and writing)

Example:
f = open("[Link]") # equivalent to 'r' or 'rt'
f = open("[Link]",'w') # write in text mode
f = open("[Link]",'r+b') # read and write in binary mode

Note: When working with files in text mode, it is highly recommended to specify the encoding
type.

f = open("[Link]",mode = 'r',encoding = 'utf-8')

Closing a file
When we are done with operations to the file, we need to properly close the file.
Closing a file will free up the resources that were tied with the file and is done using
Python close() method.
Python has a garbage collector to clean up unreferenced objects but, we must not rely on it to
close the file.
f = open("[Link]",encoding = 'utf-8')
# perform file operations
[Link]()
This method is not entirely safe. If an exception occurs when we are performing some operation
with the file, the code exits without closing the file.
A safer way is to use a try...finally block.
try:
f = open("[Link]",encoding = 'utf-8')
# perform file operations
finally:
[Link]()

PYTHON AJITH KUMAR J(BANGALORE)


118
PYTHON

This way, we are guaranteed that the file is properly closed even if an exception is raised,
causing program flow to stop.
The best way to do this is using the with statement. This ensures that the file is closed when
the block inside with is exited.
We don't need to explicitly call the close() method. It is done internally.

with open("[Link]",encoding = 'utf-8') as f:


# perform file operations

Writing into files


In order to write into a file in Python, we need to open it in write 'w', append 'a' or exclusive
creation 'x' mode.
We need to be careful with the 'w' mode as it will overwrite into the file if it already exists. All
previous data are erased.
Writing a string or sequence of bytes (for binary files) is done using write() method. This
method returns the number of characters written to the file.

with open("[Link]",'w',encoding = 'utf-8') as f:


[Link]("This is my first file\n")
[Link]("This file\n\n")
[Link]("contains three lines\n")
This program will create a new file named '[Link]' if it does not exist. If it does exist, it is
overwritten.
We must include the newline characters ourselves to distinguish different lines.

The method writelines() writes a sequence of strings to the file. The sequence can be any
iterable object producing strings, typically a list of strings.
f = open("[Link]",'r+',encoding = 'utf-8')
print ("Name of the file: ", [Link])
seq = ["This is 4th line\n", "This is 5th line"]
# Write sequence of lines at the end of the file.
[Link](0, 2)
line = [Link]( seq )

PYTHON AJITH KUMAR J(BANGALORE)


119
PYTHON

# Now read complete file from beginning.


[Link](0,0)
for line in f:
print(line)
# Close opened file
[Link]()

Reading from files


To read a file in Python, we must open the file in reading mode.
There are various methods available for this purpose. We can use the read(size) method to read
in size number of data. If size parameter is not specified, it reads and returns up to the end of
the file.
Example:
f = open("[Link]",'r',encoding = 'utf-8')
[Link](4) # read the first 4 data
[Link](4) # read the next 4 data
[Link]() # read in the rest till end of file
[Link]() # further reading returns empty sting

Manipulating file pointer using seek()


We can change our current file cursor (position) using the seek() method. Similarly,
the tell() method returns our current position (in number of bytes).
[Link]() # get the current file position
[Link](0) # bring file cursor to initial position
print([Link]()) # read the entire file
Example:
f = open("[Link]",'r',encoding = 'utf-8')
print([Link](4))
print([Link]())
print([Link](4))
print([Link](0))
print([Link]())

PYTHON AJITH KUMAR J(BANGALORE)


120
PYTHON

We can read a file line-by-line using a for loop. This is both efficient and fast.
f = open("[Link]",'r',encoding = 'utf-8')
for line in f:
print(line, end = '')

Alternately, we can use readline() method to read individual lines of a file.


Example:
f = open("[Link]",'r',encoding = 'utf-8')
print([Link]())
print([Link]())
print([Link]())
print([Link]())

Lastly, the readlines() method returns a list of remaining lines of the entire file. All these
reading method return empty values when end of file (EOF) is reached.
Example:
f = open("[Link]",'r',encoding = 'utf-8')
print([Link]())

Directory in Python
If there are many files to handle in your Python program, you can arrange your code within
different directories to make things more manageable.
A directory or folder is a collection of files and sub directories. Python has the os module,
which provides us with many useful methods to work with directories (and files as well).

Get Current Directory


We can get the present working directory using the getcwd() method.
This method returns the current working directory in the form of a string.
import os
print([Link]())

PYTHON AJITH KUMAR J(BANGALORE)


121
PYTHON

Changing Directory

We can change the current working directory using the chdir() method.
The new path that we want to change to must be supplied as a string to this method. We can
use both forward slash (/) or the backward slash (\) to separate path elements.
It is safer to use escape sequence when using the backward slash.
[Link]('C:\\Python33')
print([Link]())

List Directories and Files

All files and sub directories inside a directory can be known using the listdir() method.
This method takes in a path and returns a list of sub directories and files in that path. If no
path is specified, it returns from the current working directory.
import os
print([Link]())

Making a New Directory


We can make a new directory using the mkdir() method.
This method takes in the path of the new directory. If the full path is not specified, the new
directory is created in the current working directory.
import os
[Link]('demo_dir')
print([Link]())

Renaming a Directory or a File


The rename() method can rename a directory or a file.
The first argument is the old name and the new name must be supplies as the second
argument.
import os
print([Link]())
[Link]('test_dir','demo_dir')
print([Link]())

PYTHON AJITH KUMAR J(BANGALORE)


122
PYTHON

Removing Directory or File


A file can be removed (deleted) using the remove() method.
Similarly, the rmdir() method removes an empty directory.
import os
print([Link]())
[Link]('[Link]')
[Link]('demo_dir')
print([Link]())

Note: rmdir() method can only remove empty directories.

In order to remove a non-empty directory we can use the rmtree() method inside
the shutil module.
import os
import shutil
print([Link]())
[Link]('test')
print([Link]())

PYTHON AJITH KUMAR J(BANGALORE)


123
PYTHON

Object Oriented programming - OOPs

Python has been an object-oriented language since the time it existed. Due to this, creating
and using classes and objects are downright easy.

Overview of OOP Terminology


Class:
A variable that is shared by all instances of a class. Class variables are defined within a class.
Class variable: A variable that is shared by all instances of a class. Class variables are defined
within a class. Class variables are not used as frequently as instance variables.

Data member: A class variable or instance variable that holds data associated with a class and
its objects.
Function overloading: The assignment of more than one behaviour to a particular function. The
operation performed varies by the types of objects or arguments involved.
Instance variable: A variable that is defined inside a method and belongs only to the current
instance of a class.
Inheritance: The transfer of the characteristics of a class to other classes that are derived from
it.
Instance: An individual object of a certain class. An object obj that belongs to a class Circle, for
example, is an instance of the class Circle.
Instantiation: The creation of an instance of a class.

Method: A special kind of function that is defined in a class definition.

Object: A unique instance of a data structure that is defined by its class. An object comprises
both data members (class variables and instance variables) and methods.
Operator overloading: The assignment of more than one function to a particular operator.

Creating Classes
The class statement creates a new class definition. The name of the class immediately follows
the keyword class followed by a colon as follows
Syntax:
class ClassName:
'Optional class documentation string'
class_suite

PYTHON AJITH KUMAR J(BANGALORE)


124
PYTHON

 The class_suite consists of all the component statements defining class members, data
attributes and functions.
Example:
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
[Link] = name
[Link] = salary
[Link] += 1
def displayCount(self):
print ("Total Employee %d" % [Link])
def displayEmployee(self):
print ("Name : ", [Link], ", Salary: ", [Link])

 The variable empCount is a class variable whose value is shared among all the instances
of a in this class. This can be accessed as [Link] from inside the class or
outside the class.

 The first method __init__() is a special method, which is called class constructor or
initialization method that Python calls when you create a new instance of this class.

 You declare other class methods like normal functions with the exception that the first
argument to each method is self. Python adds the self argument to the list for you; you
do not need to include it when you call the methods.

Creating Instance Objects


To create instances of a class, you call the class using class name and pass in whatever
arguments its __init__ method accepts.
Example:
This would create first object of Employee class
emp1 = Employee("Zara", 2000)
This would create second object of Employee class
emp2 = Employee("Manni", 5000)
PYTHON AJITH KUMAR J(BANGALORE)
125
PYTHON

Accessing Attributes
You access the object's attributes using the dot operator with object. Class variable would be
accessed using class name as follows:-
[Link]()
[Link]()
print ("Total Employee %d" % [Link])

Complete Example:
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
[Link] = name
[Link] = salary
[Link] += 1
def displayCount(self):
print ("Total Employee %d" % [Link])
def displayEmployee(self):
print ("Name : ", [Link], ", Salary: ", [Link])

#This would create first object of Employee class"


emp1 = Employee("Zara", 2000)
#This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
[Link]()
[Link]()
print ("Total Employee %d" % [Link])

Name : Zara , Salary: 2000


Name : Manni , Salary: 5000
Total Employee 2

PYTHON AJITH KUMAR J(BANGALORE)


126
PYTHON

Built-in class Attributes

Every Python class keeps the 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:
class Employee:
empCount = 0
def __init__(self, name, salary):
[Link] = name
[Link] = salary
[Link] += 1

def displayCount(self):
print ("Total Employee %d" % [Link])
def displayEmployee(self):
print ("Name : ", [Link], ", Salary: ", [Link])

emp1 = Employee("Zara", 2000)


emp2 = Employee("Manni", 5000)
print ("Employee.__doc__:", Employee.__doc__)
print ("Employee.__name__:", Employee.__name__)
print ("Employee.__module__:", Employee.__module__)
print ("Employee.__bases__:", Employee.__bases__)
print ("Employee.__dict__:", Employee.__dict__ )

PYTHON AJITH KUMAR J(BANGALORE)


127
PYTHON

Employee.__doc__: None
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: (<class 'object'>,)
Employee.__dict__: {'__module__': '__main__', 'empCount': 2, '__init__': <function Employee.__init__ at
0x0541E6A8>, 'displayCount': <function [Link] at 0x05BD6C00>, 'displayEmployee':
<function [Link] at 0x060570C0>, '__dict__': <attribute '__dict__' of 'Employee'
objects>, '__weakref__': <attribute '__weakref__' of 'Employee' objects>, '__doc__': None}

Destroying Objects

Python deletes unneeded objects (built-in types or class instances) automatically to free the
memory space. The process by which Python periodically reclaims blocks of memory that no
longer are in use is termed as Garbage Collection.
Python's garbage collector runs during program execution and is triggered when an object's
reference count reaches zero. An object's reference count changes as the number of aliases
that point to it changes
An object's reference count increases when it is assigned a new name or placed in a container
(list, tuple, or dictionary). The object's reference count decreases when it is deleted with del,
its reference is reassigned, or its reference goes out of scope. When an object's reference
count reaches zero, Python collects it automatically.
a = 40 # Create object <40>
b=a # Increase ref. count of <40>
c = [b] # Increase ref. count of <40>
del a # Decrease ref. count of <40>
b = 100 # Decrease ref. count of <40>
c[0] = -1 # Decrease ref. count of <40>

You normally will not notice when the garbage collector destroys an orphaned instance and
reclaims its space. However, a class can implement the special method__del__(), called a
destructor, that is invoked when the instance is about to be destroyed. This method might be
used to clean up any non-memory resources used by an instance.

PYTHON AJITH KUMAR J(BANGALORE)


128
PYTHON

Example:
This __del__() destructor prints the class name of an instance that is about to be destroyed.
class Point:
def __init( self, x=0, y=0):
self.x = x
self.y = y
def __del__(self):
class_name = self.__class__.__name__
print (class_name, "destroyed")

pt1 = Point()
pt2 = pt1
pt3 = pt1
print (id(pt1), id(pt2), id(pt3))
# prints the ids of the obejcts
del pt1
97603632 97603632 97603632
del pt2 Point destroyed
del pt3

Inheritance
Inheritance is a powerful feature in object oriented programming.
It refers to defining a new class with little or no modification to an existing class. The new
class is called derived (or child) class and the one from which it inherits is called the base
(or parent) class.
For Example;
class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class

PYTHON AJITH KUMAR J(BANGALORE)


129
PYTHON

Syntax:
class SubClassName (ParentClass1[, ParentClass2, ...]):
'Optional class documentation string'
class_suite

Example:
class Parent: # define parent class
parentAttr = 100
def __init__(self):
print ("Calling parent constructor")
def parentMethod(self):
print ('Calling parent method')
def setAttr(self, attr):
[Link] = attr
def getAttr(self):
print ("Parent attribute :", [Link])

class Child(Parent): # define child class


def __init__(self):
print ("Calling child constructor")
def childMethod(self):
print ('Calling child method')

c = Child() # instance of child


[Link]() # child calls its method
[Link]() # calls parent's method
[Link](200) # again call parent's method
[Link]() # again call parent's method

Calling child constructor


Calling child method
Calling parent method
Parent attribute : 200

PYTHON AJITH KUMAR J(BANGALORE)


130
PYTHON

In a similar way, you can drive a class from multiple parent classes as follows
class A: # define your class A
.....
class B: # define your calss B
.....
class C(A, B): # subclass of A and B
.....

You can use issubclass() or isinstance() functions to check a relationship of two classes
and instances.
 The issubclass(sub, sup) boolean function returns True, if the given subclass sub is
indeed a subclass of the superclass sup.
 The isinstance(obj, Class) boolean function returns True, if obj is an instance of class
Class or is an instance of a subclass of Class.

Overriding Methods
You can always override your parent class methods. One reason for overriding parent's
methods is that you may want special or different functionality in your subclass.
class Parent: # define parent class
def myMethod(self):
print ('Calling parent method')

class Child(Parent): # define child class


def myMethod(self):
print ('Calling child method')
c = Child() # instance of child
[Link]() # child calls overridden method

Calling child method

PYTHON AJITH KUMAR J(BANGALORE)


131
PYTHON

Method Overloading: NOT SUPPORTED IN PYTHON


Python does not supports method overloading. We may overload the methods but can only
use the latest defined method.
Example
# First product method.
# Takes two argument and print their
# product
def product(a, b):
p=a*b
print(p)

# Second product method


# Takes three argument and print their
# product
def product(a, b, c):
p = a * b*c
print(p)

# Uncommenting the below line shows an error


#product(4, 5)

# This line will call the second product method


product(3,6 , 9)

162

PYTHON AJITH KUMAR J(BANGALORE)


132
PYTHON

Overloading Operators

Operator Overloading means giving extended meaning beyond their predefined operational
meaning. For example, operator + is used to add two integers as well as join two strings and
merge two lists. It is achievable because ‘+’ operator is overloaded by int class and str class.
You might have noticed that the same built-in operator or function shows different behavior
for objects of different classes, this is called Operator Overloading.
Example
# Python program to show use of
# + operator for different purposes.
print(1 + 2)
# concatenate two strings
print("Python"+"Programming")
# Product two numbers 3
print(3 * 4) PythonProgramming
12
# Repeat the String pythonpythonpythonpython

print("python"*4)

Overloading binary + operator in Python

When we use an operator on user defined data types then automatically a special function or
magic function associated with that operator is invoked. Changing the behaviour of operator
is as simple as changing the behavior of method or function. You define methods in your
class and operators work according to that behavior defined in methods. When we use +
operator, the magic method __add__ is automatically invoked in which the operation for +
operator is defined. There by changing this magic method’s code, we can give extra meaning
to the + operator.
Example
# Python Program to perform addition of two complex numbers using binary
# + operator overloading.
class complex:
def __init__(self, a, b):
self.a = a
self.b = b

PYTHON AJITH KUMAR J(BANGALORE)


133
PYTHON

# adding two objects


def __add__(self, other):
return self.a + other.a, self.b + other.b

def __str__(self):
return self.a, self.b

Ob1 = complex(1, 2)
Ob2 = complex(2, 3)
Ob3 = Ob1 + Ob2 (3, 5)

print(Ob3)

Binary Operators:

OPERATOR MAGIC METHOD

+ __add__(self, other)

– __sub__(self, other)

* __mul__(self, other)

/ __truediv__(self, other)

// __floordiv__(self, other)

% __mod__(self, other)

** __pow__(self, other)

PYTHON AJITH KUMAR J(BANGALORE)


134
PYTHON

Comparison Operator

OPERATOR MAGIC METHOD

< __lt__(self, other)

> __gt__(self, other)

<= __le__(self, other)

>= __ge__(self, other)

== __eq__(self, other)

!= __ne__(self, other)

Data Hiding

An object's attributes may or may not be visible outside the class definition. You need to
name attributes with a double underscore prefix, and those attributes then will not be directly
visible to outsiders.
Example
class JustCounter:
__secretCount = 0

def count(self):
self.__secretCount += 1
print (self.__secretCount)

1
counter = JustCounter() 2
Traceback (most recent call last):
[Link]() File "C:\Users\Programs\Python\Python37-32\Python
[Link]() Files\[Link]", line 11, in <module>
print (counter.__secretCount)
print (counter.__secretCount) AttributeError: 'JustCounter' object has no attribute '__secretCount'

PYTHON AJITH KUMAR J(BANGALORE)


135
PYTHON

Python protects those members by internally changing the name to include the class name.
You can access such attributes as object._className__attrName.
If you would replace your last line as following, then it works for you-
print (counter._JustCounter__secretCount)

PYTHON AJITH KUMAR J(BANGALORE)


136
PYTHON

Regular Expression

A regular expression is a special sequence of characters that helps you match or find other
strings or sets of strings, using a specialized syntax held in a pattern.
Module Regular Expressions (RE) specifies a set of strings(pattern) that matches it.

Regular Expression Patters:


[] Represent a character class
^ Matches the beginning
$ Matches the end
. Matches any character except newline
? Matches zero or one occurrence.
| Means OR (Matches with any of the characters
separated by it.
* Any number of occurrences (including 0 occurrences)
+ One ore more occurrences
{} Indicate number of occurrences of a preceding RE
to match.
() Enclose a group of Res
\ Used to drop the special meaning of character
following it (discussed below)
\d Matches any decimal digit, this is equivalent
to the set class [0-9].
\D Matches any non-digit character.
\s Matches any whitespace character.
\S Matches any non-whitespace character
\w Matches any alphanumeric character, this is
equivalent to the class [a-zA-Z0-9_].
\W Matches any non-alphanumeric character.

The module re provides support for regular expressions in Python. Below are main methods
in this module.

PYTHON AJITH KUMAR J(BANGALORE)


137
PYTHON

match function
[Link]( ) : This function attempts to match pattern to whole string. The [Link] function
returns a match object on success, None on failure.
Syntax:
[Link](pattern, string, flags=0)
Parameters:
pattern : Regular expression to be matched.
string : String where pattern is searched
flags : We can specify different flags using bitwise OR (|).

Example:
# A Python program to demonstrate working of [Link]().
import re
# a sample function that uses regular expressions to find month and day of a date.
def findMonthAndDate(string):
regex = r"([a-zA-Z]+) (\d+)"
match = [Link](regex, string)

if match == None:
print ("Not a valid date")
return

print ("Given Data: %s" % ([Link]()) )


print ("Month: %s" % ([Link](1)) )
print ("Day: %s" % ([Link](2)) )

# Driver Code Given Data: June 24


findMonthAndDate("June 24") Month: June
Day: 24
print("")
Not a valid date
findMonthAndDate("I was born on Aug 26")

PYTHON AJITH KUMAR J(BANGALORE)


138
PYTHON

search function
[Link]() : This method either returns None (if the pattern doesn’t match), or a
[Link] that contains information about the matching part of the string. This method
stops after the first match.

Syntax:
re. search (pattern, string, flags=0)
Parameters:
pattern : Regular expression to be matched.
string : String where pattern is searched
flags : We can specify different flags using bitwise OR (|).

The [Link] function returns a match object on success, none on failure.

Example:
# A Python program to demonstrate working of [Link]().
import re

# Lets use a regular expression to match a date string


# in the form of Month name followed by day number
# \d is equivalent to [0-9].
# \d+ will match a group on [0-9], group of one or greater size
regex = r"([a-zA-Z]+) (\d+)"

match = [Link](regex, "I was born on June 24")

if match != None:

# We reach here when the expression "([a-zA-Z]+) (\d+)"


# matches the date string.

PYTHON AJITH KUMAR J(BANGALORE)


139
PYTHON

# This will print [14, 21), since it matches at index 14


# and ends at 21.
print ("Match at index %s, %s" % ([Link](), [Link]()) )

# We us group() method to get all the matches and


# captured groups. The groups contain the matched values.
# In particular:
# [Link](0) always returns the fully matched string
# [Link](1) [Link](2), ... return the capture
# groups in order from left to right in the input string
# [Link]() is equivalent to [Link](0)

# So this will print "June 24"


print ("Full match: %s" % ([Link](0)) )

# So this will print "June"


print ("Month: %s" % ([Link](1)) )

# So this will print "24"


print ("Day: %s" % ([Link](2)) )

else:
print ("The regex pattern does not match.")

Match at index 14, 21


Full match: June 24
Month: June
Day: 24

PYTHON AJITH KUMAR J(BANGALORE)


140
PYTHON

[Link]()
This method return all non-overlapping matches of pattern in string, as a list of strings. The
string is scanned left-to-right, and matches are returned in the order found .
Example:
# A Python program to demonstrate working of
# findall()
import re

# A sample text string where regular expression


# is searched.
string = """Hello my Number is 123456789 and
my friend's number is 987654321"""

# A sample regular expression to find digits.


regex = '\d+'
['123456789', '987654321']

match = [Link](regex, string)


print(match)

Search and Replace


One of the most important re methods that use regular expressions is sub.
Syntax:
[Link](pattern, repl, string)
This method replaces all occurrences of the RE pattern in string with repl, substituting all
occurrences. This method returns modified string.
Example:
import re
text = "Python is a very cool Programming Language"
text2 = [Link]("cool", "good", text)
print(text2) Python is a very good Programming
Language

PYTHON AJITH KUMAR J(BANGALORE)


141
PYTHON

Regular Expression Patterns


Except for the control characters, (+ ? . * ^ $ ( ) [ ] { } | \), all characters match themselves.
The following table lists the regular expression syntax that is available in Python

Pattern Description
^ Matches beginning of line
$ Matches end of line.
. Matches any single character except newline.
[...] Matches any single character in brackets.
[^...] Matches any single character not in brackets
re* Matches 0 or more occurrences of preceding expression.
re+ Matches 1 or more occurrence of preceding expression.
a| b Matches either a or b.
\w Matches word characters
\W Matches nonword characters.
\s Matches whitespace. Equivalent to [\t\n\r\f].
\S Matches nonwhitespace.
\d Matches digits. Equivalent to [0-9].
\D Matches nondigits.
\A Matches beginning of string.
\Z Matches end of string. If a newline exists, it matches just before newline.
\z Matches end of string.

Regular Expression Examples

Literal Characters:
Example Description
python Match "python"

Character classes:
Example Description
[Pp]ython Match "Python" or "python"
rub[ye] Match "ruby" or "rube"
[aeiou] Match any one lowercase vowel
[0-9] Match any digit; same as [0123456789]
[a-z] Match any lowercase ASCII letter
[A-Z] Match any uppercase ASCII letter
[a-zA-Z0-9] Match any of the above
[^aeiou] Match anything other than a lowercase vowel
[^0-9] Match anything other than a digit

PYTHON AJITH KUMAR J(BANGALORE)


142
PYTHON

Exception Handling

Python provides two very important features to handle any unexpected error in your
Python programs and to add debugging capabilities in them-
 Exception Handling.
 Assertions.

Standard Exceptions

Exception: Base class for all exceptions


AttributeError: Raised in case of failure of attribute reference or assignment.
ArithmeticError: Base class for all errors that occur for numeric calculation.
EOFError: Raised when there is no input from either the raw_input() or input() function and
the end of file is reached.
NameError: Raised when an identifier is not found in the local or global namespace.
LookupError: Base class for all lookup errors.
StopIteration: Raised when the next() method of an iterator does not point to any object.
OSError: Raised for operating system-related errors.
TypeError: Raised when an operation or function is attempted that is invalid for the specified
data type.
ValueError: Raised when the built-in function for a data type has the valid type of arguments,
but the arguments have invalid values specified.

PYTHON AJITH KUMAR J(BANGALORE)


143
PYTHON

FloatingPointError: Raised when a floating point calculation fails.


OverflowError: Raised when a calculation exceeds maximum limit for a numeric type.
ZeroDivisonError: Raised when division or modulo by zero takes place for all numeric types.
IndexError: Raised when an index is not found in a sequence.
KeyError: Raised when the specified key is not found in the dictionary.
FileExistsError: Raised when we try to make the new directory tree even though I don't create
that directory tree anywhere else in the code.

Assertions in Python

Python has built-in assert statement to use assertion condition in the program. assert statement
has a condition or expression which is supposed to be always true. If the condition is false
assert halts the program and gives an AssertionError.
Syntax
1. assert <condition>
2. assert <condition>,<error message>

In Python we can use assert statement in two ways as mentioned above.


1. assert statement has a condition and if the condition is not satisfied the program will
stop and give AssertionError.
2. assert statement can also have a condition and a optional error message. If the
condition is not satisfied assert stops the program and gives AssertionError along with
the error message.

Example: Using assert without error message


def avg(marks):
assert len(marks) != 0
return sum(marks)/len(marks)

mark1 = [ ]
print("Average of mark1:",avg(mark1))

PYTHON AJITH KUMAR J(BANGALORE)


144
PYTHON

Traceback (most recent call last):


File "C:/Users /Programs/Python/Python37-32/Python Files/[Link]", line 6, in <module>
print("Average of mark1:",avg(mark1))
File "C:/Users /Programs/Python/Python37-32/Python Files/[Link]", line 2, in avg
assert len(marks) != 0
AssertionError

Example: Using assert with error message


def avg(marks):
assert len(marks) != 0,"List is empty."
return sum(marks)/len(marks)

mark2 = [55,88,78,90,79]
print("Average of mark2:",avg(mark2))

mark1 = []
print("Average of mark1:",avg(mark1))

Average of mark2: 78.0


Traceback (most recent call last):
File "C:/Users /Programs/Python/Python37-32/Python Files/[Link]", line 9, in <module>
print("Average of mark1:",avg(mark1))
File "C:/Users/ Programs/Python/Python37-32/Python Files/[Link]", line 2, in avg
assert len(marks) != 0,"List is empty."
AssertionError: List is empty.

Example:
def input_age(age):
try:
assert int(age) > 18
except ValueError:
return 'ValueError: Cannot convert into int'
else:
return 'Age is saved successfully'

PYTHON AJITH KUMAR J(BANGALORE)


145
PYTHON

print(input_age('23')) # This will print


print(input_age(25)) # This will print
print(input_age('nothing')) # This will raise ValueError which is handled
print(input_age('16')) # This will raise AssertionError and the the program collapse

Age is saved successfully


Age is saved successfully
ValueError: Cannot convert into int
Traceback (most recent call last):
File "C:\Users \Programs\Python\Python37-32\Python Files\[Link]", line 14, in <module>
print(input_age('16')) # This will raise AssertionError and the the program collapse
File "C:\Users \Programs\Python\Python37-32\Python Files\[Link]", line 4, in input_age
assert int(age) > 18
AssertionError

PYTHON AJITH KUMAR J(BANGALORE)


146
PYTHON

What is Exception?
An exception is an event, which occurs during the execution of a program that disrupts the
normal flow of the program's instructions. In general, when a Python script encounters a
situation that it cannot cope with, it raises an exception.
When a Python script raises an exception, it must either handle the exception immediately
otherwise it terminates and quits.

Handling an Exception
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
try:
You do your operations here
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.

Here are few important points about the above-mentioned syntax-


 A single try statement can have multiple except statements. This is useful when the
try block contains statements that may throw different types of exceptions.
 You can also provide a generic except clause, which handles any exception.
 After the except clause(s), you can include an else-clause. The code in the else-block
executes if the code in the try: block does not raise an exception.
 The else-block is a good place for code that does not need the try: block' protection

PYTHON AJITH KUMAR J(BANGALORE)


147
PYTHON

Example
This example opens a file, writes content in the file and comes out gracefully because there is
no problem at all.
try:
f = open("testfile", "w")
[Link]("This is my test file for exception handling!!")
except IOError:
print ("Error: can\'t find file or read data")
else:
print ("Written content in the file successfully")
[Link]()

Written content in the file successfully

Example
This example tries to open a file where you do not have the write permission, so it raises an
exception-
try:
f = open("testfile", "r")
[Link]("This is my test file for exception handling!!")
except IOError:
print ("Error: can\'t find file or read data")
else:
print ("Written content in the file successfully")
[Link]()

Error: can't find file or read data

PYTHON AJITH KUMAR J(BANGALORE)


148
PYTHON

The except clause with no Exceptions

You can also use the except statement with no exceptions defined as follows
Syntax
try:
You do your operations here
......................
except:
If there is any exception, then execute this block.
......................
else:
If there is no exception then execute this block.

This kind of a try-except statement catches all the exceptions that occur. Using this kind of
try-except statement is not considered a good programming practice though, because it
catches all exceptions but does not make the programmer identify the root cause of the
problem that may occur.

Example
import sys
randomList = ['a', 0, 2]
for entry in randomList:
try:
print("The entry is", entry) The entry is a
Oops! <class 'ValueError'> occured.
r = 1/int(entry) Next entry.

break The entry is 0


Oops! <class 'ZeroDivisionError'> occured.
except:
Next entry.
print("Oops!",sys.exc_info()[0],"occured.")
The entry is 2
print("Next entry.") The reciprocal of 2 is 0.5
print()
print("The reciprocal of",entry,"is",r)

PYTHON AJITH KUMAR J(BANGALORE)


149
PYTHON

The except clause with multiple exceptions


You can also use the same except statement to handle multiple exceptions as follows
Syntax
try:
You do your operations here
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block

The try-finally clause

You can use a finally: block along with a try: block. The finally: block is a place to put any
code that must execute, whether the try-block raised an exception or not.

Syntax
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................

In programming, there may be some situation in which the current method ends up while
handling some exceptions. But the method may require some additional steps before its
termination, like closing a file or a network and so on.
So, in order to handle these situations, Python provides a keyword finally, which is always
executed after try and except blocks. The finally block always executes after normal
termination of try block or after try block terminates due to some exception.

PYTHON AJITH KUMAR J(BANGALORE)


150
PYTHON

Example: Exception occurred and handled, finally executed


# Python program to demonstrate finally, Exception raised in try block
try:
k = 5//0 # raises divide by zero exception.
print(k)
# handles zerodivision exception
except ZeroDivisionError:
print("Can't divide by zero")
finally:
# this block is always executed regardless of exception generation.
Can't divide by zero
print('This is always executed') This is always executed

Example: No Exception raised, finally executed


# Python program to demonstrate finally
try:
k = 5//1 # No exception raised
print(k)
# intends to handle zerodivision exception
except ZeroDivisionError:
print("Can't divide by zero")
finally:
# this block is always executed
5
# regardless of exception generation. This is always executed
print('This is always executed')

Example: Exception not handled, finally executed


# Python program to demonstrate finally Exception is not handled
try:
k = 5//0 # exception raised
print(k)

PYTHON AJITH KUMAR J(BANGALORE)


151
PYTHON

finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')

This is always executed


Traceback (most recent call last):
File "C:/UsersPrograms/Python/Python37-32/Python Files/[Link]", line 5, in <module>
k = 5//0 # exception raised
ZeroDivisionError: integer division or modulo by zero

Argument of an Exception
An exception can have an argument, which is a value that gives additional information about
the problem.
Syntax:
try:
You do your operations here
......................
except ExceptionType as Argument:
You can print value of Argument here...
If you write the code to handle a single exception, you can have a variable follow the name of
the exception in the except statement. If you are trapping multiple exceptions, you can have a
variable follow the tuple of the exception.

Example:
# Define a function here.
def temp_convert(var):
try:
return int(var)
except ValueError as Argument:
print("The argument does not contain numbers\n",Argument)
# Call above function here. The argument does not contain numbers
temp_convert("xyz") invalid literal for int() with base 10: 'xyz'

PYTHON AJITH KUMAR J(BANGALORE)


152
PYTHON

Raising an Exception
You can raise exceptions in several ways by using the raise statement.
Syntax:
raise [Exception [, args [, traceback]]]

We can use raise to throw an exception if a condition occurs.

If you want to throw an error when a certain condition occurs using raise, you could go about
it like this:
Example;
x = 10
if x > 5:
raise Exception('x should not exceed 5. The value of x was: {}'.format(x))

Traceback (most recent call last):


File "C:/Users/ Programs/Python/Python37-32/Python Files/[Link]", line 3, in <module>
raise Exception('x should not exceed 5. The value of x was: {}'.format(x))
Exception: x should not exceed 5. The value of x was: 10

User-Defined Exception
Python also allows you to create your own exceptions by deriving classes from the standard
built-in exceptions.
Example:
class Networkerror(RuntimeError):
def __init__(self, arg):
[Link] = arg
try:
raise Networkerror('Bad hostname')
except Networkerror as e:
('B', 'a', 'd', ' ', 'h', 'o', 's', 't', 'n', 'a', 'm', 'e')
print([Link])

PYTHON AJITH KUMAR J(BANGALORE)


153
PYTHON

Runtime error is a class is a standard exception which is raised when a generated error does
not fall into any category. This program illustrates how to use runtime error as base class and
network error as derived class.
Example:
# define Python user-defined exceptions
class Error(Exception):
"""Base class for other exceptions"""
pass
class ValueTooSmallError(Error):
"""Raised when the input value is too small"""
pass
class ValueTooLargeError(Error):
"""Raised when the input value is too large"""
pass
# User guesses a number until he/she gets it right, you need to guess this number
number = 10
while True:
try:
i_num = int(input("Enter a number: "))
if i_num < number:
raise ValueTooSmallError
elif i_num > number:
raise ValueTooLargeError
Enter a number: 3
break This value is too small, try again!
except ValueTooSmallError: Enter a number: 36
print("This value is too small, try again!") This value is too large, try again!

print() Enter a number: 10


Congratulations! You guessed it correctly.
except ValueTooLargeError:
print("This value is too large, try again!")
print()
print("Congratulations! You guessed it correctly.")

PYTHON AJITH KUMAR J(BANGALORE)


154
PYTHON

In the above example,we have defined a base class called Error.


The other two exceptions (ValueTooSmallError and ValueTooLargeError) that are actually
raised by our program are derived from this class.

Example:
class UnderAge(Exception):
pass

def verify_age(age):
if int(age) < 18:
raise UnderAge
else:
print('As your Age is: '+str(age) + '\nYou are eligible for voting')

# main program
verify_age(23) # won't raise exception
verify_age(17) # will raise exception

As your Age is: 23


You are eligible for voting
Traceback (most recent call last):
File "C:\Users/Programs\Python\Python37-32\Python Files\[Link]", line 12, in <module> verify_age(17)
File "C:\Users \Programs\Python\Python37-32\Python Files\[Link]", line 6, in verify_age
raise UnderAge
UnderAge

PYTHON AJITH KUMAR J(BANGALORE)


155
PYTHON

Python3 – Database Interaction

SQLite database connection using python


SQLite is a software library that implements a self-contained, serverless, zero-configuration,
transactional SQL database engine.
SQLite is a lightweight database that can provide a relational database management system
with zero-configuration because there is no need to configure or setup anything to use it.
To use SQLite3 in Python, first, we will have to import the sqlite3 module and then create a
connection object which will connect us to the database and will let us execute the SQL
statements.
A connection object is created using the connect() function:

import sqlite3
con = [Link]('[Link]')

SQLite3 Cursor
To execute SQLite statements in Python, you need a cursor object. You can create it using
the cursor() method.
The SQLite3 cursor is a method of the connection object. To execute the SQLite3 statements,
a connection is established at first and then an object of the cursor is created using the
connection object as follows:
con = [Link]('[Link]')
cursorObj = [Link]()
Now we can use the cursor object to call the execute() method to execute any SQL queries.

Create Database
When you create a connection with SQLite, a database file is automatically created if it
doesn’t already exist. This database file is created on disk, we can also create a temporary DB
in the RAM by using :memory: with the connect function. This database is called in-memory
database.

# Create a database in RAM


con = [Link](':memory:')
# Creates or opens a file called mydb with a SQLite3 DB
con = [Link]('data/mydb')

PYTHON AJITH KUMAR J(BANGALORE)


156
PYTHON

When we are done working with the DB we need to close the connection:
[Link]()

Create Table
To create a table in SQLite3, you can use the Create Table query in the execute() method.
Consider the following steps:
1. The connection object is created
2. Cursor object is created using the connection object
3. Using cursor object, execute method is called with create table query as the parameter
Let’s create employees with the following attributes:
employees (id, name, salary, department, position, hireDate)

import sqlite3

from sqlite3 import Error

def sql_connection():

try:

con = [Link]('[Link]')

return con

except Error:

print(Error)

def sql_table(con):

cursorObj = [Link]()

[Link]("CREATE TABLE employees(id integer PRIMARY KEY, name text,


salary real, department text, position text, hireDate text)")

[Link]()

con = sql_connection()

sql_table(con)

PYTHON AJITH KUMAR J(BANGALORE)


157
PYTHON

In the above code, we have defined two methods, the first one establishes a connection and
the second method creates a cursor object to execute the create table statement.
The commit() method saves all the changes we make. In the end, both methods are called.

Insert into Table


To insert data in a table, we use the INSERT INTO statement. Consider the following line of
code:
[Link]("INSERT INTO employees VALUES(1, 'John', 700, 'HR', 'Manager',
'2017-01-04')")
[Link]()

We can also pass values/arguments to an INSERT statement in the execute()method. You can
use the question mark (?) as a placeholder for each value. The syntax of the INSERT will be
like the following:
[Link]('''INSERT INTO employees(id, name, salary, department, position,
hireDate) VALUES(?, ?, ?, ?, ?, ?)''', entities)

Where entities contain the values for the placeholders as follows:


entities = (2, 'Andrew', 800, 'IT', 'Tech', '2018-02-06')

The entire code is as follows:


import sqlite3

con = [Link]('[Link]')

def sql_insert(con, entities):

cursorObj = [Link]()

[Link]('INSERT INTO employees(id, name, salary, department, position,


hireDate) VALUES(?, ?, ?, ?, ?, ?)', entities)

[Link]()

entities = (2, 'Andrew', 800, 'IT', 'Tech', '2018-02-06')

sql_insert(con, entities)

If multiple insertion is required then we must use executemany() method.

PYTHON AJITH KUMAR J(BANGALORE)


158
PYTHON

''' entities = [(1, 'Ajith', 80000, 'IT', 'Tech Lead', '2018-02-06'),


(2, 'Kumar', 49000, 'IT', 'Tech', '2019-02-06'),
(3, 'Raju', 30000, 'IT', 'Eng', '2018-05-06')]
[Link]('INSERT INTO employees(id, name, salary, department, position,
hireDate) VALUES(?, ?, ?, ?, ?, ?)', entities) '''

Update and Delete Table


To update and delete the table simply create a connection, then create a cursor object using
the connection and finally use the UPDATE statement in the execute() method.
Suppose that we want to update the name of the employee whose id equals 2. For updating,
we will use the UPDATE statement and for the employee whose id equals 2. We will use the
WHERE clause as a condition to select this employee.
Suppose that we want to delete the name of the employee whose id equals 3. For deleting, we
will use the DELETE statement and for the employee whose id equals 3. We will use the
WHERE clause as a condition to select this employee.

Consider the following code:


import sqlite3

con = [Link]('[Link]')

def sql_update(con):

cursorObj = [Link]()

# Update employee name whose id 2


[Link]('UPDATE employees SET name = "Rogers" where id = 2')
# Delete employee whose id 3
[Link]('DELETE from employees where id = 3')

[Link]()

sql_update(con)

Select statement
The select statement is used to select data from a specific table. If you want to select all the columns
of the data from a table, you can use the asterisk (*). The syntax for this will be as follows:

select * from table_name


In SQLite3, the SELECT statement is executed in the execute method of the cursor object.
For example, select all the columns of the employees’ table, run the following code:
PYTHON AJITH KUMAR J(BANGALORE)
159
PYTHON

[Link]('SELECT * FROM employees ')


If you want to select a few columns from a table then specify the columns like the following:
select column1, column2 from tables_name

For Example:
[Link]('SELECT id, name FROM employees')

Fetch all Data


To fetch the data from a database we will execute the SELECT statement and then will use
the fetchall() method of the cursor object to store the values into a variable. After that, we
will loop through the variable and print all values.

import sqlite3

con = [Link]('[Link]')

def sql_fetch(con):

cursorObj = [Link]()

[Link]('SELECT * FROM employees')

rows = [Link]()

for row in rows:

print(row)

sql_fetch(con)

Now, to fetch id and names of those who have a salary greater than 50000:

import sqlite3

con = [Link]('[Link]')

def sql_fetch(con):

cursorObj = [Link]()

[Link]('SELECT id, name FROM employees WHERE salary > 50000.0')

PYTHON AJITH KUMAR J(BANGALORE)


160
PYTHON

rows = [Link]()

for row in rows:

print(row)

sql_fetch(con)

Commit and Rollback


Transactions are useful property of database systems. It ensures the atomicity of the
Database. Use commit to save the changes:
Or rollback to roll back any change to the database since the last call to commit:

import sqlite3

con = [Link]('[Link]')

def sql_update(con):

cursorObj = [Link]()

# Update employee name whose id 2


[Link]('UPDATE employees SET name = "Rogers" where id = 2')
# Delete employee whose id 3
[Link]('DELETE from employees where id = 3')

# [Link]()
# [Link]()

sql_update(con)

PYTHON AJITH KUMAR J(BANGALORE)


161
PYTHON

GUI Programming

Python provides various options for developing graphical user interfaces (GUIs). The most
important features are listed below.
 Tkinter: Tkinter is the Python interface to the Tk GUI toolkit shipped with Python.
 wxPython: This is an open-source Python interface for wxWidgets GUI toolkit.
 PyQt:This is also a Python interface for a popular cross-platform Qt GUI library.
 JPython: JPython is a Python port for Java, which gives Python scripts seamless
access to the Java class libraries on the local machine[Link]

Tkinter Programming
Tkinter is the standard GUI library for Python. Python when combined with Tkinter provides
a fast and easy way to create GUI applications. Tkinter provides a powerful object-oriented
interface to the Tk GUI toolkit.
Creating a GUI application using Tkinter is an easy task. All you need to do is perform the
following steps −
 Import the Tkinter module.
 Create the GUI application main window.
 Add one or more of the above-mentioned widgets to the GUI application.
 Enter the main event loop to take action against each event triggered by the user.

Example:
import tkinter
top = [Link]()
# Code to add widgets will go here...
[Link]()

PYTHON AJITH KUMAR J(BANGALORE)


162
PYTHON

Tkinter Widgets

Tkinter provides various controls, such as buttons, labels and text boxes used in a GUI
application.
There are currently 15 types of widgets in Tkinter. The most important and widely used
widgets will be discussed in the coming topics.

Tkinter Button
The Button widget is used to add buttons in a Python application. These buttons can display
text or images that convey the purpose of the buttons. You can attach a function or a method
to a button which is called automatically when you click the button.
Syntax:
w = Button ( master, option=value, ... )

Parameters:
 master: This represents the parent window.
 options: Number of options can be passed as parameters separated by commas. Some
of them are listed below.
 activebackground: to set the background color when button is under the cursor.
 activeforeground: to set the foreground color when button is under the cursor.
 bg: to set he normal background color.
 command: to call a function.
 font: to set the font on the button label.
 image: to set the image on the button.
 width: to set the width of the button.
 height: to set the height of the button.

Example:

PYTHON AJITH KUMAR J(BANGALORE)


163
PYTHON

from tkinter import *


from tkinter import messagebox
top = Tk()
[Link]("100x100")
def helloCallBack():
msg=[Link]( "Hello Python", "Hello World")
B = Button(top, text ="Hello", command = helloCallBack)
[Link](x=50,y=50)
[Link]()

Tkinter Canvas:
The Canvas is a rectangular area intended for drawing pictures or other complex layouts. You
can place graphics, text, widgets or frames on a Canvas.
Syntax:
w = Canvas ( master, option=value, ... )

Parameters:
 master: This represents the parent window
 options: There are number of options which are used to change the format of the
widget. Number of options can be passed as parameters separated by commas. Some
of them are listed below.

PYTHON AJITH KUMAR J(BANGALORE)


164
PYTHON

 bd: to set the border width in pixels.


 bg: to set the normal background color.
 cursor: to set the cursor used in the canvas.
 highlightcolor: to set the color shown in the focus highlight.
 width: to set the width of the widget.
 height: to set the height of the widget.

Example:
from tkinter import *
from tkinter import messagebox
top = Tk()
C = Canvas(top, bg="blue", height=250, width=300)
coord = 10, 50, 240, 210
arc = C.create_arc(coord, start=0, extent=150, fill="red")
line = C.create_line(10,10,200,200,fill='white')
[Link]()
[Link]()

PYTHON AJITH KUMAR J(BANGALORE)


165
PYTHON

Tkinter Checkbuttton
The Checkbutton widget is used to display several options to a user as toggle buttons. The
user can then select one or more options by clicking the button corresponding to each option.
You can also display images in place of text.
Syntax:
w = Checkbutton ( master, option, ... )
Parameters:
 master: This represents the parent window.
 options: There are number of options which are used to change the format of this
widget. Number of options can be passed as parameters separated by commas. Some
of them are listed below.
 Title: To set the title of the widget.
 activebackground: to set the background color when widget is under the cursor.
 activeforeground: to set the foreground color when widget is under the cursor.
 bg: The normal background color displayed behind the label and indicator
 command: to call a function.
 font: to set the font on the button label.
 image: to set the image on the widget.

Example:

from tkinter import *


import tkinter
top = Tk()
CheckVar1 = IntVar()
CheckVar2 = IntVar()
C1 = Checkbutton(top, text = "Music", variable = CheckVar1, \
onvalue = 1, offvalue = 0, height=5, width = 20, )
C2 = Checkbutton(top, text = "Video", variable = CheckVar2, \
onvalue = 0, offvalue = 1, height=5, width = 20)
[Link]()
[Link]()
[Link]()

PYTHON AJITH KUMAR J(BANGALORE)


166
PYTHON

Tkinter Entry

The Entry widget is used to accept single-line text strings from a user.
 If you want to display multiple lines of text that can be edited, then you should use the
Text widget.
 If you want to display one or more lines of text that cannot be modified by the user,
then you should use the Label widget.

Syntax:
w = Entry( master, option, ... )
Parameters:
 master: This represents the parent window.
 options: Number of options can be passed as parameters separated by commas. Some
of them are listed below.
 bd: to set the border width in pixels.
 bg: to set the normal background color.
 cursor: to set the cursor used.
 command: to call a function.
 highlightcolor: to set the color shown in the focus highlight.
 width: to set the width of the button.
 height: to set the height of the button.

Example:
from tkinter import *
top = Tk()
L1 = Label(top, text="User Name")
[Link]( side = LEFT)
E1 = Entry(top, bd =5)
[Link](side = RIGHT)
[Link]()

PYTHON AJITH KUMAR J(BANGALORE)


167
PYTHON

Tkinter Frame
The Frame widget is very important for the process of grouping and organizing other widgets
in a somehow friendly way. It works like a container, which is responsible for arranging the
position of other widgets.

Syntax:
w = Frame ( master, option, ... )
Parameters:
 master: This represents the parent window.
 options: Number of options can be passed as parameters separated by commas. Some
of them are listed below.

 highlightcolor: To set the color of the focus highlight when widget must be focused.
 bd: to set the border width in pixels.
 bg: to set the normal background color.
 cursor: to set the cursor used.
 width: to set the width of the widget.
 height: to set the height of the widget.

Example:
from tkinter import *
root = Tk()
frame = Frame(root)
[Link]()
bottomframe = Frame(root)
[Link]( side = BOTTOM )
redbutton = Button(frame, text="Red", fg="red")
[Link]( side = LEFT)
greenbutton = Button(frame, text="Brown", fg="brown")
[Link]( side = LEFT )
bluebutton = Button(frame, text="Blue", fg="blue")
[Link]( side = LEFT )
blackbutton = Button(bottomframe, text="Black", fg="black")
[Link]( side = BOTTOM)
[Link]()

PYTHON AJITH KUMAR J(BANGALORE)


168
PYTHON

Tkinter Label
This widget implements a display box where you can place text or images. The text displayed
by this widget can be updated at any time you want.
Syntax:
w = Label ( master, option, ... )
Parameters:
 master: This represents the parent window.
 options: Number of options can be passed as parameters separated by commas. Some
of them are listed below.

 bg: to set he normal background color.


 bg to set he normal background color.
 command: to call a function.
 font: to set the font on the button label.
 image: to set the image on the button.
 width: to set the width of the button.
 height: to set the height of the button.

Example:
from tkinter import *
root = Tk()
var = StringVar()
label = Label( root, textvariable=var, relief=RAISED )
[Link]("Hey!? How are you doing?")
[Link]()
[Link]()

PYTHON AJITH KUMAR J(BANGALORE)


169
PYTHON

Tkinter Listbox
The Listbox widget is used to display a list of items from which a user can select a number of
items
Syntax:
w = Listbox ( master, option, ... )
Parameters:
 master: This represents the parent window.
 options: Number of options can be passed as parameters separated by commas. Some
of them are listed below.
 highlightcolor: To set the color of the focus highlight when widget has to be focused.
 bg: to set he normal background color.
 bd: to set the border width in pixels.
 font: to set the font on the button label.
 image: to set the image on the widget.
 width: to set the width of the widget.
 height: to set the height of the widget.

Example:
from tkinter import *
import tkinter
top = Tk()
Lb1 = Listbox(top)
[Link](1, "Python")
[Link](2, "Java")
[Link](3, "C")
[Link](4, "PHP")
[Link](5, "JSP")
[Link](6, "Ruby")
[Link]()
[Link]()

PYTHON AJITH KUMAR J(BANGALORE)


170
PYTHON

Tkinter Menubutton
A menubutton is the part of a drop-down menu that stays on the screen all the time. Every
menubutton is associated with a Menu widget that can display the choices for that
menubutton when the user clicks on it.
Syntax:
w = Menubutton ( master, option, ... )
Parameters:
 master: This represents the parent window.
 options: Number of options can be passed as parameters separated by commas. Some
of them are listed below.
 activebackground: To set the background when mouse is over the widget.
 activeforeground: To set the foreground when mouse is over the widget.
 bg: to set he normal background color.
 bd: to set the size of border around the indicator.
 cursor: To appear the cursor when the mouse over the menubutton.
 image: to set the image on the widget.
 width: to set the width of the widget.
 height: to set the height of the widget.
 highlightcolor: To set the color of the focus highlight when widget has to be focused.

Example:
from tkinter import *
import tkinter
top = Tk()
mb= Menubutton ( top, text="Juice", relief=RAISED )
[Link]()
[Link] = Menu ( mb, tearoff = 0 )
mb["menu"] = [Link]

pineVar = IntVar()
oraVar = IntVar()
mangoVar = IntVar()

PYTHON AJITH KUMAR J(BANGALORE)


171
PYTHON

[Link].add_checkbutton ( label="PineApple",
variable=pineVar )
[Link].add_checkbutton ( label="Orange",
variable=oraVar )
[Link].add_checkbutton ( label="Mango",
variable=mangoVar )
[Link]()
[Link]()

Tkinter Menu
The goal of this widget is to allow us to create all kinds of menus that can be used by our
applications. The core functionality provides ways to create three menu types: pop-up,
toplevel and pull-down.
Syntax:
w = Menu ( master, option, ... )
Parameters:
 master: This represents the parent window.
 options: Number of options can be passed as parameters separated by commas. Some
of them are listed below.

 title: To set the title of the widget.


 activebackground: to set the background color when widget is under the cursor.
 activeforeground: to set the foreground color when widget is under the cursor.
 bg: to set he normal background color.
 command: to call a function.
 font: to set the font on the button label.
 image: to set the image on the widget.

PYTHON AJITH KUMAR J(BANGALORE)


172
PYTHON

Example
from tkinter import *
def donothing():
filewin = Toplevel(root)
button = Button(filewin, text="Do nothing button")
[Link]()

root = Tk()
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="New", command=donothing)
filemenu.add_command(label="Open", command=donothing)
filemenu.add_command(label="Save", command=donothing)
filemenu.add_command(label="Save as...", command=donothing)
filemenu.add_command(label="Close", command=donothing)

filemenu.add_separator()

filemenu.add_command(label="Exit", command=[Link])
menubar.add_cascade(label="File", menu=filemenu)
editmenu = Menu(menubar, tearoff=0)
editmenu.add_command(label="Undo", command=donothing)

editmenu.add_separator()

editmenu.add_command(label="Cut", command=donothing)
editmenu.add_command(label="Copy", command=donothing)
editmenu.add_command(label="Paste", command=donothing)
editmenu.add_command(label="Delete", command=donothing)
editmenu.add_command(label="Select All", command=donothing)

PYTHON AJITH KUMAR J(BANGALORE)


173
PYTHON

menubar.add_cascade(label="Edit", menu=editmenu)
helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_command(label="Help Index", command=donothing)
helpmenu.add_command(label="About...", command=donothing)
menubar.add_cascade(label="Help", menu=helpmenu)
[Link](menu=menubar)
[Link]()

PYTHON AJITH KUMAR J(BANGALORE)


174
PYTHON

Tkinter Message
This widget provides a multiline and noneditable object that displays texts, automatically
breaking lines and justifying their contents. Its functionality is very similar to the one
provided by the Label widget, except that it can also automatically wrap the text, maintaining
a given width or aspect ratio.

Syntax:
w = Message ( master, option, ... )
Parameters:
 master: This represents the parent window.
 options: Number of options can be passed as parameters separated by commas. Some
of them are listed below.
 bd: to set the border around the indicator.
 bg: to set he normal background color.
 font: to set the font on the button label.
 image: to set the image on the widget.
 width: to set the width of the widget.
 height: to set the height of the widget.

Example
from tkinter import *
root = Tk()
var = StringVar()
label = Message( root, textvariable=var, relief=RAISED )
[Link]("Hey!? How are you doing?")
[Link](bg='yellow')
[Link]()
[Link]()

PYTHON AJITH KUMAR J(BANGALORE)


175
PYTHON

Tkinter Radiobutton
This widget implements a multiple-choice button, which is a way to offer many possible
selections to the user and lets user choose only one of them.

Syntax:
w = Radiobutton ( master, option, ... )
Parameters:
 master: This represents the parent window.
 options: Number of options can be passed as parameters separated by commas. Some
of them are listed below.
 activebackground: to set the background color when widget is under the cursor.
 activeforeground: to set the foreground color when widget is under the cursor.
 bg: to set he normal background color.
 command: to call a function.
 font: to set the font on the button label.
 image: to set the image on the widget.
 width: to set the width of the label in characters.
 height: to set the height of the label in characters.

Example
from tkinter import *
def sel():
selection = "You selected the option " + str([Link]())
[Link](text = selection)
root = Tk()
var = IntVar()
R1 = Radiobutton(root, text="Option 1", variable=var, value=1,
command=sel)
[Link]( anchor = W )
R2 = Radiobutton(root, text="Option 2", variable=var, value=2,
command=sel)
[Link]( anchor = W )

PYTHON AJITH KUMAR J(BANGALORE)


176
PYTHON

R3 = Radiobutton(root, text="Option 3", variable=var, value=3,


command=sel)
[Link]( anchor = W)
label = Label(root)
[Link]()
[Link]()

Tkinter Scrollbar
This widget provides a slide controller that is used to implement vertical scrolled widgets,
such as Listbox, Text and Canvas.

Syntax:
w = Scrollbar ( master, option, ... )
Parameters:
 master: This represents the parent window.
 options: Number of options can be passed as parameters separated by commas. Some
of them are listed below.
 width: to set the width of the widget.
 activebackground: To set the background when mouse is over the widget.
 bg: to set he normal background color.
 bd: to set the size of border around the indicator.
 cursor: To appear the cursor when the mouse over the menubutton.

Example:

from tkinter import *

root = Tk()

scrollbar = Scrollbar(root)

[Link]( side = RIGHT, fill=Y )

mylist = Listbox(root, yscrollcommand = [Link] )

for line in range(100):

PYTHON AJITH KUMAR J(BANGALORE)


177
PYTHON

[Link](END, "This is line number " + str(line))

[Link]( side = LEFT, fill = BOTH )

[Link]( command = [Link] )

mainloop()

Tkinter Text
Text widgets provide advanced capabilities that allow you to edit a multiline text and format
the way it has to be displayed, such as changing its color and font.
Syntax:
w = Text ( master, option, ... )
Parameters:
 master: This represents the parent window.
 options: Number of options can be passed as parameters separated by commas. Some
of them are listed below.

 highlightcolor: To set the color of the focus highlight when widget has to be focused.
 insertbackground: To set the background of the widget.
 bg: to set he normal background color.
 font: to set the font on the button label.
 image: to set the image on the widget.
 width: to set the width of the widget.
 height: to set the height of the widget.

PYTHON AJITH KUMAR J(BANGALORE)


178
PYTHON

Example:
from tkinter import *
root = Tk()
text = Text(root)
[Link](INSERT, "Hello.....")
[Link](END, "Bye Bye.....")
[Link]()
text.tag_add("here", "1.0", "1.4")
text.tag_add("start", "1.8", "1.13")
text.tag_config("here", background="yellow", foreground="orange")
text.tag_config("start", background="black", foreground="green")
[Link]()

PYTHON AJITH KUMAR J(BANGALORE)


179
PYTHON

Tkinter LabelFrame

A labelframe is a simple container widget. Its primary purpose is to act as a spacer or


container for complex window layouts.

Syntax:
w = LabelFrame ( master, option, ... )
Parameters:
 master: This represents the parent window.
 options: Number of options can be passed as parameters separated by commas. Some
of them are listed below.
 bg: The normal background color displayed behind the label and indicator.
 bd: The size of the border around the indicator. Default is 2 pixels.
 cursor: If you set this option to a cursor name (arrow, dot etc.), the mouse cursor will
change to that pattern when it is over the checkbutton.
 font: The vertical dimension of the new frame.
 height: The vertical dimension of the new frame.

Example:
from tkinter import *
root = Tk()
labelframe = LabelFrame(root, text="This is a LabelFrame")
[Link](fill="both", expand="yes")
left = Label(labelframe, text="Inside the LabelFrame")
[Link]()
[Link]()

PYTHON AJITH KUMAR J(BANGALORE)


180
PYTHON

Tkinter tkMessageBox
The tkMessageBox module is used to display message boxes in your applications. This
module provides several functions that you can use to display an appropriate message.
Syntax:
[Link](title, message [, options])
Parameters:
 FunctionName: This is the name of the appropriate message box function.
 title: This is the text to be displayed in the title bar of a message box.
 message: This is the text to be displayed as a message.
 options: options are alternative choices that you may use to tailor a standard message
box. Some of the options that you can use are default and parent. The default option is
used to specify the default button, such as ABORT, RETRY, or IGNORE in the
message box. You could use one of the following functions with dialogue box-
 showinfo()
 showwarning()
 showerror ()
 askquestion()
 askokcancel()
 askyesno ()
 askretrycancel ()

Example:
from tkinter import *
from tkinter import messagebox
top = Tk()
[Link]("100x100")
def hello():
[Link]("Say Hello", "Hello
World")
B1 = Button(top, text = "Say Hello", command = hello)
[Link](x=35,y=50)
[Link]()

PYTHON AJITH KUMAR J(BANGALORE)


181
PYTHON

Tkinter Colors
Tkinter represents colors with strings. There are 2 ways to specify colors in Tkinter-
 You can use a string specifying the proportion of red, green and blue in hexadecimal
digits. For example, "#fff" is white, "#000000" is black, "#000fff000" is pure green,
and "#00ffff" is pure cyan (green plus blue).
 You can also use any locally defined standard color name. The colors "white",
"black", "red", "green", "blue", "cyan", "yellow", and "magenta" will always be
available.

Color options:
The common color options are-
 activebackground: Background color for the widget when the widget is active.
 activeforeground: Foreground color for the widget when the widget is active.
 background: Background color for the widget. This can also be represented as bg.
 disabledforeground: Foreground color for the widget when the widget is disabled.
 foreground: Foreground color for the widget. This can also be represented as fg.
 highlightbackground: Background color of the highlight region when the widget has
focus.
 highlightcolor: Foreground color of the highlight region when the widget has focus.
 selectbackground: Background color for the selected items of the widget.
 selectforeground: Foreground color for the selected items of the widget.

Tkinter Fonts
There may be up to three ways to specify type style.
1. Simple Tuple Fonts
As a tuple whose first element is the font family, followed by a size in points,
optionally followed by a string containing one or more of the style modifiers bold,
italic, underline and overstrike.
Example:
 ("Helvetica", "16") for a 16-point Helvetica regular.
 ("Times", "24", "bold italic") for a 24-point Times bold italic.

PYTHON AJITH KUMAR J(BANGALORE)


182
PYTHON

2. Font object Fonts


You can create a "font object" by importing the tkFont module and using its Font
class constructor −
Example:
import tkFont
font = [Link] ( option, ... )

Here is the list of options-


 family: The font family name as a string.
 size: The font height as an integer in points. To get a font n pixels high, use -n.
 weight: "bold" for boldface, "normal" for regular weight.
 slant: "italic" for italic, "roman" for unslanted.
 underline: 1 for underlined text, 0 for normal.
 overstrike: 1 for overstruck text, 0 for normal.

Example:

helv36 = [Link](family="Helvetica",size=36,weight="bold")

3. X Window Fonts
If you are running under the X Window System, you can use any of the X font names.
For example, the font named "-*-lucidatypewriter-medium-r-*-*-*-140-*-*-*-*-*-*"
is the author's favorite fixed-width font for onscreen use.

PYTHON AJITH KUMAR J(BANGALORE)


183
PYTHON

Color Game – Project

Scenario:
In this game player must enter color of the word that appears on the screen and hence the
score increases by one, the total time to play this game is 30 seconds. Colors used in this
game are Red, Blue, Green, Pink, Black, Yellow, Orange, White, Purple and Brown.
Interface will display name of different colors in different colors. Player must identify the
color and enter the correct color name to win the game.

Code:
# import the modules
import tkinter
import random

# list of possible colour.


colours = ['Red','Blue','Green','Pink','Black',
'Yellow','Orange','White','Purple','Brown']
score = 0

# the game time left, initially 30 seconds.


timeleft = 30

# function that will start the game.


def startGame(event):

if timeleft == 30:

# start the countdown timer.


countdown()

# run the function to


# choose the next colour.

PYTHON AJITH KUMAR J(BANGALORE)


184
PYTHON

nextColour()

# Function to choose and


# display the next colour.
def nextColour():

# use the globally declared 'score'


# and 'play' variables above.
global score
global timeleft

# if a game is currently in play


if timeleft > 0:

# make the text entry box active.


e.focus_set()

# if the colour typed is equal


# to the colour of the text
if [Link]().lower() == colours[1].lower():

score += 1

# clear the text entry box.


[Link](0, [Link])

[Link](colours)

# change the colour to type, by changing the


# text _and_ the colour to a random colour value

PYTHON AJITH KUMAR J(BANGALORE)


185
PYTHON

[Link](fg = str(colours[1]), text = str(colours[0]))

# update the score.


[Link](text = "Score: " + str(score))

# Countdown timer function


def countdown():

global timeleft

# if a game is in play
if timeleft > 0:

# decrement the timer.


timeleft -= 1

# update the time left label


[Link](text = "Time left: "
+ str(timeleft))

# run the function again after 1 second.


[Link](1000, countdown)

# Driver Code

# create a GUI window


root = [Link]()

PYTHON AJITH KUMAR J(BANGALORE)


186
PYTHON

# set the title


[Link]("COLORGAME")

# set the size


[Link]("375x200")

# add an instructions label


instructions = [Link](root, text = "Type in the colour"
"of the words, and not the word text!",
font = ('Helvetica', 12))
[Link]()

# add a score label


scoreLabel = [Link](root, text = "Press enter to start",
font = ('Helvetica', 12))
[Link]()

# add a time left label


timeLabel = [Link](root, text = "Time left: " +
str(timeleft), font = ('Helvetica', 12))

[Link]()

# add a label for displaying the colours


label = [Link](root, font = ('Helvetica', 60))
[Link]()

# add a text entry box for


# typing in colours
e = [Link](root)

PYTHON AJITH KUMAR J(BANGALORE)


187
PYTHON

# run the 'startGame' function


# when the enter key is pressed
[Link]('<Return>', startGame)
[Link]()

# set focus on the entry box


e.focus_set()

# start the GUI


[Link]()

OUTPUT:

PYTHON AJITH KUMAR J(BANGALORE)


188
PYTHON

Catching the Ball Game

Scenario:
There is one bar at the bottom of game window which can be moved left or right using the
buttons that are in the game window. Red ball will continuously fall from top to bottom and
can start from any random x-axis distance. The task is to bring that bar to a suitable location
by moving left or right so that the red ball will fall on that bar(catch the ball onto the bar) not
on the ground. If player catches the ball onto the bar then score will get increase and that ball
will disappear and again a new red ball will start falling from top to bottom starting from
random x-axis distance. If player miss the ball from catching it on the bar then you will lose
the game and then finally scorecard will appear on the game window.

Approach:
1. Use Tkinter package in python for building GUI(Graphical user interface).
2. Use Canvas for drawing objects in Python – Canvas is a rectangular area intended for
drawing pictures or other complex layouts. We can place graphics, text, widgets or
frames on Canvas.
3. Syntax: w = Canvas ( master, option=value, ... )
Parameters:
 master - This represents the parent window.
 options - List of most commonly used options for this widget.
These options can be used as key-value pairs separated by commas.
Example- width, height etc.
4. Use canvas.create_oval for creating the ball.
create_oval creates a circle or an ellipse at the given coordinates. It takes two pairs of
coordinates; the top left and bottom right corners of the bounding rectangle for the
oval.
Syntax: oval = canvas.create_oval(x0, y0, x1, y1, options)
5. Use canvas.create_rectangle for creating the bar.
create_rectangle creates a rectangle at the given coordinates. It takes two pairs of
coordinates; the top left and bottom right coordinates.
Syntax: oval = canvas.create_rectangle(x0, y0, x1, y1, options)
6. Use [Link] for moving the ball or bar.
[Link] enables the object to move with the specified (x, y) coordinates.
Syntax: move=[Link](name of object, x, y)

PYTHON AJITH KUMAR J(BANGALORE)


189
PYTHON

Note: *Take x=0 for moving the ball in vertical direction only and take y=0 for moving the
bar in horizontal direction only. *Dissapear the ball when it touches the ground or the bar
using [Link](object).
7. Use Button for moving the bar in forward or backward and then apply action event on
it.

Code:

# Python code for catching the ball game

# importing suitable packages


from tkinter import Tk,Button,Label
from tkinter import Canvas
from random import randint

# defining Tk from Tkinter


root = Tk()
[Link]("Catch the ball Game")
[Link](False,False)

# for defining the canvas


canvas = Canvas(root, width=600, height=600)
[Link]()

# variable for the vertical distance


# travelled by ball
limit = 0

# variable for horizontal distance


# of bar from x-axis
dist = 5

PYTHON AJITH KUMAR J(BANGALORE)


190
PYTHON

# variable for score


score = 0

# Class for the Creating and moving ball


class Ball:

# for creation of ball on the canvas


def __init__(self, canvas, x1, y1, x2, y2):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
[Link] = canvas

# for creation of ball object


[Link] = canvas.create_oval(self.x1, self.y1, self.x2, self.y2,
fill = "red",tags = 'dot1')

# for moving the ball


def move_ball(self):

# defining offset
offset = 10
global limit

# checking if ball lands ground or bar


if limit >= 510:
global dist,score,next

# checking that ball falls on the bar

PYTHON AJITH KUMAR J(BANGALORE)


191
PYTHON

if(dist - offset <= self.x1 and


dist + 40 + offset >= self.x2):

# incrementing the score


score += 10

# dissappear the ball


[Link]('dot1')

# calling the function for again


# creation of ball object
ball_set()

else:
# dissappear the ball
[Link]('dot1')
bar.delete_bar(self)

# display the score


score_board()
return

# incrementing the vertical distance


# travelled by ball by deltay
limit += 1

# moving the ball in vertical direction


# by taking x=0 and y=deltay
[Link]([Link],0,1)

PYTHON AJITH KUMAR J(BANGALORE)


192
PYTHON

# for continuous moving of ball again call move_ball


[Link](10,self.move_ball)

# class for creating and moving bar


class bar:

# method for creating bar


def __init__(self,canvas,x1,y1,x2,y2):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
[Link] = canvas

# for creating bar using create_rectangle


[Link]=canvas.create_rectangle(self.x1, self.y1, self.x2, self.y2,

fill="yellow",tags='dot2')

# method for moving the bar


def move_bar(self,num):
global dist

# checking the forward or backward button


if(num == 1):

# moving the bar in forward direction by


# taking x-axis positive distance and
# taking vertical distance y=0
[Link]([Link],20,0)

PYTHON AJITH KUMAR J(BANGALORE)


193
PYTHON

# incrementing the distance of bar from x-axis


dist += 20
else:

# moving the bar in backward direction by taking x-axis


# negative distance and taking vertical distance y=0
[Link]([Link],-20,0)

# decrementing the distance of bar from x-axis


dist-=20

def delete_bar(self):
[Link]('dot2')

# Function to define the dimensions of the ball


def ball_set():
global limit
limit=0

# for random x-axis distance from


# where the ball starts to fall
value = randint(0,570)

# define the dimensions of the ball


ball1 = Ball(canvas,value,20,value+30,50)

# call function for moving of the ball


ball1.move_ball()

PYTHON AJITH KUMAR J(BANGALORE)


194
PYTHON

# Function for displaying the score


# after getting over of the game
def score_board():
root2 = Tk()
[Link]("Catch the ball Game")
[Link](False,False)
canvas2 = Canvas(root2,width=300,height=300)
[Link]()

w = Label(canvas2,text="\nOOPS...GAME IS OVER\n\nYOUR SCORE = "


+
str(score) + "\n\n")
[Link]()

button3 = Button(canvas2, text="PLAY AGAIN", bg="green",


command=lambda:play_again(root2))
[Link]()

button4 = Button(canvas2,text="EXIT",bg="green",
command=lambda:exit_handler(root2))
[Link]()

# Function for handling the play again request


def play_again(root2):
[Link]()
main()

# Function for handling exit request


def exit_handler(root2):
[Link]()
[Link]()
PYTHON AJITH KUMAR J(BANGALORE)
195
PYTHON

# Main function
def main():
global score,dist
score = 0
dist = 0

# defining the dimensions of bar


bar1=bar(canvas,5,560,45,575)

# defining the text,colour of buttons and


# also define the action after click on
# the button by calling suitable methods
button = Button(canvas,text="==>", bg="green",
command=lambda:bar1.move_bar(1))

# placing the buttons at suitable location on the canvas


[Link](x=300,y=580)

button2 = Button(canvas,text="<==",bg="green",
command=lambda:bar1.move_bar(0))
[Link](x=260,y=580)

# calling the function for defining


# the dimensions of ball
ball_set()
[Link]()

# Driver code
if(__name__=="__main__"):
main()

PYTHON AJITH KUMAR J(BANGALORE)


196
PYTHON

OUTPUT:

PYTHON AJITH KUMAR J(BANGALORE)


197
PYTHON

PYTHON AJITH KUMAR J(BANGALORE)

You might also like