0% found this document useful (0 votes)
2 views163 pages

Python

This document provides an introduction to Python, detailing its history, features, and applications. It covers the installation process, basic syntax, and programming conventions, emphasizing Python's versatility as a general-purpose language. Additionally, it highlights Python's dynamic typing and the importance of indentation in code structure.

Uploaded by

being.human.2680
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)
2 views163 pages

Python

This document provides an introduction to Python, detailing its history, features, and applications. It covers the installation process, basic syntax, and programming conventions, emphasizing Python's versatility as a general-purpose language. Additionally, it highlights Python's dynamic typing and the importance of indentation in code structure.

Uploaded by

being.human.2680
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
You are on page 1/ 163

Chapter 1

Getting started with Python


Python is a general purpose, dynamic, high level and interpreted programming language. It
supports Object Oriented programming approach to develop applications. It is simple and easy to
learn and provides lots of high-level data structures. Python is easy to learn yet powerful and
versatile scripting language which makes it attractive for Application Development. Python's
syntax and dynamic typing with its interpreted nature, makes it an ideal language for scripting
and rapid application development.

Python supports multiple programming pattern, including object oriented, imperative and
functional or procedural programming styles. Python is not intended to work on special area
such as web programming. That is why it is known as multipurpose because it can be used with
web, enterprise, 3D CAD etc. Python makes the development and debugging fast because there
is no compilation step included in python development and edit-test-debug cycle is very fast.

Python programming language was developed by Guido Van Rossum in 1991

Python History

 Python laid its foundation in the late 1980s.


 The implementation of Python was started in the December 1989 by Guido Van Rossum
at CWI in Netherland.
 In February 1991, van Rossum published the code (labeled version 0.9.0) to alt.sources.
 In 1994, Python 1.0 was released with new features like: lambda, map, filter, and reduce.
 Python 2.0 added new features like: list comprehensions, garbage collection system.
 On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to
rectify fundamental flaw of the language.
 ABC programming language is said to be the predecessor of Python language which was
capable of Exception Handling and interfacing with Amoeba Operating System.
 Python is influenced by following programming languages:
o ABC language.
o Modula-3

Python Features
Python provides lots of features that are listed below.
1) Easy to Learn and Use : Python is easy to learn and use. It is developer-friendly and high
level programming language.
2) Expressive Language : Python language is more expressive means that it is more
understandable and readable.
3) Interpreted Language : Python is an interpreted language i.e. interpreter executes the code
line by line at a time. This makes debugging easy and thus suitable for beginners.
4) Cross-platform Language : Python can run equally on different platforms such as Windows,
Linux, Unix and Macintosh etc. So, we can say that Python is a portable language.
5) Free and Open Source :Python language is freely available at offical web address. The source-
code is also available. Therefore it is open source.
6) Object-Oriented Language :Python supports object oriented language and concepts of classes
and objects come into existence.
7) Extensible : It implies that other languages such as C/C++ can be used to compile the code
and thus it can be used further in our python code.
8) Large Standard Library : Python has a large and broad library and prvides rich set of module
and functions for rapid application development.
9) GUI Programming Support : Graphical user interfaces can be developed using Python.
10) Integrated : It can be easily integrated with languages like C, C++, JAVA etc.

Python Applications
Python is known for its general purpose nature that makes it applicable in almost each domain of
software development. Python as a whole can be used in any sphere of development. Here, we
are specifing applications areas where python can be applied.
1) Web Applications : We can use Python to develop web applications. It provides libraries to
handle internet protocols such as HTML and XML, JSON, Email processing, request,
beautifulSoup, Feedparser etc. It also provides Frameworks such as Django, Pyramid, Flask etc
to design and delelop web based applications. Some important developments are:
PythonWikiEngines, Pocoo, PythonBlogSoftware etc.
2) Desktop GUI Applications : Python provides Tk GUI library to develop user interface in
python based application. Some other useful toolkits wxWidgets, Kivy, pyqt that are useable on
several platforms. The Kivy is popular for writing multitouch applications.
3) Software Development : Python is helpful for software development process. It works as a
support language and can be used for build control and management, testing etc.
4) Scientific and Numeric : Python is popular and widely used in scientific and numeric
computing. Some useful library and package are SciPy, Pandas, IPython etc. SciPy is group of
packages of engineering, science and mathematics.
5) Business Applications : Python is used to build Bussiness applications like ERP and e-
commerce systems. Tryton is a high level application platform.
6) Console Based Application : We can use Python to develop console based applications. For
example: IPython.
7) Audio or Video based Applications : Python is awesome to perform multiple tasks and can be
used to develop multimedia applications. Some of real applications are: TimPlayer, cplay etc.
8) 3D CAD Applications : To create CAD application Fandango is a real application which
provides full features of CAD.
9) Enterprise Applications : Python can be used to create applications which can be used within
an Enterprise or an Organization. Some real time applications are: OpenErp, Tryton, Picalo etc.
10) Applications for Images : Using Python several application can be developed for image.
Applications developed are: VPython, Gogh, imgSeek etc.
There are several such applications which can be developed using Python

Python Version List

Python programming language is being updated regularly with new features and supports. There
are lots of updations in python versions, started from 1994 to current release.
A list of python versions with its released date is given below.
Python Version Released Date

Python 1.0 January 1994

Python 1.5 December 31, 1997

Python 1.6 September 5, 2000

Python 2.0 October 16, 2000

Python 2.1 April 17, 2001

Python 2.2 December 21, 2001

Python 2.3 July 29, 2003

Python 2.4 November 30, 2004

Python 2.5 September 19, 2006

Python 2.6 October 1, 2008

Python 2.7 July 3, 2010

Python 3.0 December 3, 2008

Python 3.1 June 27, 2009

Python 3.2 February 20, 2011

Python 3.3 September 29, 2012

Ving some ver March 16, 2014

Python 3.5 September 13, 2015

Python 3.6 December 23, 2016

Python 3.7 June 27, 2018


Python Keywords/ Reserved Words

Python Keywords are special reserved words which convey a special meaning to the
compiler/interpreter. Each keyword have a special meaning and a specific operation. These
keywords can't be used as variable. Following is the List of Python Keywords.

True False None and as

Asset def class continue break

Else finally elif del except

global for if from import

Raise try or return pass

nonlocal in not is lambda

Installing Python
Visit the link https://www.python.org/downloads/ to download the latest release of Python. In
this process, we will install Python 3.6.7 on our Windows operating system.
Double-click the executable file which is downloaded; the following window will open. Select
Customize installation and proceed.
The following window shows all the optional features. All the features need to be installed and
are checked by default; we need to click next to continue.
The following window shows a list of advanced options. Check all the options which you want
to install and click next. Here, we must notice that the first check-box (install for all users) must
be checked.
Now, we are ready to install python-3.6.7. Let's install it.
Now, try to run python on the command prompt. Type the command python in case of python2
or python3 in case of python3. It will show an error as given in the below image. It is because
we haven't set the path.
Environment Variables
To set the path of python, we need to the right click on "my computer" and go to Properties →
Advanced → Environment Variables.
Add the new path variable in the user variable section.
Type PATH as the variable name and set the path to the installation directory of the python
shown in the below image.
Executing Python from the Command Line
Now, the path is set, we are ready to run python on our local system. Restart CMD, and
type python again. It will open the python interpreter shell where we can execute the python
statements. The following screen will appear
To come out from screen press Ctrl Z (^Z) at >>> prompt.

IDLE
Once you have Python installed on your computer, you are ready to work on it. Python works in
two ways
 Interactive mode
 Script mode

Interactive mode : means you type the command – one command at a time, python executes the
given command and give you the output. In interactive mode you type the command in front of
Python prompt >>>. For example if you type 10+20 in front of Python prompt it will give the
result 30. Search for IDLE in windows or in Run window type IDLE and the following screen
will appear

Type in front of Python Prompt and it will give the result


Script mode :

Click on Start button -> All Programs -> Python -> IDLE(Python GUI)

ii) Python Shell will be opened. Now click on File -> New Window.

A new Editor will be opened. Write our Python code here.


Click on file -> save as

Run code by clicking on Run in the Menu bar.


Run -> Run Module or press F5

Result will be displayed on a new Python shell as:

Editing Python Files


To edit saved Python file open the file by clicking on File Open or ^O (ctrl O) and then choosing
the file from the list of given files.
Python Documentation

Python documentation strings (or docstrings) provide a convenient way of associating


documentation with Python modules, functions, classes, and methods. It’s specified in source
code that is used, like a comment, to document a specific segment of code. Unlike conventional
source code comments, the docstring should describe what the function does, not how.

Dynamic Types

Python variable assignment is different from some of the popular languages like c, c++ and java.
There is no declaration of a variable, just an assignment statement.
When we declare a variable in C or alike languages, this sets aside an area of memory for
holding values allowed by the data type of the variable. The memory allocated will be interpreted
as the data type suggests. If it’s an integer variable the memory allocated will be read as an
integer and so on. When we assign or initialize it with some value, that value will get stored at
that memory location. At compile time, initial value or assigned value will be checked. So we
cannot mix types. Example: initializing a string value to an int variable is not allowed and the
program will not compile.
But Python is a dynamically typed language. It doesn’t know about the type of the variable until
the code is run. So declaration is of no use. What it does is, It stores that value at some memory
location and then binds that variable name to that memory container. And makes the contents of
the container accessible through that variable name. So the data type does not matter.

# This will store 6 in the memory and binds the


# name x to it. After it runs, type of x will
# be int.
x=6
print(type(x))
# This will store 'hello' at some location int
# the memory and binds name x to it. After it
# runs type of x will be str.
x = 'hello'
print(type(x))
output :
<class 'int'>
<class 'str'>

Naming Conventions
While working in python, one should keep in mind certain style rules and conversations. In the
following lines, we are giving some very elementary and basic style rules:

1. Statement Termination : Python does not use any symbol to terminate a statement. when
you end a physical code –line by pressing enter key, the statement is considered is
terminated by default.

2. Maximum Line Length : Line length should be maximum 79 characters


3. Lines and Indentation : Blocks of code are denoted by line indentation , which is
enforced through 4 spaces (not) per tabs ) indentation level.
4. Blank Lines : Use two blank lines between top level definitions ,one blank line between
method/function definitions. Functions and methods should be separated with two
blank lines and class definitions with three blank lines
5. Avoid multiple statement on one line : Although you can combine more than one
statement in one line using symbol semicolon (;) between two statements , but it is not
recommended.
6. Whitespace : You should always have whitespace around operators and after
punctuation but not with parentheses. Python considers these 6 characters as whitespace :
‘’ (space) , ‘\in’(newline), ‘\t’(horizontal tab), ‘\v’ (vertical tab), ‘\f’ (formfeed) and ‘\r’ (
carriage return )
7. Case Sensitive : Python is case sensitive, so case of statements is very important. be
careful while typing code and identifier-names.

Exercise :
Very Short Answer Questions

1 Who developed Python Programming Language ?

2 Is Python an Object Oriented language ?

3 In how many different ways, can you work in Python?

4 What is the extension of Python script File?

5 What is keyword?

Short Answer Questions

1 Write various versions of Python ?

2 What is IDLE?

3 Write Python naming conventions.

4 What is Dynamic Type in Python

5 What is Environment variable.


Long Answer Questions

1 What is Python Programming Language. Give its applications and features.

2 How you will install Python. Write its mode of working.


CHAPTER 2
Basic Python Syntax
Basic Syntax
Lines and Indentation
Python provides no braces to indicate blocks of code for class and function definitions or flow
control. Blocks of code are denoted by line indentation, which is highly enforced.The number of
spaces in the indentation is variable, but all statements within the block must be indented the
same amount. For example −

if True:
print "True"
else:
print "False"
However, the following block generates an error −

if True:
print "Answer"
print "True"
else:
print "Answer"
print "False"
Thus, in Python all the continuous lines indented with same number of spaces would form a
block. The following example has various statement blocks −
Multi-Line Statements
Statements in Python typically end with a new line. Python does, however, allow the use of the
line continuation character (\) to denote that the line should continue. For example −

total = item_one + \
item_two + \
item_three
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."""

Comments
Comments in Python can be used to explain any program code. It can also be used to hide the
code as well. Comments are the most helpful stuff of any program. It enables us to understand
the way, a program works. In python, any statement written along with # symbol is known as a
comment. The interpreter does not interpret the comment. Comment is not a part of the program,
but it enhances the interactivity of the program and makes the program readable.
Python supports two types of comments:
1) Single Line Comment:
In case user wants to specify a single line comment, then comment must start with ?#?
Eg:
# This is single line comment.
print ("Hello Python" )
Output:
Hello Python
2) Multi Line Comment:
Multi lined comment can be given inside triple quotes.
eg:
''''' This
Is
Multipline comment'''
eg:
#single line comment
print ("Hello Python")
'''''This is
multiline comment'''
Output:
Hello Python
String Values
In python, strings can be created by enclosing the character or the sequence of characters in the
quotes. Python allows us to use single quotes, double quotes, or triple quotes to create the string.
Consider the following example in python to create a string.
str = "Hi Welcone Python !"
if we check the type of the variable str using a python script
print(type(str)), then it will print string (str).
In python, strings are treated as the sequence of strings which means that python doesn't support
the character data type instead a single character written as 'p' is treated as the string of length 1.

Strings indexing and splitting


Like other languages, the indexing of the python strings starts from 0. For example, The string
"HELLO" is indexed as given in the below figure.
As shown in python, the slice operator [] is used to access the individual characters of the string.
However, we can use the : (colon) operator in python to access the substring. Consider the
following example.
String Methods
Python offers many built in methods for string manipulations. Following are string methods :
Function Name Description Example
capitalize() Returns the String with first character var = ‘PYTHON’
capitalized and rest of the characters in print (var.capitalize())
lower case. output : Python
lower() Converts all the characters of the String var = ‘India’
to lowercase. print (var.lower())
output : india
upper() Converts all the characters of the String var = ‘ambala’
to uppercase. print (var.upper())
output : AMBALA
title() Returns the ‘title cased’ version of var = ‘welcome to
String which means that all words start Python programming’
with uppercase and rest of the characters print (var.title())
in the words are in lowercase. output :Welcome To
Python Programming
count( str[,beg [,end]]) Returns the number of times substring var=’ambala’
‘str’ occurs in range [beg, end] if beg str=’a’
and end index are given. If it is not print (var.count(str))
given then substring is searched in output : 3
whole String.
Search is case-sensitive.
islower() Returns ‘True’ if all the characters in var=’Python’
the String are in lowercase. If any one print (var.islower())
character is in uppercase it will return output : False
‘False’. var=’python’
print (var.islower())
output : True
isupper() Returns ‘True’ if all the characters in var=’Python’
the String are in uppercase. If any one print (var.isupper())
character is in lowercase it will return output : False
‘False’. var=’PYTHON’
print (var.isupper())
output : True
replace(old,new[,count]) Replaces all the occurrences of var=’This is a good
substring ‘old’ with ‘new’ in the String. example’
If ‘count’ is defined then only ‘count’ str=’was’
number of occurrences of ‘old’ will be print
replaced with ‘new’. (var.replace(‘is’,str))
where, output : Thwas was a
old =substring to be replaced good exampleprint
new =substring that will replace the old (var.replace(‘is’,str,1))
count =number of occurrences of old output : Thwas is a good
that will be replaced with new. example

var=’This is a good
example’
Returns the length of given String print (len(var))
len(string) output : 22

The format Method


Python format() method is used to perform format operations on string. While formatting string
a delimiter {} (braces) is used to replace it with the value. This delimiter either can contain index
or positional argument.

Parameter Values

Parameter Description

format The format you want to format the value into.


Legal values:
'<' - Left aligns the result (within the available space)
'>' - Right aligns the result (within the available space)
'^' - Center aligns the result (within the available space)
'=' - Places the sign to the left most position
'+' - Use a sign to indicate if the result is positive or negative
'-' - Use a sign for negative values only
' ' - Use a leading space for positive numbers
',' - Use a comma as a thousand separator
'_' - Use a underscore as a thousand separator
'b' - Binary format
'c' - Converts the value into the corresponding unicode character
'd' - Decimal format
'e' - Scientific format, with a lower case e
'E' - Scientific format, with an upper case E
'f' - Fix point number format
'F' - Fix point number format, upper case
'g' - General format
'G' - General format (using a upper case E for scientific notations)
'o' - Octal format
'x' - Hex format, lower case
'X' - Hex format, upper case
'n' - Number format
'%' - Percentage format

Python String format() Method Example 1


An example of simple format method which format string using positional delimiter.
# Python format() function example
# Variable declaration
str = "C"
str2 = "C#"
# Calling function
str3 = "{} and {} both are programming languages".format(str,str2)
# Displaying result
print(str3)
Output:
C and C# both are programming languages
Python String format() Method Example 2
The delimiter (braces) are using numerical index to replace and format string.
# Python format() function example
# Variable declaration
str = "C"
str2 = "C#"
# Calling function
str3 = "{1} and {0} both are programming languages".format(str,str2)
# Displaying result
print(str3)
Output:
C# and C both are programming languages
Python String format() Method Example 3
Formatting numerical value in different-different number systems. See the below example.
# Python format() function example
# Variable declaration
val = 10
# Calling function
print("decimal: {0:d}".format(val)); # display decimal result
print("hex: {0:x}".format(val)); # display hexadecimal result
print("octal: {0:o}".format(val)); # display octal result
print("binary: {0:b}".format(val)); # display binary result
Output:
decimal: 10
hex: a
octal: 12
binary: 1010
Python String format() Method Example 4
Formating float and percentile in string is pretty easy.
# Python format() function example
# Variable declaration
val = 100000000
# Calling function
print("decimal: {:,}".format(val)); # formatting float value
print("decimal: {:.2%}".format(56/9)); # formatting percentile value
Output:
decimal: 100,000,000
decimal: 622.22%

String Operators
String operators can be used to manipulate the string in multiple ways. Following is the list of
String operators
Operator Description
+ It is known as concatenation operator used to join the strings given either side
of the operator.
* It is known as repetition operator. It concatenates the multiple copies of the
same string.
[] It is known as slice operator. It is used to access the sub-strings of a particular
string.
[:] It is known as range slice operator. It is used to access the characters from the
specified range.
in It is known as membership operator. It returns if a particular sub-string is
present in the specified string.
not in It is also a membership operator and does the exact reverse of in. It returns true
if a particular substring is not present in the specified string.
r/R It is used to specify the raw string. Raw strings are used in the cases where we
need to print the actual meaning of escape characters such as "C://python". To
define any string as a raw string, the character r or R is followed by the string.
% It is used to perform string formatting. It makes use of the format specifiers
used in C programming like %d or %f to map their values in python. We will
discuss how formatting is done in python.
Python String operator Example

Str=”Hello”
str1 = " world"
print(str*3) # prints HelloHelloHello
print(str+str1)# prints Hello world
print(str[4]) # prints o
print(str[2:4]); # prints ll
print('w' in str) # prints false as w is not present in str
print('wo' not in str1) # prints false as wo is present in str1.
print(r'C://python37') # prints C://python37 as it is written
print("The string str : %s"%(str)) # prints The string str : Hello

Output :
HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello
Numeric Data Types
Python numeric data type is used to hold numeric values like
 int (signed integers) − They are often called just integers or ints, are positive or negative
whole numbers with no decimal point.
 long (long integers ) − Also called longs, they are integers of unlimited size, written like
integers and followed by an uppercase or lowercase L.
 float (floating point real values) − Also called floats, they represent real numbers and
are written with a decimal point dividing the integer and fractional parts. Floats may also
be in scientific notation, with E or e indicating the power of 10 (2.5e2 = 2.5 x 10 2 =
250).

 complex (complex numbers) − are of the form a + bJ, where a and b are floats and J (or
j) represents the square root of -1 (which is an imaginary number). The real part of the
number is a, and the imaginary part is b. Complex numbers are not used much in Python
programming.

In Python we need not to declare datatype while declaring a variable like C or C++. We can
simply just assign values in a variable. But if we want to see what type of numerical value is it
holding right now, we can use type() function.

Here are some examples of numbers

int Long float complex

10 51924361L 0.0 3.14j

100 -0x19323L 15.20 45.j

-786 0122L -21.9 9.322e-36j

080 0xDEFABCECBDAECBFBAEL 32.3+e18 .876j

-0490 535633629843L -90. -.6545+0J

-0x260 -052318172735L -32.54e100 3e+26J

0x69 -4721885298529L 70.2-E12 4.53e-7j

Python allows you to use a lowercase L with long, but it is recommended that you use only an
uppercase L to avoid confusion with the number 1. Python displays long integers with an
uppercase L.

A complex number consists of an ordered pair of real floating point numbers denoted by a + bj,
where a is the real part and b is the imaginary part of the complex number.
Conversion Functions
Python internally changes the data type of some operands so that all operands have same data
type. This type of conversion is called automatic or implicit type conversion. Python also
supports explicit type conversion. It is also known as type casting. It is performed by <data
type>(expression).
Let's see an example where Python promotes conversion of lower datatype (integer) to higher
data type (float) to avoid data loss.
Data conversion integer to float Example 1

#Converting integer to float

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

Output :
datatype of num_int: <class 'int'>
datatype of num_flo: <class 'float'>

Value of num_new: 124.23


datatype of num_new: <class 'float'>

Data Conversion addition of string and integer using explicit conversion Example 2

#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))

Output :
Data type of num_int: <class 'int'>
Data type of num_str before Type Casting: <class 'str'>
Data type of num_str after Type Casting: <class 'int'>
Sum of num_int and num_str: 579
Data type of the sum: <class 'int'>

Simple Output
The simplest way to produce output is using the print() function where you can pass zero or more
expressions separated by commas. This function converts the expressions you pass into a string
before writing to the screen.
Example
print (“hello”) # string to be printed
print(17.5) # float to be printed
print(25) # int to be printed
print(“sum of 2 and 3 is”,2+3) # message and calculation to be printed

Simple Input
The input() method reads a line from input, converts into a string and returns it.
The syntax of input() method is:
input([prompt])
input() Parameters
The input() method takes a single optional argument:
prompt (Optional) - a string that is written to standard output (usually screen) without trailing
newline
Return value from input()
The input() method reads a line from input (usually user), converts the line into a string by
removing the trailing newline, and returns it. If EOF is read, it raises an EOFError exception.
Example 1: How input() works in Python?
# get input from user
inputString = input()
print('The inputted string is:', inputString)
When you run the program, the output will be:
Python is interesting.
The inputted string is: Python is interesting
Example 2: Get input from user with a prompt
# get input from user
inputString = input('Enter a string:')
print('The inputted string is:', inputString)
When you run the program, the output will be:
Enter a string: Python is interesting.
The inputted string is: Python is interesting
The % Method
Python uses C-style string formatting to create new, formatted strings. The "%" operator is used
to format a set of variables enclosed in a "tuple" (a fixed size list), together with a format string,
which contains normal text together with "argument specifiers", special symbols like "%s" and
"%d". For string %s and for integer %d is used.

Let's say you have a variable called "name" with your user name in it, and you would then like to
print(out a greeting to that user.)
# This prints out "Hello, Mohan!"
name = "Mohan"
print("Hello, %s!" % name)

Output :
Hello, Mohan
To use two or more argument specifiers, use a tuple (parentheses):
# This prints out "Mohan is 32 years old."
name = "Mohan"
age = 32
print("%s is %d years old." % (name, age))

Output:
Mohan is 32 years old.

Exercise :
Very Short Answer Questions

1. What is string ?
2. What is comment ?
3. What is conversion function ?
4. What is % method ?
5. What is input function ?

Short Answer Questions

1. Write string operators.


2. What is numeric data type ?
3. Explain input and print function.
4. Why conversion functions are required ?
5. How you can give comment in Python Program

Long Answer Questions

1. What s string ? How it is represented ? Give string functions with example.


2. What is number and give its types.
Chapter 3
Language Components

Indenting Requirements
Most of the programming languages like C, C++, Java use braces { } to define a block of code.
Python uses indentation. A code block (body of a function, loop etc.) starts with indentation and
ends with the first unindented line. The amount of indentation is up to you, but it must be
consistent throughout that block.
Generally four whitespaces are used for indentation and is preferred over tabs. Here is an
example.
for i in range(1,11):
print(i)
if i == 5:
break
The enforcement of indentation in Python makes the code look neat and clean. This results into
Python programs that look similar and consistent.
Indentation can be ignored in line continuation. But it's a good idea to always indent. It makes
the code more readable. For example:
if True:
print('Hello')
a=5
and

if True: print('Hello'); a = 5
both are valid and do the same thing. But the former style is clearer.
Incorrect indentation will result into IndentationError.
The if Statement
Decision making is the most important aspect of almost all the programming languages. As the
name implies, decision making allows us to run a particular block of code for a particular
decision. Here, the decisions are made on the validity of the particular conditions. Condition
checking is the backbone of decision making.
In python, decision making is performed by the following statements.
Statement Description
If Statement The if statement is used to test a specific condition. If the condition is
true, a block of code (if-block) will be executed.
If - else The if-else statement is similar to if statement except the fact that, it
Statement also provides the block of the code for the false case of the condition
to be checked. If the condition provided in the if statement is false,
then the else statement will be executed.
Nested if Nested if statements enable us to use if ? else statement inside an outer
Statement if statement.

The if statement
The if statement is used to test a particular condition and if the condition is true, it executes a
block of code known as if-block. The condition of if statement can be any valid logical
expression which can be either evaluated to true or false.
The syntax of the if-statement is given below.
1. if expression:
2. statement
Example 1 : Program to check even number
num = int(input("enter the number?"))
if num%2 == 0:
print("Number is even")
Output:
enter the number?10
Number is even
Example 2 : Program to print the largest of the three numbers.
a = int(input("Enter a? "));
b = int(input("Enter b? "));
c = int(input("Enter c? "));
if a>b and a>c:
print("a is largest");
if b>a and b>c:
print("b is largest");
if c>a and c>b:
print("c is largest");
Output:
Enter a? 100
Enter b? 120
Enter c? 130
c is largest

The if-else statement


The if-else statement provides an else block combined with the if statement which is executed in
the false case of the condition.
If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.
The syntax of the if-else statement is given below.
if condition:
#block of statements
else:
#another block of statements (else-block)
Example 1 : Program to check whether a person is eligible to vote or not.
age = int (input("Enter your age? "))
if age>=18:
print("You are eligible to vote !!");
else:
print("Sorry! you have to wait !!");

Output:
Enter your age? 20
You are eligible to vote !!

Enter your age? 12


Sorry! you have to wait !!
Example 2: Program to check whether a number is even or not.
num = int(input("enter the number?"))
if num%2 == 0:
print("Number is even...")
else:
print("Number is odd...")

Output:
enter the number?10
Number is even

enter the number?13


Number is odd

The elif statement


The elif statement enables us to check multiple conditions and execute the specific block of
statements depending upon the true condition among them. We can have any number of elif
statements in our program depending upon our need. However, using elif is optional.
The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if
statement.
The syntax of the elif statement is given below.
if expression 1:
# block of statements

elif expression 2:
# block of statements

elif expression 3:
# block of statements

else:
# block of statements
Example 1
number = int(input("Enter the number?"))
if number==10:
print("number is equals to 10")
elif number==50:
print("number is equal to 50");
elif number==100:
print("number is equal to 100");
else:
print("number is not equal to 10, 50 or 100");

Output:
Enter the number?15
number is not equal to 10, 50 or 100

Enter the number?50


number is equal to 50
Example 2
marks = int(input("Enter the marks? "))
if marks > 85 and marks <= 100:
print("Congrats ! you scored grade A ...")
elif marks > 60 and marks <= 85:
print("You scored grade B + ...")
elif marks > 40 and marks <= 60:
print("You scored grade B ...")
elif (marks > 30 and marks <= 40):
print("You scored grade C ...")
else:
print("Sorry you are fail ?")

Output:
Enter the marks ?95
Congrats ! you scored grade A ...

Enter the marks? 44


You scored grade B ...
Relational and Logical Operators
Operators are used to perform operations on variables and values.
Python divides the operators in the following groups:
 Arithmetic operators
 Assignment operators
 Comparison/Relational operators
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators
Relational/Comparison operator
Comparison operators are used to comparing the value of the two operands and returns boolean
true or false accordingly. The comparison operators are described in the following table.
Operator Description
== If the value of two operands is equal, then the condition becomes true.
!= If the value of two operands is not equal then the condition becomes true.
If the first operand is less than or equal to the second operand, then the condition
<=
becomes true.
If the first operand is greater than or equal to the second operand, then the condition
>=
becomes true.
<> If the value of two operands is not equal, then the condition becomes true.
If the first operand is greater than the second operand, then the condition becomes
>
true.

< If the first operand is less than the second operand, then the condition becomes true.

Example Relational Operator :


x=5
y=3
print(x == y)
# returns False because 5 is not equal to 3
print(x != y)
# returns True because 5 is not equal to 3
print(x > y)
# returns True because 5 is greater than 3
print(x < y)
# returns False because 5 is not less than 3

Output :
False
True
True
False
Logical Operator
The logical operators are used primarily in the expression evaluation to make a decision. Python
supports the following logical operators.

Operator Description

If both the expression are true, then the condition will be true. If a and b are the two
And
expressions, a → true, b → true => a and b → true.

If one of the expressions is true, then the condition will be true. If a and b are the two
Or
expressions, a → true, b → false => a or b → true.

Not If an expression a is true then not (a) will be false and vice versa.

Example Logical Operator:


x=5
print(x > 3 and x < 10)
# returns True because 5 is greater than 3 AND 5 is less than 10
print(x > 3 or x < 4)
# returns True because one of the conditions are true (5 is greater than 3, but 5 is not less than 4)
print(not(x > 3 and x < 10))
# returns False because not is used to reverse the result

Output :
True
True
False

Bit Wise Operators


The bitwise operators perform bit by bit operation on the values of the two operands.

Operator Description

& (binary If both the bits at the same place in two operands are 1, then 1 is copied to the
and) result. Otherwise, 0 is copied.

The resulting bit will be 0 if both the bits are zero otherwise the resulting bit will
| (binary or)
be 1.

^ (binary The resulting bit will be 1 if both the bits are different otherwise the resulting bit
xor) will be 0.

It calculates the negation of each bit of the operand, i.e., if the bit is 0, the resulting
~ (negation)
bit will be 1 and vice versa.

The left operand value is moved left by the number of bits present in the right
<< (left shift)
operand.

>> (right
The left operand is moved right by the number of bits present in the right operand.
shift)

Example Bitwise Operator :

a=7
b=9
print(a&b)
output :
1
The while Loop
The while loop is also known as a pre-tested loop. In general, a while loop allows a part of the
code to be executed as long as the given condition is true.
It can be viewed as a repeating if statement. The while loop is mostly used in the case where the
number of iterations is not known in advance.
The syntax is given below.
while expression:
statements
Here, the statements can be a single statement or the group of statements. The expression should
be any valid python expression resulting into true or false. The true is any non-zero value.
Example 1
i=1;
while i<=10:
print(i);
i=i+1;
Output:
1
2
3
4
5
6
7
8
9
10
Example 2
i=1
number=0
b=9
number = int(input("Enter the number?"))
while i<=10:
print("%d X %d = %d \n"%(number,i,number*i));
i = i+1;
Output:
Enter the number?10

10 X 1 = 10
10 X 2 = 20
10 X 3 = 30
10 X 4 = 40
10 X 5 = 50
10 X 6 = 60
10 X 7 = 70
10 X 8 = 80
10 X 9 = 90
10 X 10 = 100

Infinite while loop


If the condition given in the while loop never becomes false then the while loop will never
terminate and result into the infinite while loop.
Any non-zero value in the while loop indicates an always-true condition whereas 0 indicates the
always-false condition. This type of approach is useful if we want our program to run
continuously in the loop without any disturbance.
Example:
while (1):
print("Hi! we are inside the infinite while loop");
Output:
Hi! we are inside the infinite while loop
(infinite times)
Using else with Python while loop
Python enables us to use the while loop with the while loop also. The else block is executed
when the condition given in the while statement becomes false. Like for loop, if the while loop is
broken using break statement, then the else block will not be executed and the statement present
after else block will be executed.
Consider the following example.
i=1;
while i<=5:
print(i)
i=i+1;
else:print("The while loop exhausted");
Output:
1
2
3
4
5
The while loop exhausted
break and continue

break statement
The break is a keyword in python which is used to bring the program control out of the loop. The
break statement breaks the loops one by one, i.e., in the case of nested loops, it breaks the inner
loop first and then proceeds to outer loops. In other words, we can say that break is used to abort
the current execution of the program and the control goes to the next line after the loop.
The break is commonly used in the cases where we need to break the loop for a given condition.
The syntax of the break is given below.
#loop statements
break;
Example:
i = 0;
while 1:
print(i," ",end=""),
i=i+1;
if i == 10:
break;
print("came out of while loop");

Output:

0 1 2 3 4 5 6 7 8 9 came out of while loop

continue Statement
The continue statement in python is used to bring the program control to the beginning of the
loop. The continue statement skips the remaining lines of code inside the loop and start with the
next iteration. It is mainly used for a particular condition inside the loop so that we can skip
some specific code for a particular condition.
The syntax of Python continue statement is given below.
#loop statements
continue;
#the code to be skipped
Example :
i = 0;
while i!=10:
print("%d"%i);
continue;
i=i+1;
Output:
infinite loop

The for Loop


The for loop in Python is used to iterate the statements or a part of the program several times. It
is frequently used to traverse the data structures like list, tuple, or dictionary.
The syntax of for loop in python is given below.
for iterating_var in sequence:
statement(s)

Example :
i=1
n=int(input("Enter the number up to which you want to print the natural numbers?"))
for i in range(0,10):
print(i,end = ' ')
Output:
0123456789
Example : printing the table of the given number
i=1;
num = int(input("Enter a number:"));
for i in range(1,11):
print("%d X %d = %d"%(num,i,num*i));
Output:
Enter a number:10
10 X 1 = 10
10 X 2 = 20
10 X 3 = 30
10 X 4 = 40
10 X 5 = 50
10 X 6 = 60
10 X 7 = 70
10 X 8 = 80
10 X 9 = 90
10 X 10 = 100
Nested for loop in python
Python allows us to nest any number of for loops inside a for loop. The inner loop is executed n
number of times for every iteration of the outer loop. The syntax of the nested for loop in python
is given below.
for iterating_var1 in sequence:
for iterating_var2 in sequence:
#block of statements
#Other statements
Example :
n = int(input("Enter the number of rows you want to print?"))
i,j=0,0
for i in range(0,n):
print()
for j in range(0,i+1):
print("*",end="")
Output:
Enter the number of rows you want to print?5
*
**
***
****
*****
Using else statement with for loop
Unlike other languages like C, C++, or Java, python allows us to use the else statement with the
for loop which can be executed only when all the iterations are exhausted. Here, we must notice
that if the loop contains any of the break statement then the else statement will not be executed.
Example :
for i in range(0,5):
print(i)
else:print("for loop completely exhausted, since there is no break.");
In the above example, for loop is executed completely since there is no break statement in the
loop. The control comes out of the loop and hence the else block is executed.
Output:
0
1
2
3
4
for loop completely exhausted, since there is no break.
Exercise :
Very Short Answer Questions :

1. What is indentation ?
2. What is if statement ?
3. What is if else statement ?
4. Write the category of operator ?
5. What is looping ?
6. What is break statement ?
7. What is continue statement ?

Short Answer Questions :

1. Write if else statement.


2. Explain for loop.
3. Explain while loop.
4. Difference between while and continue.
5. Write different category of operators.

Long Answer Questions :

1. What are various decision making statement. Explain them with examples.
2. Write the category of operators with example.
3. Write program for calculating the factorial of a number.
4. Write program to find sum of first n natural numbers.
Chapter 4
List, Tuples ,Sets & Dictionaries
LIST
A list is a standard data type of Python to store sequence of values belong to any type. List in
python is implemented to store the sequence of various type of data. However, python contains
six data types that are capable to store the sequences but the most common and reliable type is
list. A list can be defined as a collection of values or items of different types. The items in the list
are separated with the comma (,) and enclosed with the square brackets []. Lists are mutable i.e.
modifiable. In other words the memory address of list will not change even after you change its
values.
A list can be defined as follows.
1. L1 = ["Ram", 102, "Ambala"]
2. L2 = [1, 2, 3, 4, 5, 6]
3. L3 = [1, "Harshit"]
4. L4=[]
If we try to print the type of L1, L2, L3 and L4 then it will come out to be a list.
Lets consider a proper example to define a list and printing its values.
emp = ["Ram", 102, "Ambala"]

Dep1 = ["CS",10];

Dep2 = ["IT",11];

HOD_CS = [100,"Mr. Harshit"]

HOD_IT = [101, "Mr. Been"]

print("printing employee data...");

print("Name : %s, ID: %d, City: %s"%(emp[0],emp[1],emp[2]))


print("printing departments...");

print("Department 1:\nName: %s, ID: %d\nDepartment 2:\nName: %s, ID:


%s"%(Dep1[0],Dep2[1],Dep2[0],Dep2[1]));

print("HOD Details ....");

print("CS HOD Name: %s, Id: %d"%(HOD_CS[1],HOD_CS[0]));

print("IT HOD Name: %s, Id: %d"%(HOD_IT[1],HOD_IT[0]));

print(type(emp),type(Dep1),type(Dep2),type(HOD_CS),type(HOD_IT));

Output:
printing employee data...
Name : Ram, ID: 102, City: Ambala
printing departments...
Department 1:
Name: CS, ID: 11
Department 2:
Name: IT, ID: 11
HOD Details ....
CS HOD Name: Mr. Harshit, Id: 100
IT HOD Name: Mr. Been, Id: 101
<class 'list'> <class 'list'> <class 'list'> <class 'list'> <class 'list'>
List indexing and splitting
The indexing are processed in the same way as it happens with the strings. The elements of the
list can be accessed by using the slice operator [].
The index starts from 0 and goes to length - 1. The first element of the list is stored at the 0th
index, the second element of the list is stored at the 1st index, and so on.
Consider the following example.
Unlike other languages, python provides us the flexibility to use the negative indexing also. The
negative indices are counted from the right. The last element (right most) of the list has the index
-1, its adjacent left element is present at the index -2 and so on until the left most element is
encountered.
Updating List values
Lists are the most versatile data structures in python since they are mutable and their values can
be updated by using the slice and assignment operator. Python also provide us the append()
method which can be used to add values to the string.
Consider the following example to update the values inside the list.
List = [1, 2, 3, 4, 5, 6]
print(List)
List[2] = 10;
print(List)
List[1:3] = [89, 78]
print(List)
Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
The list elements can also be deleted by using the del keyword. Python also provides us the
remove() method if we do not know which element is to be deleted from the list.
Consider the following example to delete the list elements.
List = [0,1,2,3,4]
print(List)
del List[0]
print(List)
del List[3]
print(List)
Output:
[0, 1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3]
Python List Operations
The concatenation (+) and repetition (*) operator work in the same way as they were working
with the strings.
Lets see how the list responds to various operators.

1. Consider a List l1 = [1, 2, 3, 4], and l2 = [5, 6, 7, 8]

Operator Description Example

The repetition operator enables the list elements to be L1*2 = [1, 2, 3, 4, 1,


Repetition
repeated multiple times. 2, 3, 4]

It concatenates the list mentioned on either side of the l1+l2 = [1, 2, 3, 4, 5,


Concatenation
operator. 6, 7, 8]

It returns true if a particular item exists in a particular list print(2 in l1) prints
Membership
otherwise false. True.

for i in l1:
print(i)
Output
Iteration The for loop is used to iterate over the list elements.
1
2
3
4
Length It is used to get the length of the list len(l1) = 4

Iterating a List
A list can be iterated by using a for - in loop. A simple list containing four strings can be iterated
as follows.
List = ["Ram", "Sham", "Mohan", "Sohan"]
for i in List: #i will iterate over the elements of the List and contains each element in each ite
ration.
print(i);
Output:
Ram
Sham
Mohan
Sohan
Adding elements to the list
Python provides append() function by using which we can add an element to the list. However,
the append() method can only add the value to the end of the list.
Consider the following example in which, we are taking the elements of the list from the user
and printing the list on the console.
l =[];
n = int(input("Enter the number of elements in the list")); #Number of elements will be enter
ed by the user
for i in range(0,n): # for loop to take the input
l.append(input("Enter the item?")); # The input is taken from the user and added to the list
as the item
print("printing the list items....");
for i in l: # traversal loop to print the list items
print(i, end = " ");
Output:
Enter the number of elements in the list 5
Enter the item?1
Enter the item?2
Enter the item?3
Enter the item?4
Enter the item?5
printing the list items....
1 2 3 4 5
Removing elements from the list
List = [0,1,2,3,4]
print("printing original list: ");
for i in List:
print(i,end=" ")
List.remove(0)
print("\nprinting the list after the removal of first element...")
for i in List:
print(i,end=" ")
Output:
printing original list:
01234
printing the list after the removal of first element...
1234
Python List Built-in functions
Python provides the following built-in functions which can be used with the lists.
SN Function Description

1 cmp(list1, list2) It compares the elements of both the lists.

2 len(list) It is used to calculate the length of the list.

3 max(list) It returns the maximum element of the list.

4 min(list) It returns the minimum element of the list.

5 list(seq) It converts any sequence to the list.

Python List built-in methods


SN Function Description

1 list.append(obj) The element represented by the object obj is added to the list.

2 list.clear() It removes all the elements from the list.

3 List.copy() It returns a shallow copy of the list.

4 list.count(obj) It returns the number of occurrences of the specified object in the list.
5 list.extend(seq) The sequence represented by the object seq is extended to the list.

6 list.index(obj) It returns the lowest index in the list that object appears.

7 list.insert(index, obj) The object is inserted into the list at the specified index.

8 list.pop(obj=list[-1]) It removes and returns the last object of the list.

9 list.remove(obj) It removes the specified object from the list.

10 list.reverse() It reverses the list.

11 list.sort([func]) It sorts the list by using the specified compare function if given.

Tuples
Python Tuple is used to store the sequence of immutable python objects. Tuple is similar to lists
since the value of the items stored in the list can be changed whereas the tuple is immutable and
the value of the items stored in the tuple can not be changed. A tuple can be written as the
collection of comma-separated values enclosed with the small brackets. A tuple can be defined
as follows.
1. T1 = (101, "Harry", 22)
2. T2 = ("Apple", "Banana", "Mango")
Example 1:
tuple1 = (10, 20, 30, 40, 50, 60)
print(tuple1)
count = 0
for i in tuple1:
print("tuple1[%d] = %d"%(count, i));
count=count+1
Output:
(10, 20, 30, 40, 50, 60)
tuple1[0] = 10
tuple1[1] = 20
tuple1[2] = 30
tuple1[3] = 40
tuple1[4] = 50
tuple1[5] = 60

Example 2:
tuple1 = tuple(input("Enter the tuple elements ..."))
print(tuple1)
count = 0
for i in tuple1:
print("tuple1[%d] = %s"%(count, i));
Output:
Enter the tuple elements ...12345
('1', '2', '3', '4', '5')
tuple1[0] = 1
tuple1[1] = 2
tuple1[2] = 3
tuple1[3] = 4
tuple1[4] = 5
However, if we try to reassign the items of a tuple, we would get an error as the tuple object
doesn't support the item assignment.
An empty tuple can be written as follows.
T3 = ()
The tuple having a single value must include a comma as given below.
T4 = (90,)
A tuple is indexed in the same way as the lists. The items in the tuple can be accessed by using
their specific index value.
Tuple indexing and splitting
The indexing and slicing in tuple are similar to lists. The indexing in the tuple starts from 0 and
goes to length(tuple) - 1.
The items in the tuple can be accessed by using the slice operator. Python also allows us to use
the colon operator to access multiple items in the tuple.
Consider the following image to understand the indexing and slicing in detail.

Unlike lists, the tuple items can not be deleted by using the del keyword as tuples are immutable.
To delete an entire tuple, we can use the del keyword with the tuple name.
Consider the following example.
tuple1 = (1, 2, 3, 4, 5, 6)
print(tuple1)
del tuple1[0]
print(tuple1)
del tuple1
print(tuple1)
Output:
(1, 2, 3, 4, 5, 6)
Traceback (most recent call last):
File "tuple.py", line 4, in <module>
print(tuple1)
NameError: name 'tuple1' is not defined
Like lists, the tuple elements can be accessed in both the directions. The right most element (last)
of the tuple can be accessed by using the index -1. The elements from left to right are traversed
using the negative indexing.
Consider the following example.
tuple1 = (1, 2, 3, 4, 5)
print(tuple1[-1])
print(tuple1[-4])
Output:
5
2
Basic Tuple operations
The operators like concatenation (+), repetition (*), Membership (in) works in the same way as
they work with the list. Consider the following table for more detail.
Let's say Tuple t = (1, 2, 3, 4, 5) and Tuple t1 = (6, 7, 8, 9) are declared.
Operator Description Example
The repetition operator enables the tuple elements to be T1*2 = (1, 2, 3, 4, 5, 1,
Repetition
repeated multiple times. 2, 3, 4, 5)
It concatenates the tuple mentioned on either side of the T1+T2 = (1, 2, 3, 4, 5, 6,
Concatenation
operator. 7, 8, 9)
It returns true if a particular item exists in the tuple print (2 in T1) prints
Membership
otherwise false. True.
for i in T1:
print(i)
Output
Iteration The for loop is used to iterate over the tuple elements.
1
2
3
4
5
Length It is used to get the length of the tuple. len(T1) = 5
Python Tuple inbuilt functions
SN Function Description
cmp(tuple1, It compares two tuples and returns true if tuple1 is greater than tuple2
1
tuple2) otherwise false.
2 len(tuple) It calculates the length of the tuple.
3 max(tuple) It returns the maximum element of the tuple.
4 min(tuple) It returns the minimum element of the tuple.
5 tuple(seq) It converts the specified sequence to the tuple.
List VS Tuple
SN List Tuple
1 The literal syntax of list is shown by the []. The literal syntax of the tuple is shown by the ().
2 The List is mutable. The tuple is immutable.
3 The List has the variable length. The tuple has the fixed length.
The list provides more functionality than
4 The tuple provides less functionality than the list.
tuple.
The list Is used in the scenario in which we The tuple is used in the cases where we need to
need to store the simple collections with store the read-only collections i.e., the value of
5
no constraints where the value of the items the items can not be changed. It can be used as
can be changed. the key inside the dictionary.

Sets
The set in python can be defined as the unordered collection of various items enclosed within the
curly braces. The elements of the set can not be duplicate. The elements of the python set must
be immutable. Unlike other collections in python, there is no index attached to the elements of
the set, i.e., we cannot directly access any element of the set by the index. However, we can print
them all together or we can get the list of elements by looping through the set.
Creating a set
The set can be created by enclosing the comma separated items with the curly braces. Python
also provides the set method which can be used to create the set by the passed sequence.
Example 1: using curly braces
Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunda
y"}
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)
Output:
{'Friday', 'Tuesday', 'Monday', 'Saturday', 'Thursday', 'Sunday', 'Wednesday'}
<class 'set'>
looping through the set elements ...
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday
Example 2: using set() method
Days = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Su
nday"])
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)
Output:
{'Friday', 'Wednesday', 'Thursday', 'Saturday', 'Monday', 'Tuesday', 'Sunday'}
<class 'set'>
looping through the set elements ...
Friday
Wednesday
Thursday
Saturday
Monday
Tuesday
Sunday
Python Set operations
In the previous example, we have discussed about how the set is created in python. However, we
can perform various mathematical operations on python sets like union, intersection, difference,
etc.
Adding items to the set
Python provides the add() method which can be used to add some particular item to the set.
Consider the following example.
Example:
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nAdding other months to the set...");
Months.add("July");
Months.add("August");
print("\nPrinting the modified set...");
print(Months)
print("\nlooping through the set elements ... ")
for i in Months:
print(i)
Output:
printing the original set ...
{'February', 'May', 'April', 'March', 'June', 'January'}
Adding other months to the set...
Printing the modified set...
{'February', 'July', 'May', 'April', 'March', 'August', 'June', 'January'}
looping through the set elements ...
February
July
May
April
March
August
June
January

Update method
To add more than one item in the set, Python provides the update() method.
Consider the following example.
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nupdating the original set ... ")
Months.update(["July","August","September","October"]);
print("\nprinting the modified set ... ")
print(Months);
Output:
printing the original set ...
{'January', 'February', 'April', 'May', 'June', 'March'}
updating the original set ...
printing the modified set ...
{'January', 'February', 'April', 'August', 'October', 'May', 'June', 'July', 'September', 'March'}
Removing items from the set
Python provides discard() method which can be used to remove the items from the set.
Consider the following example.
Example
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nRemoving some months from the set...");
Months.discard("January");
Months.discard("May");
print("\nPrinting the modified set...");
print(Months)
print("\nlooping through the set elements ... ")
for i in Months:
print(i)
Output:
printing the original set ...
{'February', 'January', 'March', 'April', 'June', 'May'}
Removing some months from the set...
Printing the modified set...
{'February', 'March', 'April', 'June'}
looping through the set elements ...
February
March
April
June

Remove method
Python also provide the remove() method to remove the items from the set. Consider the
following example to remove the items using remove() method.
Example
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nRemoving some months from the set...");
Months.remove("January");
Months.remove("May");
print("\nPrinting the modified set...");
print(Months)
Output:
printing the original set ...
{'February', 'June', 'April', 'May', 'January', 'March'}
Removing some months from the set...
Printing the modified set...
{'February', 'June', 'April', 'March'}

Pop method
We can also use the pop() method to remove the item. However, this method will always remove
the last item. Consider the following example to remove the last item from the set.
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nRemoving some months from the set...");
Months.pop();
Months.pop();
print("\nPrinting the modified set...");
print(Months)
Output:
printing the original set ...
{'June', 'January', 'May', 'April', 'February', 'March'}
Removing some months from the set...
Printing the modified set...
{'May', 'April', 'February', 'March'}

Clear method
Python provides the clear() method to remove all the items from the set.
Consider the following example.
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nRemoving all the items from the set...");
Months.clear()
print("\nPrinting the modified set...")
print(Months)
Output:
printing the original set ...
{'January', 'May', 'June', 'April', 'March', 'February'}
Removing all the items from the set...
Printing the modified set...

Union of two Sets


The union of two sets are calculated by using the or (|) operator. The union of the two sets
contains the all the items that are present in both the sets.
Consider the following example to calculate the union of two sets.
Example 1 : using union | operator
Days1 = {"Monday","Tuesday","Wednesday","Thursday"}
Days2 = {"Friday","Saturday","Sunday"}
print(Days1|Days2) #printing the union of the sets
Output:
{'Friday', 'Sunday', 'Saturday', 'Tuesday', 'Wednesday', 'Monday', 'Thursday'}
Union method
Python also provides the union() method which can also be used to calculate the union of two
sets. Consider the following example.
Example 2: using union() method
Days1 = {"Monday","Tuesday","Wednesday","Thursday"}
Days2 = {"Friday","Saturday","Sunday"}
print(Days1.union(Days2)) #printing the union of the sets
Output:
{'Friday', 'Monday', 'Tuesday', 'Thursday', 'Wednesday', 'Sunday', 'Saturday'}
Intersection of two sets
The & (intersection) operator is used to calculate the intersection of the two sets in python. The
intersection of the two sets are given as the set of the elements that common in both sets.
Consider the following example.
Example 1: using & operator
set1 = {"Ayush","John", "David", "Martin"}
set2 = {"Steve","Milan","David", "Martin"}
print(set1&set2) #prints the intersection of the two sets
Output:
{'Martin', 'David'}
Example 2: using intersection() method
set1 = {"Ayush","John", "David", "Martin"}
set2 = {"Steave","Milan","David", "Martin"}
print(set1.intersection(set2)) #prints the intersection of the two sets
Output:
{'Martin', 'David'}

The intersection_update() method


The intersection_update() method removes the items from the original set that are not present in
both the sets (all the sets if more than one are specified).
The Intersection_update() method is different from intersection() method since it modifies the
original set by removing the unwanted items, on the other hand, intersection() method returns a
new set.
Consider the following example.
a = {"ayush", "bob", "castle"}
b = {"castle", "dude", "emyway"}
c = {"fuson", "gaurav", "castle"}
a.intersection_update(b, c)
print(a)
Output:
{'castle'}
Difference of two sets
The difference of two sets can be calculated by using the subtraction (-) operator. The resulting
set will be obtained by removing all the elements from set 1 that are present in set 2.
Consider the following example.
Example 1 : using subtraction ( - ) operator
Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday", "Tuesday", "Sunday"}
print(Days1-Days2) #{"Wednesday", "Thursday" will be printed}
Output:
{'Thursday', 'Wednesday'}
Example 2 : using difference() method
Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday", "Tuesday", "Sunday"}
print(Days1.difference(Days2)) # prints the difference of the two sets Days1 and Days2
Output:
{'Thursday', 'Wednesday'}
Set comparisons
Python allows us to use the comparison operators i.e., <, >, <=, >= , == with the sets by using
which we can check whether a set is subset, superset, or equivalent to other set. The boolean true
or false is returned depending upon the items present inside the sets.
Consider the following example.
Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday", "Tuesday"}
Days3 = {"Monday", "Tuesday", "Friday"}
#Days1 is the superset of Days2 hence it will print true.
print (Days1>Days2)
#prints false since Days1 is not the subset of Days2
print (Days1<Days2)
#prints false since Days2 and Days3 are not equivalent
print (Days2 == Days3)
Output:
True
False
False
Python Built-in set methods
Python contains the following methods to be used with the sets.
SN Method Description
1 add(item) It adds an item to the set. It has no effect if the
item is already present in the set.
2 clear() It deletes all the items from the set.
3 copy() It returns a shallow copy of the set.
4 difference_update(....) It modifies this set by removing all the items
that are also present in the specified sets.
5 discard(item) It removes the specified item from the set.
6 intersection() It returns a new set that contains only the
common elements of both the sets. (all the sets
if more than two are specified).
7 intersection_update(....) It removes the items from the original set that
are not present in both the sets (all the sets if
more than one are specified).
8 Isdisjoint(....) Return True if two sets have a null
intersection.
9 Issubset(....) Report whether another set contains this set.
10 Issuperset(....) Report whether this set contains another set.
11 pop() Remove and return an arbitrary set element
that is the last element of the set. Raises
KeyError if the set is empty.
12 remove(item) Remove an element from a set; it must be a
member. If the element is not a member, raise
a KeyError.
13 symmetric_difference(....) Remove an element from a set; it must be a
member. If the element is not a member, raise
a KeyError.
14 symmetric_difference_update(....) Update a set with the symmetric difference of
itself and another.
15 union(....) Return the union of sets as a new set.
(i.e. all elements that are in either set.)
16 update() Update a set with the union of itself and
others.

Dictionaries

Dictionary is used to implement the key-value pair in python. The dictionary is the data type in
python which can simulate the real-life data arrangement where some specific value exists for
some particular key. In other words, we can say that a dictionary is the collection of key-value
pairs where the value can be any python object whereas the keys are the immutable python
object, i.e., Numbers, string or tuple.
Creating the dictionary
The dictionary can be created by using multiple key-value pairs enclosed with the small brackets
() and separated by the colon (:). The collections of the key-value pairs are enclosed within the
curly braces {}.
The syntax to define the dictionary is given below.
Dict = {"Name": "Ayush","Age": 22}
In the above dictionary Dict, The keys Name, and Age are the string that is an immutable object.
Let's see an example to create a dictionary and printing its content.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
Output
<class 'dict'>
printing Employee data ....
{'Age': 29, 'salary': 25000, 'Name': 'John', 'Company': 'GOOGLE'}
Accessing the dictionary values
We have discussed how the data can be accessed in the list and tuple by using the indexing.
However, the values can be accessed in the dictionary by using the keys as keys are unique in the
dictionary.
The dictionary values can be accessed in the following way.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
print(type(Employee))
print("printing Employee data .... ")
print("Name : %s" %Employee["Name"])
print("Age : %d" %Employee["Age"])
print("Salary : %d" %Employee["salary"])
print("Company : %s" %Employee["Company"])
Output:
<class 'dict'>
printing Employee data ....
Name : John
Age : 29
Salary : 25000
Company : GOOGLE
Python provides us with an alternative to use the get() method to access the dictionary values. It
would give the same result as given by the indexing.
Updating dictionary values
The dictionary is a mutable data type, and its values can be updated by using the specific keys.
Let's see an example to update the dictionary values.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
print("Enter the details of the new employee....");
Employee["Name"] = input("Name: ");
Employee["Age"] = int(input("Age: "));
Employee["salary"] = int(input("Salary: "));
Employee["Company"] = input("Company:");
print("printing the new data");
print(Employee)
Output:
<class 'dict'>
printing Employee data ....
{'Name': 'John', 'salary': 25000, 'Company': 'GOOGLE', 'Age': 29}
Enter the details of the new employee....
Name: David
Age: 19
Salary: 8900
Company:JTP
printing the new data
{'Name': 'David', 'salary': 8900, 'Company': 'JTP', 'Age': 19}

Deleting elements using del keyword


The items of the dictionary can be deleted by using the del keyword as given below.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
print("Deleting some of the employee data")
del Employee["Name"]
del Employee["Company"]
print("printing the modified information ")
print(Employee)
print("Deleting the dictionary: Employee");
del Employee
print("Lets try to print it again ");
print(Employee)
Output:
<class 'dict'>
printing Employee data ....
{'Age': 29, 'Company': 'GOOGLE', 'Name': 'John', 'salary': 25000}
Deleting some of the employee data
printing the modified information
{'Age': 29, 'salary': 25000}
Deleting the dictionary: Employee
Lets try to print it again
Traceback (most recent call last):
File "list.py", line 13, in <module>
print(Employee)
NameError: name 'Employee' is not defined

Iterating Dictionary
A dictionary can be iterated using the for loop as given below.
Example 1
# for loop to print all the keys of a dictionary
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
for x in Employee:
print(x);
Output:
Name
Company
salary
Age

Example 2
#for loop to print all the values of the dictionary
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
for x in Employee:
print(Employee[x]);
Output:
29
GOOGLE
John
25000
Sorting Dictionaries
color_dict = {'Name':'Ram',
'Pay':'8000',
'Dept':'Sale',
'Gender':'Male'}

for key in sorted(color_dict):


print("%s: %s" % (key, color_dict[key]))

Dept: Sale
Gender: Male
Name: Ram
Pay: 8000
Copying Collections
Exercise :
Very Short Answer type questions :

1. Explain tuple.
2. What is list ?
3. What is set ?
4. What is dictionary?
5. What is union?
6. What is intersection?
7. What is push operation?
8. What is pop operation?

Short Answer type question


1. Explain tuple and its functions.
2. Explain sets and various operations on it.
3. Explain dictionary and how it is created.
4. Explain list and its various operation.
5. Difference between list and tuple.

Long Answer type question


1. What is list ? How it is accessed and updated in Python ?
2. What is tuple ? What are its basic operations and functions?
3. What is set and explain its built in methods.
4. What is dictionary and how its values are updated.
Chapter 5
Functions
Introduction
Functions are the most important aspect of an application. A function can be defined as the
organized block of reusable code which can be called whenever required. Python allows us to
divide a large program into the basic building blocks known as function. The function contains
the set of programming statements followed by function name. A function can be called multiple
times to provide reusability and modularity to the python program. In other words, we can say
that the collection of functions creates a program. The function is also known as procedure or
subroutine in other programming languages. Python provide us various inbuilt functions like
range() or print(). Although, the user can create its functions which can be called user-defined
functions.
Advantage of functions in python
There are the following advantages of functions.
o By using functions, we can avoid rewriting same logic/code again and again in a
program.
o We can call python functions any number of times in a program and from any place in a
program.
o We can track a large python program easily when it is divided into multiple functions.
o Reusability is the main achievement of python functions.
o However, Function calling is always overhead in a python program.
Creating a function
In python, we can use def keyword to define the function. The syntax to define a function in
python is given below.
def my_function():
function-suite
return <expression>
The function block is started with the colon (:) and all the same level block statements remain at
the same indentation. A function can accept any number of parameters that must be the same in
the definition and function calling.

Function calling
In python, a function must be defined before the function calling otherwise the python interpreter
gives an error. Once the function is defined, we can call it from another function or the python
prompt. To call the function, use the function name followed by the parentheses.
A simple function that prints the message "Hello Word" is given below.
def hello_world():
print("hello world")
hello_world()
Output:
hello world
Parameters in function
The information into the functions can be passed as the parameters. The parameters are specified
in the parentheses. We can give any number of parameters, but we have to separate them with a
comma. Consider the following example which contains a function that accepts a string as the
parameter and prints it.

Example 1
#defining the function
def func (name):
print("Hi ",name);
#calling the function
func("Ashu")

Output :
Hi Ashu

Example 2
#python function to calculate the sum of two variables
#defining the function
def sum (a,b):
return a+b;
#taking values from the user
a = int(input("Enter a: "))
b = int(input("Enter b: "))
#printing the sum of a and b
print("Sum = ",sum(a,b))
Output:
Enter a: 10
Enter b: 20
Sum = 30
Call by reference in Python/Passing Collections to Functions
In python, all the functions are called by reference, i.e., all the changes made to the reference
inside the function revert back to the original value referred by the reference. However, there is
an exception in the case of mutable objects since the changes made to the mutable objects like
string do not revert to the original string rather, a new string object is made, and therefore the
two different objects are printed.
Example 1 Passing Immutable Object (List)
#defining the function
def change_list(list1):
list1.append(20);
list1.append(30);
print("list inside function = ",list1)
#defining the list
list1 = [10,30,40,50]
#calling the function
change_list(list1);
print("list outside function = ",list1);
Output:
list inside function = [10, 30, 40, 50, 20, 30]
list outside function = [10, 30, 40, 50, 20, 30]
Example 2 Passing Mutable Object (String)
#defining the function
def change_string (str):
str = str + " Hello";
print("printing the string inside function :",str);
string1 = "Hi I am there"
#calling the function
change_string(string1)
print("printing the string outside function :",string1)
Output:
printing the string inside function : Hi I am there Hows you
printing the string outside function : Hi I am there
Types of arguments
There may be several types of arguments which can be passed at the time of function calling.
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
1. Required Arguments
Till now, we have learned about function calling in python. However, we can provide the
arguments at the time of function calling. As far as the required arguments are concerned, these
are the arguments which are required to be passed at the time of function calling with the exact
match of their positions in the function call and function definition. If either of the arguments is
not provided in the function call, or the position of the arguments is changed, then the python
interpreter will show the error.
Consider the following example.
Example 1
#the argument name is the required argument to the function func
def func(name):
message = "Hi "+name;
return message;
name = input("Enter the name?")
print(func(name))
Output:
Enter the name?Ravi
Hi Ravi
Example 2
#the function simple_interest accepts three arguments and returns the simple interest accordingly
def simple_interest(p,t,r):
return (p*t*r)/100
p = float(input("Enter the principle amount? "))
r = float(input("Enter the rate of interest? "))
t = float(input("Enter the time in years? "))
print("Simple Interest: ",simple_interest(p,r,t))
Output:
Enter the principle amount? 10000
Enter the rate of interest? 5
Enter the time in years? 2
Simple Interest: 1000.0
2. Keyword arguments
Python allows us to call the function with the keyword arguments. This kind of function call will
enable us to pass the arguments in the random order. The name of the arguments is treated as the
keywords and matched in the function calling and definition. If the same match is found, the
values of the arguments are copied in the function definition.
Example 1
#function func is called with the name and message as the keyword arguments
def func(name,message):
print("printing the message with",name,"and ",message)
func(name = "Ravi",message="hello") #name and message is copied with the values John and he
llo respectively
Output:
printing the message with Ravi and hello
Example 2 providing the values in different order at the calling
#The function simple_interest(p, t, r) is called with the keyword arguments the order of argument
s doesn't matter in this case
def simple_interest(p,t,r):
return (p*t*r)/100
print("Simple Interest: ",simple_interest(t=10,r=10,p=1900))
Output:
Simple Interest: 1900.0
3. Default Arguments
Python allows us to initialize the arguments at the function definition. If the value of any of the
argument is not provided at the time of function call, then that argument can be initialized with
the value given in the definition even if the argument is not specified at the function call.
Example 1
def printme(name,age=22):
print("My name is",name,"and age is",age)
printme(name = "john") #the variable age is not passed into the function however the default val
ue of age is considered in the function
Output:
My name is john and age is 22
4. Variable length Arguments
In the large projects, sometimes we may not know the number of arguments to be passed in
advance. In such cases, Python provides us the flexibility to provide the comma separated values
which are internally treated as tuples at the function call. However, at the function definition, we
have to define the variable with * (star) as *<variable - name >.

Example
def printme(*names):
print("type of passed argument is ",type(names))
print("printing the passed arguments...")
for name in names:
print(name)
printme("Rohan","Sohan","Mohan","Nikhil")

Output:
type of passed argument is <class 'tuple'>
printing the passed arguments...
Rohan
Sohan
Mohan
Nikhil
Scope of variables
The scopes of the variables depend upon the location where the variable is being declared. The
variable declared in one part of the program may not be accessible to the other parts.
In python, the variables are defined with the two types of scopes.
1. Global variables
2. Local variables
The variable defined outside any function is known to have a global scope whereas the variable
defined inside a function is known to have a local scope.
Example 1
def print_message():
message = "hello !! I am going to print a message." # the variable message is local to the funct
ion itself
print(message)
print_message()
print(message) # this will cause an error since a local variable cannot be accessible here.
Output:
hello !! I am going to print a message.
File "/root/PycharmProjects/PythonTest/Test1.py", line 5, in
print(message)
NameError: name 'message' is not defined
Example 2
def calculate(*args):
sum=0
for arg in args:
sum = sum +arg
print("The sum is",sum)
sum=0
calculate(10,20,30) #60 will be printed as the sum
print("Value of sum outside the function:",sum) # 0 will be printed
Output:
The sum is 60
Value of sum outside the function: 0

Functions - "First Class Citizens"

First class objects in a language are handled uniformly throughout. They may be stored in data
structures, passed as arguments, or used in control structures. A programming language is said to
support first-class functions if it treats functions as first-class objects. Python supports the
concept of First Class functions.
Properties of first class functions:
 A function is an instance of the Object type.
 You can store the function in a variable.
 You can pass the function as a parameter to another function.
 You can return the function from a function.
 You can store them in data structures such as hash tables, lists, …
Functions are objects: Python functions are first class objects. In the example below, we are
assigning function to a variable.

Passing Functions to a Function


Because functions are objects we can pass them as arguments to other functions. Functions that
can accept other functions as arguments are also called higher-order functions. In the example
below, we have created a function greet which takes a function as an argument.
# Python program to illustrate functions
# can be passed as arguments to other functions
def shout(text):
return text.upper()

def whisper(text):
return text.lower()

def greet(func):
# storing the function in a variable
greeting = func("Hi, I am created by a function passed as an argument.")
print greeting

greet(shout)
greet(whisper)
Output
HI, I AM CREATED BY A FUNCTION PASSED AS AN ARGUMENT.

hi, i am created by a function passed as an argument.

Map
map() function returns a list of the results after applying the given function to each item of a
given iterable (list, tuple etc.)
Syntax :
map(fun, iter)

Parameters :
fun : It is a function to which map passes each element of given iterable.
iter : It is a iterable which is to be mapped.

NOTE : You can pass one or more iterable to the map() function.
# Python program to demonstrate working
# of map.
# Return double of n
def addition(n):
return n + n
# We double all numbers using map()
numbers = (1, 2, 3, 4)
result = map(addition, numbers)
print(list(result))

filter
element in the sequence to be true or not.

syntax:
filter(function, sequence)

Parameters:
function: function that tests if each element of a
sequence true or not.
sequence: sequence which needs to be filtered, it can
be sets, lists, tuples, or containers of any iterators.
Retruns:
returns an iterator that is already filtered.
# function that filters vowels
def fun(variable):
letters = ['a', 'e', 'i', 'o', 'u']
if (variable in letters):
return True
else:
return False
# sequence
sequence = ['g', 'e', 'e', 'j', 'k', 's', 'p', 'r']
# using filter function
filtered = filter(fun, sequence)
print('The filtered letters are:')
for s in filtered:
print(s)

Mapping Functions in a Dictionary


Use {} curly brackets to construct the dictionary, and [] square brackets to index it. Separate the
key and value with colons : and with commas , between each pair. Keys must be quoted As with
lists we can print out the dictionary by printing the reference to it. A dictionary maps a set of
objects (keys) to another set of objects (values). A Python dictionary is a mapping of unique keys
to values. Dictionaries are mutable, which means they can be changed. The values that the keys
point to can be any Python value. Dictionaries are unordered, so the order that the keys are added
doesn't necessarily reflect what order they may be reported back.

released = {

"iphone" : 2007,

"iphone 3G" : 2008,

"iphone 3GS" : 2009,

"iphone 4" : 2010,

"iphone 4S" : 2011,

"iphone 5" : 2012

print released

Lambda
A lambda function is a small anonymous function. A lambda function can take any number of
arguments, but can only have one expression

Syntax

lambda arguments : expression

The expression is executed and the result is returned:

Example

A lambda function that adds 10 to the number passed in as an argument, and print the result:

x = lambda a : a + 10
print(x(5))

Lambda functions can take any number of arguments:

Example

A lambda function that multiplies argument a with argument b and print the result:

x = lambda a, b : a * b
print(x(5, 6))

Inner Functions
To define an inner function in Python, we simply create a function inside another function using
the Python's def keyword. Here is an example:

def function1(): # outer function


print ("Hello from outer function")
def function2(): # inner function
print ("Hello from inner function")
function2()
function1()
Output
Hello from outer function

Closures

Closure is basically keeping a record of a function with an environment. For example, if we call
a function with an argument (foo(1)), then it must keep a record of the environment with that
argument to be used later in the program. It will be clear from the examples given below.
def f1(a):

def f2(b):

return a+b

return f2

a = f1(1)

b = f1(100)

print (a(2))

print (b(2))

Output

102

You can see that the environment created by f1(1) is different from that of f1(100), and both
were remembered by Python, thus printing different values for a(2) and b(2). This is what
closure is.
So basically, a function (object) that remembers the environment where it was made is a closure.

A closure is also the answer to the question - "What is the use of nested function". But this also
gives us another question - "What is the use of closures?"

Classes are more flexible than closures but closures are faster. One can make closures to handle
simple cases where making a class is not really necessary.
Chapter 6
Modules
A python module can be defined as a python program file which contains a python code
including python functions, class, or variables. In other words, we can say that our python code
file saved with the extension (.py) is treated as the module. We may have a runnable code inside
the python module. Modules in Python provides us the flexibility to organize the code in a
logical way.
To use the functionality of one module into another, we must have to import the specific module.
Example
In this example, we will create a module named as file.py which contains a function func that
contains a code to print some message on the console.
Let's create the module named as file.py.
#displayMsg prints a message to the name being passed.
def displayMsg(name)
print("Hi "+name);
Here, we need to include this module into our main module to call the method displayMsg()
defined in the module named file.
Loading the module in our python code
We need to load the module in our python code to use its functionality. Python provides two
types of statements as defined below.
1. The import statement
2. The from-import statement
The import statement
The import statement is used to import all the functionality of one module into another. Here, we
must notice that we can use the functionality of any python source file by importing that file as
the module into another python source file.
We can import multiple modules with a single import statement, but a module is loaded once
regardless of the number of times, it has been imported into our file.
The syntax to use the import statement is given below.
import module1,module2,........ module n
Hence, if we need to call the function displayMsg() defined in the file file.py, we have to import
that file as a module into our module as shown in the example below.
Example:
import file;
name = input("Enter the name?")
file.displayMsg(name)
Output:
Enter the name?Kavi
Hi Kavi
The from-import statement
Instead of importing the whole module into the namespace, python provides the flexibility to
import only the specific attributes of a module. This can be done by using from? import
statement. The syntax to use the from-import statement is given below.
from < module-name> import <name 1>, <name 2>..,<name n>
Consider the following module named as calculation which contains three functions as
summation, multiplication, and divide.
calculation.py:
#place the code in the calculation.py
def summation(a,b):
return a+b
def multiplication(a,b):
return a*b;
def divide(a,b):
return a/b;
Main.py:
from calculation import summation
#it will import only the summation() from calculation.py
a = int(input("Enter the first number"))
b = int(input("Enter the second number"))
print("Sum = ",summation(a,b)) #we do not need to specify the module name while accessing su
mmation()
Output:
Enter the first number10
Enter the second number20
Sum = 30
The from...import statement is always better to use if we know the attributes to be imported from
the module in advance. It doesn't let our code to be heavier. We can also import all the attributes
from a module by using *.
Consider the following syntax.
from <module> import *
Renaming a module
Python provides us the flexibility to import some module with a specific name so that we can use
this name to use that module in our python source file.
The syntax to rename a module is given below.
import <module-name> as <specific-name>
Example
#the module calculation of previous example is imported in this example as cal.
import calculation as cal;
a = int(input("Enter a?"));
b = int(input("Enter b?"));
print("Sum = ",cal.summation(a,b))
Output:
Enter a?10
Enter b?20
Sum = 30

Standard Modules – sys


The sys module provides functions and variables used to manipulate different parts of the Python
runtime environment. You will learn some of the important features of this module here.
sys.exit
This causes the script to exit back to either the Python console or the command prompt. This is
generally used to safely exit from the program in case of generation of an exception.

sys.maxsize
Returns the largest integer a variable can take.
>>> import sys
>>>sys.maxsize
9223372036854775807
sys.path
This is an environment variable that is a search path for all Python modules.
>>>sys.path
['', 'C:\\python36\\Lib\\idlelib', 'C:\\python36\\python36.zip', 'C:\\python36\\DLLs',
'C:\\python36\\lib', 'C:\\python36', 'C:\\Users\\acer\\AppData\\Roaming\\Python\\Python36\\site-
packages', 'C:\\python36\\lib\\site-packages']
sys.version
This attribute displays a string containing the version number of the current Python interpreter.
>>>sys.version
'3.7.0 (v3.7.0:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)]'

Standard Modules – math


Some of the most popular mathematical functions are defined in the math module. These include
trigonometric functions, representation functions, logarithmic functions, angle conversion
functions, etc. In addition, two mathematical constants are also defined in this module.

Pie (π) is a well-known mathematical constant, which is defined as the ratio of the circumference
to the diameter of a circle and its value is 3.141592653589793.
>>> import math
>>>math.pi
3.141592653589793
Another well-known mathematical constant defined in the math module is e. It is called Euler's
number and it is a base of the natural logarithm. Its value is 2.718281828459045.
>>>math.e
2.718281828459045
The math module contains functions for calculating various trigonometric ratios for a given
angle. The functions (sin, cos, tan, etc.) need the angle in radians as an argument. We, on the
other hand, are used to express the angle in degrees. The math module presents two angle
conversion functions: degrees() and radians(), to convert the angle from degrees to radians and
vice versa. For example, the following statements convert the angle of 30 degrees to radians and
back (Note: π radians is equivalent to 180 degrees).
>>>math.radians(30)
0.5235987755982988
>>>math.degrees(math.pi/6)
29.999999999999996
The following statements show sin, cos and tan ratios for the angle of 30 degrees
(0.5235987755982988 radians):
>>math.sin(0.5235987755982988)
0.49999999999999994
>>>math.cos(0.5235987755982988)
0.8660254037844387
>>>math.tan(0.5235987755982988)
0.5773502691896257
You may recall that sin(30)=0.5, cos(30)=32 (which is 0.8660254037844387) and tan(30)= 13
(which is 0.5773502691896257).
math.log()
The math.log() method returns the natural logarithm of a given number. The natural logarithm is
calculated to the base e.
>>>math.log(10)
2.302585092994046
math.log10()
The math.log10() method returns the base-10 logarithm of the given number. It is called the
standard logarithm.
>>>math.log10(10)
1.0
math.exp()
The math.exp() method returns a float number after raising e (math.e) to given number. In other
words, exp(x) gives e**x.
>>>math.log10(10)
1.0
This can be verified by the exponent operator.
>>>math.e**10
22026.465794806703
math.pow()
The math.pow() method receives two float arguments, raises the first to the second and returns
the result. In other words, pow(4,4) is equivalent to 4**4.
>>>math.pow(2,4)
16.0
>>>2**4
16
math.sqrt()
The math.sqrt() method returns the square root of a given number.
>>>math.sqrt(100)
10.0
>>>math.sqrt(3)
1.7320508075688772
The following two functions are called representation functions. The ceil() function
approximates the given number to the smallest integer, greater than or equal to the given floating
point number. The floor() function returns the largest integer less than or equal to the given
number.
>>>math.ceil(4.5867)
5
>>>math.floor(4.5687)
4
Standard Modules - time
In the real world applications, there are the scenarios where we need to work with the date and
time. There are the examples in python where we have to schedule the script to run at some
particular timings.

In python, the date is not a data type, but we can work with the date objects by importing the
module named with datetime, time, and calendar.

Tick
In python, the time instants are counted since 12 AM, 1st January 1970. The function time() of
the module time returns the total number of ticks spent since 12 AM, 1st January 1970. A tick
can be seen as the smallest unit to measure the time.
Consider the following example.
Example
import time;
#prints the number of ticks spent since 12 AM, 1st January 1970
print(time.time())
Output:
1545124460.9151757
The localtime() functions of the time module are used to get the current time tuple. Consider the
following example.
Example
import time;
#returns a time tuple
print(time.localtime(time.time()))
Output:
time.struct_time(tm_year=2018, tm_mon=12, tm_mday=18, tm_hour=15, tm_min=1,
tm_sec=32, tm_wday=1, tm_yday=352, tm_isdst=0)
Time tuple
The time is treated as the tuple of 9 numbers. Let's look at the members of the time tuple.
Index Attribute Values
0 Year 4 digit (for example 2018)
1 Month 1 to 12
2 Day 1 to 31
3 Hour 0 to 23
4 Minute 0 to 59
5 Second 0 to 60
6 Day of weak 0 to 6
7 Day of year 1 to 366
8 Daylight -1, 0, 1 , or -1
savings

The datetime Module


The datetime module enables us to create the custom date objects, perform various operations on
dates like the comparison, etc.
To work with dates as date objects, we have to import datetime module into the python source
code.
Consider the following example to get the datetime object representation for the current time.
Example
import datetime;
#returns the current datetime object
print(datetime.datetime.now())
Output:
2018-12-18 16:16:45.462778
The calendar module
Python provides a calendar object that contains various methods to work with the calendars.
Consider the following example to print the Calendar of the last month of 2018.
Example
import calendar;
cal = calendar.month(2018,12)
#printing the calendar of December 2018
print(cal)
Output:

December 2018

Mo Tu We Th Fr Sa Su

1 2

3 4 5 6 7 8 9

10 11 12 13 14 15 16

17 18 19 20 21 22 23

24 25 26 27 28 29 30
31

Using dir() function


The dir() function returns a sorted list of names defined in the passed module. This list contains
all the sub-modules, variables and functions defined in this module.

Consider the following example.

Example
import json
List = dir(json)
print(List)
Output:
['JSONDecoder', 'JSONEncoder', '__all__', '__author__', '__builtins__', '__cached__',
'__doc__',
'__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__',
'_default_decoder', '_default_encoder', 'decoder', 'dump', 'dumps', 'encoder', 'load',
'loads', 'scanner']

Exercise :
Very Short Answer Type Questions :

1. What is module ?
2. What is the extension of module file ?
3. What is import statement ?
4. Write the Names of modules.
5. What is dir ?

Short Answer Type Questions :

1. How module is imported in Python file.


2. Explain the math module with example.
3. What are various time function ?
4. Explain sys module.
5. How can you show calendar.

Long Answer Type Questions :

1. What is module ? How it is created and used in Python? What is its role ?
2. Explain various built in modules in Python with example.
Chapter 7.
Exceptions
An exception can be defined as an abnormal condition in a program resulting in the disruption in
the flow of the program. Whenever an exception occurs, the program halts the execution, and
thus the further code is not executed. Therefore, an exception is the error which python script is
unable to tackle with.
Python provides us with the way to handle the Exception so that the other part of the code can be
executed without any disruption. However, if we do not handle the exception, the interpreter
doesn't execute all the code that exists after that.
Common Exceptions
A list of common exceptions that can be thrown from a normal python program is given below.
1. ZeroDivisionError: Occurs when a number is divided by zero.
2. NameError: It occurs when a name is not found. It may be local or global.
3. IndentationError: If incorrect indentation is given.
4. IOError: It occurs when Input Output operation fails.
5. EOFError: It occurs when the end of the file is reached, and yet operations are being
performed.
Problem without handling exceptions
As we have already discussed, the exception is an abnormal condition that halts the execution of
the program. Consider the following example.
Example
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
print("a/b = %d"%c)
#other code:
print("Hi I am other part of the program")
Output:
Enter a:10
Enter b:0
Traceback (most recent call last):
File "exception-test.py", line 3, in <module>
c = a/b;
ZeroDivisionError: division by zero
If the python program contains suspicious code that may throw the exception, we must place that
code in the try block. The try block must be followed with the except statement which contains a
block of code that will be executed if there is some exception in the try block.

Syntax
try:
#block of code
except Exception1:
#block of code
except Exception2:
#block of code
#other code

We can also use the else statement with the try-except statement in which, we can place the code
which will be executed in the scenario if no exception occurs in the try block.
The syntax to use the else statement with the try-except statement is given below.
try:
#block of code

except Exception1:
#block of code

else:
#this code executes if no except block is executed

Example
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
print("a/b = %d"%c)
except Exception:
print("can't divide by zero")
else:
print("Hi I am else block")
Output:
Enter a:10
Enter b:2
a/b = 5
Hi I am else block
The except statement with no exception
Python provides the flexibility not to specify the name of exception with the except statement.
Consider the following example.
Example
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
print("a/b = %d"%c)
except:
print("can't divide by zero")
else:
print("Hi I am else block")
Output:
Enter a:10
Enter b:0
can't divide by zero
Points to remember
1. Python facilitates us to not specify the exception with the except statement.
2. We can declare multiple exceptions in the except statement since the try block may
contain the statements which throw the different type of exceptions.
3. We can also specify an else block along with the try-except statement which will be
executed if no exception is raised in the try block.
4. The statements that don't throw the exception should be placed inside the else block.
Example
try:
#this will throw an exception if the file doesn't exist.
fileptr = open("file.txt","r")
except IOError:
print("File not found")
else:
print("The file opened successfully")
fileptr.close()
Output:
File not found
Declaring multiple exceptions
The python allows us to declare the multiple exceptions with the except clause. Declaring
multiple exceptions is useful in the cases where a try block throws multiple exceptions.
Syntax
try:
#block of code
except (<Exception 1>,<Exception 2>,<Exception 3>,...<Exception n>)
#block of code
else:
#block of code
Example
try:
a=10/0;
except ArithmeticError,StandardError:
print "Arithmetic Exception"
else:
print "Successfully Done"
Output:
Arithmetic Exception
The finally block
We can use the finally block with the try block in which, we can pace the important code which
must be executed before the try statement throws an exception.
The syntax to use the finally block is given below.
syntax
try:
# block of code
# this may throw an exception
finally:
# block of code
# this will always be executed
Example
try:
fileptr = open("file.txt","r")
try:
fileptr.write("Hi I am good")
finally:
fileptr.close()
print("file closed")
except:
print("Error")
Output:
file closed
Error
Raising exceptions
An exception can be raised by using the raise clause in python. The syntax to use the raise
statement is given below.
syntax
raise Exception_class,<value>
Points to remember
1. To raise an exception, raise statement is used. The exception class name follows it.
2. An exception can be provided with a value that can be given in the parenthesis.
3. To access the value "as" keyword is used. "e" is used as a reference variable which stores
the value of the exception.
Example
try:
age = int(input("Enter the age?"))
if age<18:
raise ValueError;
else:
print("the age is valid")
except ValueError:
print("The age is not valid")
Output:
Enter the age?17
The age is not valid
Example
try:
a = int(input("Enter a?"))
b = int(input("Enter b?"))
if b is 0:
raise ArithmeticError;
else:
print("a/b = ",a/b)
except ArithmeticError:
print("The value of b can't be 0")
Output:
Enter a?10
Enter b?0
The value of b can't be 0
Custom Exception
The python allows us to create our exceptions that can be raised from the program and caught
using the except clause. However, we suggest you read this section after visiting the Python
object and classes.
Consider the following example.
Example
class ErrorInCode(Exception):
def __init__(self, data):
self.data = data
def __str__(self):
return repr(self.data)
try:
raise ErrorInCode(2000)
except ErrorInCode as ae:
print("Received error:", ae.data)
Output:
Received error: 2000
Python - Assert Statement
Python provides the assert statement to check if a given logical expression is true or false.
Program execution proceeds only if the expression is true and raises the AssertionError when it
is false. The following code shows the usage of the assert statement.
Example: assert
num=int(input('Enter a number: '))
assert num>=0
print('You entered: ', num)
The print statement will display if the entered number is greater than or equal to 0. Negative
numbers result in aborting the program after showing the AssertionError.
Result:
Enter a number: 100
You entered 100
Enter a number: -10
Traceback (most recent call last):
File "C:/python36/xyz.py", line 2, in <module>
assert num>=0
AssertionError
The assert statement can optionally include an error message string, which gets displayed along
with the AssertionError. In the above code, you can change the assert statement to the following
and run the code:
Example: assert
num=int(input('Enter a number: '))
assert num>=0, "Only positive numbers accepted."
print('You entered: ', num)
Output:
Enter a number: -10
Traceback (most recent call last):
File "C:/python36/xyz.py", line 2, in <module>
assert num>=0, "Only positive numbers accepted."
AssertionError: Only positive numbers accepted.
The AssertionError is also a built-in exception and can be handled using the try...except
construct as follows:
Example: AssertionError
try:
num=int(input('Enter a number: '))
assert(num >=0), "Only positive numbers accepted."
print(num)
except AssertionError as msg:
print(msg)

When the input causes an AssertionError, the program will not terminate, as was the case earlier.
Instead, it will be handled by the except block. The error message in the assert statement will be
passed as argument to the exception argument msg, using keyword as.
Output:
Enter a number: -10
Only positive numbers accepted.

Exercise :
Very Short Answer Questions :

1. What is exception ?
2. Write some name of exception?
3. What is try statement ?
4. What is catch statement ?
5. What is finally statement ?
6. Explain assert statement.

Short Answer Questions:


1 Why exception handling is required.
2 What is exception and how it is handled in Phyton
3 Explain try catch and finally statement.
4 How can you arise exception ?
5 Explain assert statement with example.
Long Answer Questions :

1. Explain the process of exception handling in Python with suitable example.


Chapter 9
Input and Output
Till now, we were taking the input from the console and writing it back to the console to interact
with the user. Sometimes, it is not enough to only display the data on the console. The data to be
displayed may be very large, and only a limited amount of data can be displayed on the console,
and since the memory is volatile, it is impossible to recover the programmatically generated data
again and again. However, if we need to do so, we may store it onto the local file system which
is volatile and can be accessed every time. Here, comes the need of file handling.
Opening a file
Python provides the open() function which accepts two arguments, file name and access mode in
which the file is accessed. The function returns a file object which can be used to perform
various operations like reading, writing, etc.
The syntax to use the open() function is given below.
file object = open(<file-name>, <access-mode>, <buffering>)
The files can be accessed using various modes like read, write, or append. The following are the
details about the access mode to open a file.
Access
SN Description
mode
It opens the file to read-only. The file pointer exists at the beginning. The file is by default
1 r
open in this mode if no access mode is passed.
It opens the file to read only in binary format. The file pointer exists at the beginning of the
2 rb
file.
3 r+ It opens the file to read and write both. The file pointer exists at the beginning of the file.
It opens the file to read and write both in binary format. The file pointer exists at the
4 rb+
beginning of the file.

It opens the file to write only. It overwrites the file if previously exists or creates a new one
5 w
if no file exists with the same name. The file pointer exists at the beginning of the file.
It opens the file to write only in binary format. It overwrites the file if it exists previously or
6 wb
creates a new one if no file exists with the same name. The file pointer exists at the
beginning of the file.
It opens the file to write and read both. It is different from r+ in the sense that it overwrites
7 w+ the previous file if one exists whereas r+ doesn?t overwrite the previously written file. It
creates a new file if no file exists. The file pointer exists at the beginning of the file.
It opens the file to write and read both in binary format. The file pointer exists at the
8 wb+
beginning of the file.
It opens the file in the append mode. The file pointer exists at the end of the previously
9 a
written file if exists any. It creates a new file if no file exists with the same name.
It opens the file in the append mode in binary format. The pointer exists at the end of the
10 ab previously written file. It creates a new file in binary format if no file exists with the same
name.
It opens a file to append and read both. The file pointer remains at the end of the file if a file
11 a+
exists. It creates a new file if no file exists with the same name.
It opens a file to append and read both in binary format. The file pointer remains at the end
12 ab+
of the file.
Let's look at the simple example to open a file named "file.txt" (stored in the same directory) in read mode
and printing its content on the console.
Example
#opens the file file.txt in read mode
fileptr = open("file.txt","r")
if fileptr:
print("file is opened successfully")
Output:
<class '_io.TextIOWrapper'>
file is opened successfully

The close() method


Once all the operations are done on the file, we must close it through our python script using the
close() method. Any unwritten information gets destroyed once the close() method is called on a
file object.
We can perform any operation on the file externally in the file system is the file is opened in
python, hence it is good practice to close the file once all the operations are done.
The syntax to use the close() method is given below.
fileobject.close()
Example
# opens the file file.txt in read mode
fileptr = open("file.txt","r")
if fileptr:
print("file is opened successfully")
#closes the opened file
fileptr.close()

Reading the file


To read a file using the python script, the python provides us the read() method. The read()
method reads a string from the file. It can read the data in the text as well as binary format.
The syntax of the read() method is given below.
fileobj.read(<count>)
Here, the count is the number of bytes to be read from the file starting from the beginning of the
file. If the count is not specified, then it may read the content of the file until the end.
Consider the following example.
Example
#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file.txt","r");
#stores all the data of the file into the variable content
content = fileptr.read(9);
# prints the type of the data stored in the file
print(type(content))
#prints the content of the file
print(content)
#closes the opened file
fileptr.close()
Output:
<class 'str'>
Hi, I am
Read Lines of the file
Python facilitates us to read the file line by line by using a function readline(). The readline()
method reads the lines of the file from the beginning, i.e., if we use the readline() method two
times, then we can get the first two lines of the file.
Consider the following example which contains a function readline() that reads the first line of
our file "file.txt" containing three lines.
Example
#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file.txt","r");
#stores all the data of the file into the variable content
content = fileptr.readline();
# prints the type of the data stored in the file
print(type(content))
#prints the content of the file
print(content)
#closes the opened file
fileptr.close()
Output:
<class 'str'>
Hi, I am the file and being used as

Looping through the file


By looping through the lines of the file, we can read the whole file.
Example
#open the file.txt in read mode. causes an error if no such file exists.
fileptr = open("file.txt","r");
#running a for loop
for i in fileptr:
print(i) # i contains each line of the file
Output:
Hi, I am the file and being used as
an example to read a
file in python.
Writing the file
To write some text to a file, we need to open the file using the open method with one of the
following access modes.
a: It will append the existing file. The file pointer is at the end of the file. It creates a new file if
no file exists.
w: It will overwrite the file if any file exists. The file pointer is at the beginning of the file.
Consider the following example.
Example 1
#open the file.txt in append mode. Creates a new file if no such file exists.
fileptr = open("file.txt","a");
#appending the content to the file
fileptr.write("Python is the modern day language. It makes things so simple.")
#closing the opened file
fileptr.close();
Now, we can see that the content of the file is modified.
File.txt:
Hi, I am the file and being used as
an example to read a
file in python.
Python is the modern day language. It makes things so simple.
Example 2
#open the file.txt in write mode.
fileptr = open("file.txt","w");
#writing the content of the file
fileptr.write("Python is the modern day language. It makes things so simple.")
#closing the opened file
fileptr.close();
Now, we can check that all the previously written content of the file is overwritten with the new
text we have passed.
File.txt:
Python is the modern day language. It makes things so simple.
Creating a new file
The new file can be created by using one of the following access modes with the function open().
x: it creates a new file with the specified name. It causes an error a file exists with the same
name.
a: It creates a new file with the specified name if no such file exists. It appends the content to the
file if the file already exists with the specified name.
w: It creates a new file with the specified name if no such file exists. It overwrites the existing
file.
Consider the following example.
Example
#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file2.txt","x");
print(fileptr)
if fileptr:
print("File created successfully");
Output:
File created successfully
Using with statement with files
The with statement was introduced in python 2.5. The with statement is useful in the case of
manipulating the files. The with statement is used in the scenario where a pair of statements is to
be executed with a block of code in between.
The syntax to open a file using with statement is given below.
with open(<file name>, <access mode>) as <file-pointer>:
#statement suite
The advantage of using with statement is that it provides the guarantee to close the file regardless
of how the nested block exits.
It is always suggestible to use the with statement in the case of file s because, if the break, return,
or exception occurs in the nested block of code then it automatically closes the file. It doesn't let
the file to be corrupted.
Consider the following example.
Example
with open("file.txt",'r') as f:
content = f.read();
print(content)
Output:
Python is the modern day language. It makes things so simple.
File Pointer positions
Python provides the tell() method which is used to print the byte number at which the file pointer
exists. Consider the following example.
Example
# open the file file2.txt in read mode
fileptr = open("file2.txt","r")
#initially the filepointer is at 0
print("The filepointer is at byte :",fileptr.tell())
#reading the content of the file
content = fileptr.read();
#after the read operation file pointer modifies. tell() returns the location of the fileptr.
print("After reading, the filepointer is at:",fileptr.tell())
Output:
The filepointer is at byte : 0
After reading, the filepointer is at 26
Modifying file pointer position
In the real world applications, sometimes we need to change the file pointer location externally
since we may need to read or write the content at various locations.
For this purpose, the python provides us the seek() method which enables us to modify the file
pointer position externally.
The syntax to use the seek() method is given below.
<file-ptr>.seek(offset[, from)
The seek() method accepts two parameters:
offset: It refers to the new position of the file pointer within the file.
from: It indicates the reference position from where the bytes are to be moved. If it is set to 0, the
beginning of the file is used as the reference position. If it is set to 1, the current position of the
file pointer is used as the reference position. If it is set to 2, the end of the file pointer is used as
the reference position.
Consider the following example.
Example
# open the file file2.txt in read mode
fileptr = open("file2.txt","r")
#initially the filepointer is at 0
print("The filepointer is at byte :",fileptr.tell())
#changing the file pointer location to 10.
fileptr.seek(10);
#tell() returns the location of the fileptr.
print("After reading, the filepointer is at:",fileptr.tell())
Output:
The filepointer is at byte : 0
After reading, the filepointer is at 10

Exercise :
Very Short Answer Question

1. What is the function of open() ?


2. How can you close a opened file in Python
3. What is access mode ?
4. Write the access mode to create new file in Python.
5. What is file pointer

Short Answer Question

6. What is file and how it opened in Python


7. Explain various mode of opening the file in Python
8. What is with statement ?
9. How can you create file in Python
10. How file pointer position can be changed ?

Short Answer Question


11. What is file ? Explain the method to open, close the file in Python
12. How files are read and written in Python.
Chapter 10
Classes in Python
Like other general purpose languages, python is also an object-oriented language since its
beginning. Python is an object-oriented programming language. It allows us to develop
applications using an Object Oriented approach. In Python, we can easily create and use classes
and objects.

Major principles of object-oriented programming system are given below.

 Object
 Class
 Method
 Inheritance
 Polymorphism
 Data Abstraction
 Encapsulation

Object

The object is an entity that has state and behavior. It may be any real-world object like the
mouse, keyboard, chair, table, pen, etc.

Everything in Python is an object, and almost everything has attributes and methods. All
functions have a built-in attribute __doc__, which returns the doc string defined in the function
source code.
Class
The class can be defined as a collection of objects. It is a logical entity that has some specific
attributes and methods. For example: if you have an employee class then it should contain an
attribute and method, i.e. an email id, name, age, salary, etc.
Syntax
class ClassName:
<statement-1>
.
.
<statement-N>
Method
The method is a function that is associated with an object. In Python, a method is not unique to
class instances. Any object type can have methods.
Inheritance
Inheritance is the most important aspect of object-oriented programming which simulates the real
world concept of inheritance. It specifies that the child object acquires all the properties and
behaviors of the parent object. By using inheritance, we can create a class which uses all the
properties and behavior of another class. The new class is known as a derived class or child
class, and the one whose properties are acquired is known as a base class or parent class. It
provides re-usability of the code.
Polymorphism
Polymorphism contains two words "poly" and "morphs". Poly means many and Morphs means
form, shape. By polymorphism, we understand that one task can be performed in different ways.
For example You have a class animal, and all animals speak. But they speak differently. Here,
the "speak" behavior is polymorphic in the sense and depends on the animal. So, the abstract
"animal" concept does not actually "speak", but specific animals (like dogs and cats) have a
concrete implementation of the action "speak".

Encapsulation
Encapsulation is also an important aspect of object-oriented programming. It is used to restrict
access to methods and variables. In encapsulation, code and data are wrapped together within a
single unit from being modified by accident.
Data Abstraction
Data abstraction and encapsulation both are often used as synonyms. Both are nearly synonym
because data abstraction is achieved through encapsulation. Abstraction is used to hide internal
details and show only functionalities. Abstracting something means to give names to things so
that the name captures the core of what a function or a whole program does.
Object-oriented vs Procedure-oriented Programming languages
Index Object-oriented Programming Procedural Programming

Object-oriented programming is the problem-


Procedural programming uses a list of
1. solving approach and used where
instructions to do computation step by step.
computation is done by using objects.

In procedural programming, It is not easy


It makes the development and maintenance
2. to maintain the codes when the project
easier.
becomes lengthy.

It simulates the real world entity. So real- It doesn't simulate the real world. It works
3. world problems can be easily solved through on step by step instructions divided into
oops. small parts called functions.

It provides data hiding. So it is more secure Procedural language doesn't provide any
4. than procedural languages. You cannot access proper way for data binding, so it is less
private data from anywhere. secure.

Example of object-oriented programming Example of procedural languages are: C,


5.
languages is C++, Java, .Net, Python, C#, etc. Fortran, Pascal, VB etc.

Python Class and Objects

As we have already discussed, a class is a virtual entity and can be seen as a blueprint of an
object. The class came into existence when it instantiated. Let's understand it by an example.
Suppose a class is a prototype of a building. A building contains all the details about the floor,
doors, windows, etc. we can make as many buildings as we want, based on these details. Hence,
the building can be seen as a class, and we can create as many objects of this class. On the other
hand, the object is the instance of a class. The process of creating an object can be called as
instantiation.
Creating classes in python
In python, a class can be created by using the keyword class followed by the class name. The
syntax to create a class is given below.
Syntax
class ClassName:
#statement_suite

In python, we must notice that each class is associated with a documentation string which can be
accessed by using <class-name>.__doc__. A class contains a statement suite including fields,
constructor, function, etc. definition.

Consider the following example to create a class Employee which contains two fields as
Employee id, and name.
The class also contains a function display() which is used to display the information of the
Employee.
Example
class Employee:
id = 10;
name = "ayush"
def display (self):
print(self.id,self.name)
Here, the self is used as a reference variable which refers to the current class object. It is always
the first argument in the function definition. However, using self is optional in the function call.

Creating an instance of the class


A class needs to be instantiated if we want to use the class attributes in another class or method.
A class can be instantiated by calling the class using the class name.

The syntax to create the instance of the class is given below.

<object-name> = <class-name>(<arguments>)

The following example creates the instance of the class Employee defined in the above example.
Example
class Employee:
id = 10;
name = "Ravi"
def display (self):
print("ID: %d \nName: %s"%(self.id,self.name))
emp = Employee()
emp.display()
Output:
ID: 10
Name: Ravi

Python Constructor
A constructor is a special type of method (function) which is used to initialize the instance
members of the class.
Constructors can be of two types.
 Parameterized Constructor
 Non-parameterized Constructor
Constructor definition is executed when we create the object of this class. Constructors also
verify that there are enough resources for the object to perform any start-up task.
Creating the constructor in python

In python, the method __init__ simulates the constructor of the class. This method is called when
the class is instantiated. We can pass any number of arguments at the time of creating the class
object, depending upon __init__ definition. It is mostly used to initialize the class attributes.
Every class must have a constructor, even if it simply relies on the default constructor.
Consider the following example to initialize the Employee class attributes.
Example
class Employee:
def __init__(self,name,id):
self.id = id;
self.name = name;
def display (self):
print("ID: %d \nName: %s"%(self.id,self.name))
emp1 = Employee("Ravi",101)
emp2 = Employee("Harshit",102)
#accessing display() method to print employee 1 information
emp1.display();
#accessing display() method to print employee 2 information
emp2.display();

Output:
ID: 101
Name: Ravi
ID: 102
Name: Harshit

Example: Counting the number of objects of a class


class Student:
count = 0
def __init__(self):
Student.count = Student.count + 1
s1=Student()
s2=Student()
s3=Student()
print("The number of students:",Student.count)

Output:
The number of students: 3

Python Non-Parameterized Constructor Example


class Student:
# Constructor - non parameterized
def __init__(self):
print("This is non parametrized constructor")
def show(self,name):
print("Hello",name)
student = Student()
student.show("Ravi")

Output:
This is non parametrized constructor
Hello Ravi

Python Parameterized Constructor Example


class Student:
# Constructor - parameterized
def __init__(self, name):
print("This is parametrized constructor")
self.name = name
def show(self):
print("Hello",self.name)
student = Student("Ravi")
student.show()

Output:
This is parametrized constructor
Hello Ravi

Python In-built class functions


The in-built functions defined in the class are described in the following table.
SN Function Description
1 getattr(obj,name,default) It is used to access the attribute of the object.
2 setattr(obj, name,value) It is used to set a particular value to the specific
attribute of an object.
3 delattr(obj, name) It is used to delete a specific attribute.
4 hasattr(obj, name) It returns true if the object contains some specific
attribute.
Example
class Student:
def __init__(self,name,id,age):
self.name = name;
self.id = id;
self.age = age
#creates the object of the class Student
s = Student("Ravi",101,22)
#prints the attribute name of the object s
print(getattr(s,'name'))
# reset the value of attribute age to 23
setattr(s,"age",23)
# prints the modified value of age
print(getattr(s,'age'))
# prints true if the student contains the attribute with name id

print(hasattr(s,'id'))
# deletes the attribute age
delattr(s,'age')
# this will give an error since the attribute age has been deleted
print(s.age)

Output:
Ravi
23
True
AttributeError: 'Student' object has no attribute 'age'
Built-in class attributes
Along with the other attributes, a python class also contains some built-in class attributes which
provide information about the class.
The built-in class attributes are given in the below table.
SN Attribute Description
1 __dict__ It provides the dictionary containing the information about the
class namespace.
2 __doc__ It contains a string which has the class documentation
3 __name__ It is used to access the class name.
4 __module__ It is used to access the module in which, this class is
defined.
5 __bases__ It contains a tuple including all base classes.
Example
class Student:
def __init__(self,name,id,age):
self.name = name;
self.id = id;
self.age = age
def display_details(self):
print("Name:%s, ID:%d, age:%d"%(self.name,self.id))
s = Student("Ravi",101,22)
print(s.__doc__)
print(s.__dict__)
print(s.__module__)

Output:
None
{'name': 'Ravi’', 'id': 101, 'age': 22}
__main__
Python Inheritance
Inheritance is an important aspect of the object-oriented paradigm. Inheritance provides code
reusability to the program because we can use an existing class to create a new class instead of
creating it from scratch. In inheritance, the child class acquires the properties and can access all
the data members and functions defined in the parent class. A child class can also provide its
specific implementation to the functions of the parent class. In python, a derived class can
inherit base class by just mentioning the base in the bracket after the derived class name.

Consider the following syntax to inherit a base class into the derived class.
Syntax
class derived-class(base class):
<class-suite>
A class can inherit multiple classes by mentioning all of them inside the bracket. Consider the
following syntax.
Syntax
class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
<class - suite>
Example 1
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
d.bark()
d.speak()
Output:
dog barking
Animal Speaking

Python Multi-Level inheritance


Multi-Level inheritance is possible in python like other object-oriented languages. Multi-level
inheritance is archived when a derived class inherits another derived class. There is no limit on
the number of levels up to which, the multi-level inheritance is archived in python.

The syntax of multi-level inheritance is given below.


Syntax
class class1:
<class-suite>
class class2(class1):
<class suite>
class class3(class2):
<class suite>
Example
class Animal:
def speak(self):
print("Animal Speaking")
#The child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
#The child class Dogchild inherits another child class Dog
class DogChild(Dog):
def eat(self):
print("Eating bread...")
d = DogChild()
d.bark()
d.speak()
d.eat()
Output:
dog barking
Animal Speaking
Eating bread...

Python Multiple inheritance


Python provides us the flexibility to inherit multiple base classes in the child class.
The syntax to perform multiple inheritance is given below.
Syntax
class Base1:
<class-suite>
class Base2:
<class-suite>
class BaseN:
<class-suite>
class Derived(Base1, Base2, ...... BaseN):
<class-suite>

Example
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(d.Summation(10,20))
print(d.Multiplication(10,20))
print(d.Divide(10,20))

Output:
30
200
0.5

The issubclass(sub,sup) method


The issubclass(sub, sup) method is used to check the relationships between the specified classes.
It returns true if the first class is the subclass of the second class, and false otherwise.
Consider the following example.
Example
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(issubclass(Derived,Calculation2))
print(issubclass(Calculation1,Calculation2))

Output:
True
False

The isinstance (obj, class) method


The isinstance() method is used to check the relationship between the objects and classes. It
returns true if the first parameter, i.e., obj is the instance of the second parameter, i.e., class.
Consider the following example.
Example
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(isinstance(d,Derived))

Output:
True

Method Overriding
We can provide some specific implementation of the parent class method in our child class.
When the parent class method is defined in the child class with some specific implementation,
then the concept is called method overriding. We may need to perform method overriding in the
scenario where the different definition of a parent class method is needed in the child class.
Consider the following example to perform method overriding in python.
Example
class Animal:
def speak(self):
print("speaking")
class Dog(Animal):
def speak(self):
print("Barking")
d = Dog()
d.speak()

Output:
Barking

Data abstraction in python


Abstraction is an important aspect of object-oriented programming. In python, we can also
perform data hiding by adding the double underscore (___) as a prefix to the attribute which is to
be hidden. After this, the attribute will not be visible outside of the class through the object.
Consider the following example.
Example
class Employee:
__count = 0;
def __init__(self):
Employee.__count = Employee.__count+1
def display(self):
print("The number of employees",Employee.__count)
emp = Employee()
emp2 = Employee()
try:
print(emp.__count)
finally:
emp.display()

Output:
The number of employees 2
AttributeError: 'Employee' object has no attribute '__count'
Exercise :
Very Short Answer Questions :

1. What is OOPS ?
2. Explain class.
3. Explain object.
4. What is Polymorphism ?
5. What is inheritance ?
6. What is constructor ?

Short Answer Questions :

1. What is class and how it is created in Python.


2. What is Object and how it is created in Python.
3. Write the name of different type of inheritance ?
4. What is Constructor and its types ?
5. Difference between object oriented programming and procedure programming.

Long Answer Questions :

1. Explain Object Oriented Programming in detail and its features.


2. What is class and object. How they are implemented in Python.
3. What is inheritance and its types. Explain with examples.
Chapter 10. Regular Expressions
Introduction
A regular expression in a programming language is a special text string used for describing a
search pattern. It is extremely useful for extracting information from text such as code, files, log,
spreadsheets or even documents. While using the regular expression the first thing is to
recognize is that everything is essentially a character, and we are writing patterns to match a
specific sequence of characters also referred as string. Ascii or latin letters are those that are on
your keyboards and Unicode is used to match the foreign text. It includes digits and punctuation
and all special characters like $#@!%, etc.

For instance, a regular expression could tell a program to search for specific text from the string
and then to print out the result accordingly. Expression can include Text matching, Repetition,
Branching & Pattern-composition etc.

In Python, a regular expression is denoted as RE (REs, regexes or regex pattern) are imported
through re module. Python supports regular expression through libraries. In Python regular
expression supports various things like Modifiers, Identifiers, and White space characters.

Simple Character Matches


The following regex functions are used in the python.

SN Function Description

This method matches the regex pattern in the string with the optional flag. It returns true if
1 match
a match is found in the string otherwise it returns false.

2 search This method returns the match object if there is a match found in the string.

3 findall It returns a list that contains all the matches of a pattern in the string.

4 split Returns a list in which the string has been split in each match.

5 sub Replace one or many matches in the string.

Example :
import re
str = "How are you. How is everything"
matches = re.findall("How", str)
print(matches)

Output:

['How', 'How']

Special Characters
Metacharacter/Special character is a character with the specified meaning.

Metacharacter Description Example

[] It represents the set of characters. "[a-z]"

\ It represents the special sequence. "\r"

. It signals that any character is present at some specific place. "Ja.v."

^ It represents the pattern present at the beginning of the string. "^Java"

$ It represents the pattern present at the end of the string. "point"

* It represents zero or more occurrences of a pattern in the string. "hello*"

+ It represents one or more occurrences of a pattern in the string. "hello+"

{} The specified number of occurrences of a pattern the string. "java{2}"

| It represents either this or that character is present. "java|point"

() Capture and group

Example
import re
str = "The Computer Programming"
#Find all lower case characters alphabetically between "a" and "m":
x = re.findall("[a-m]", str)
print(x)
Output:

['h', 'e', 'm', 'e', 'g', 'a', 'm', 'm', 'i', 'g']

import re
str = "hello world"
#Check if the string starts with 'hello':
x = re.findall("^hello", str)
if (x):
print("Yes, the string starts with 'hello'")
else:
print("No match")

Output :
Yes, the string starts with 'hello'

Character Classes

A special sequence is a \ followed by one of the characters in the list below, and has a special
meaning:

Character Description Example


Returns a match if the specified characters are at the beginning of the
\A “\AThe"
string
\D Returns a match where the string DOES NOT contain digits "\D"
\s Returns a match where the string contains a white space character "\s"
Returns a match where the string DOES NOT contain a white space
\S "\S"
character
Returns a match where the string contains any word characters
\w (characters from a to Z, digits from 0-9, and the underscore _ "\w"
character)
Returns a match where the string DOES NOT contain any word
\W "\W"
characters
Returns a match if the specified characters are at the end of the
\Z "Spain\Z"
string

Example :
import re
str = "The Computer Programming"
#Check if the string starts with "The":
x = re.findall("\AThe", str)
print(x)
if (x):
print("Yes, there is a match!")
else:
print("No match")
Output :

['The']
Yes, there is a match!

Quantifiers
A quantifier after a token, which can be a single character or group in brackets, specifies how
often that preceding element is allowed to occur. The most common quantifiers are

 the question mark ?


 the asterisk or star character *
 and the plus sign +

import re
str = "The Computer Programming requires logic skills"
#Check if the string contains "pu" followed by 0 or more "c" characters:
x = re.findall("puc*", str)
print(x)
if (x):
print("Yes, there is at least one match!")
else:
print("No match")

Output :
['pu']
Yes, there is at least one match!
The Dot Character
Dot character represents any character (except newline character)in expression.

import re
str = "hello world"
#Search for a sequence that starts with "he", followed by two (any) characters, and an "o":
x = re.findall("he..o", str)
print(x)

Output :
['hello']

Greedy Matches

The '*', '+', and '?' quantifiers are all greedy; they match as much text as possible. Adding ? after
the quantifier makes it perform the match in non-greedy or minimal fashion; as few characters as
possible will be matched.

Example :
import re
string = "<h1>Heading</h1><p>HTML text.</p>"
match = re.search("<.*>", string)
if match:
print("Greedy")
print("start:", match.start(0))
print("end:", match.end(0))
print("group:", match.group(0))
match = re.search("<.*?>", string)
if match:
print("\nNon-greedy")
print("start:", match.start(0))
print("end:", match.end(0))
print("group:", match.group(0))
Output:
Greedy
start: 0
end: 33
group: <h1>Heading</h1><p>HTML text.</p>
Non-greedy
start: 0
end: 4
group: <h1>

Grouping
Match groups match whatever regular expression is inside parentheses, and indicates the start
and end of a group; the contents of a group can be retrieved after a match has been performed.
Example:
import re
string = "<p>HTML text.</p>"
match = re.match("<p>(.*)</p>", string)
if match:
print("start:", match.start(1))
print("end:", match.end(1))
print("group:", match.group(1))
string = "'cat': 'Frisky', 'dog': 'Spot', 'fish': 'Bubbles'"
match = re.search("'cat': '(.*?)', 'dog': '(.*?)', 'fish': '(.*?)'", string)
if match:
print("groups:", match.group(1), match.group(2), match.group(3))

Output:
start: 3
end: 13
group: HTML text.
groups: Frisky Spot Bubbles
Matching at Beginning or End
^ searches string in the given expression from the beginning
import re
str = "hello world"
#Check if the string starts with 'hello':
x = re.findall("^hello", str)
if (x):
print("Yes, the string starts with 'hello'")
else:
print("No match")

Output :
Yes, the string starts with 'hello'
$ searches string in the given expression at the end.
import re
str = "hello world"
#Check if the string ends with 'world':
x = re.findall("world$", str)
if (x):
print("Yes, the string ends with 'world'")
else:
print("No match")

Output :
Yes, the string ends with 'hello'

Match Objects
The match object contains the information about the search and the output. If there is no match
found, the None object is returned.
Example
import re
str = "How are you. How many lines ?"
matches = re.search("How", str)
print(type(matches))
print(matches) #matches is the search object

Output:
<class '_sre.SRE_Match'>
<_sre.SRE_Match object; span=(0, 3), match='How'>

The Match object methods


There are the following methods associated with the Match object.
span(): It returns the tuple containing the starting and end position of the match.
string(): It returns a string passed into the function.
group(): The part of the string is returned where the match is found.
Example
import re
str = "How are you. How is everything"
matches = re.search("How", str)
print(matches.span())
print(matches.group())
print(matches.string)

Output:
(0, 3)
How
How are you. How is everything
Substituting
Substituting means replacing one character/string with another. The sub() function replaces the
matches with the text of your choice.
Example :
import re
#Replace all white-space characters with the digit "9":
str = "The rain in Spain"
x = re.sub("\s", "9", str)
print(x)

Splitting a String
The split() function returns a list where the string has been split at each match.
Example :

import re
#Split the string at every white-space character:
str = "The rain in Spain"
x = re.split("\s", str)
print(x)

Compiling Regular Expressions


If you want to use the same regexp more than once in a script, it might be a good idea to use a
regular expression object, i.e. the regex is compiled.
The general syntax:
re.compile(pattern[, flags])
compile returns a regex object, which can be used later for searching and replacing. The
expressions behaviour can be modified by specifying a flag value.
Compiled regular objects usually are not saving much time, because Python internally compiles
AND CACHES regexes whenever you use them with re.search() or re.match(). The only extra
time a non-compiled regex takes is the time it needs to check the cache, which is a key lookup of
a dictionary.
Flags

Compilation flags let you modify some aspects of how regular expressions work. Flags are
available in the re module under two names, a long name such as IGNORECASE and a short,
one-letter form such as I.

Sr.No. Flag & Meaning


ASCII, A
1
Makes several escapes like \w, \b, \s and \d match only on ASCII characters with the
respective property.
DOTALL, S
2
Make, match any character, including newlines
IGNORECASE, I
3
Do case-insensitive matches
LOCALE, L
4
Do a locale-aware match
MULTILINE, M
5
Multi-line matching, affecting ^ and $
VERBOSE, X (for ‘extended’)
6
Enable verbose REs, which can be organized more cleanly and understandably

Example:
import re
xx = """guru99
careerguru99
selenium"""
k1 = re.findall(r"^\w", xx)
k2 = re.findall(r"^\w", xx, re.MULTILINE)
print(k1)
print(k2)

Exercise:
Very Short Answer Questions :
1. What is regular expression ?
2. What is match function
3. What is quantifiers ?
4. What is the function of dot character ?
5. What characters are used for searching in beginning and at end ?
6. What is flag ?
Short Answer Questions :
1. What are special characters used in regular expression ?
2. Explain character classes used in regular expression.
3. Expalin different quantifiers.
4. What is greedy match ?
5. Explain Grouping in regular expression.
6. How can you match objects ?
7. What is Substituting ?
8. What is splitting ?

Long Answer Questions :


1. What is regular expression ? Explain different Python functions to search in regular
expression.
LIST OF PRACTICALS

1. What do the following string methods do?

 lower
 count
 replace
Answer : a) Lower function

Lower function will convert the given string in small letter.


a = "Hello, World!"
print(a.lower())

output :
hello, world!
b) count function
count method returns an integer that denotes number of times a substring occurs in a given
string.
a = "Hello, World! Hello, Python"
print(a.count("Hello"))
output :
2
c) replace function

The replace method replaces a string with another string:

a = "Hello, World!"
print(a.replace("H", "J"))
Output:
Jello, World!
2. Write instructions to perform each of the steps below
(a) Create a string containing at least five words and store it in a variable.
(b) Print out the string.
(c) Convert the string to a list of words using the string split method.
(d) Sort the list into reverse alphabetical order using some of the list methods
(e) Print out the sorted, reversed list of words.
Answer :
#creating string to store five words
a = "Apple,Ornage,Banana,Mango,Grapes"
#printing string
print(a)
#splitting the string
b = a.split(",")
#printing splitted string
print(b)
#sorting the list in reverse order
b.sort(reverse=True)
#printing the reverse list
print (b)

Output :
Apple,Ornage,Banana,Mango,Grapes
['Apple', 'Ornage', 'Banana', 'Mango', 'Grapes']
['Ornage', 'Mango', 'Grapes', 'Banana', 'Apple']
3. Write a program that determines whether the number is prime.
Answer :
#to check whether a number is prime no. or not prime no
n=int(input("Enter a number "))
r=2
while (r<n):
if(n%r)==0:
print(n," is not a prime no")
break;
r=r+1
if(n==r):
print(n, " is a prime no")

Output :
Enter a number 8
8 is not a prime no

Enter a number 7
7 is a prime no
4. Find all numbers which are multiple of 17, but not the multiple of 5, between 2000
and 2500?

#numbers which are multiple of 17, but not the multiple of 5, between 2000 and 2500
print(“numbers multiple of 17, but not the multiple of 5, between 2000 and 2500 “)
for i in range(2000,2501):
if (i % 17==0) and(not(i % 5==0)):
print (i)

Output :
numbers multiple of 17, but not the multiple of 5, between 2000 and 2500
2006
2023
2057
2074
2091
2108
2142
2159
2176
2193
2227
2244
2261
2278
2312
2329
2346
2363
2397
2414
2431
2448
2482
2499

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy