0% found this document useful (0 votes)
11 views157 pages

Python Programming Basics and Examples

The document provides a comprehensive index of Python programming exercises and concepts, covering topics such as installation, basic programming, data types, and various Python functions. It also includes a historical overview of Python, its features, and the advantages of using Python for programming. Additionally, it emphasizes Python's ease of use, portability, and object-oriented nature, making it suitable for both beginners and experienced developers.

Uploaded by

24h51a05v8
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views157 pages

Python Programming Basics and Examples

The document provides a comprehensive index of Python programming exercises and concepts, covering topics such as installation, basic programming, data types, and various Python functions. It also includes a historical overview of Python, its features, and the advantages of using Python for programming. Additionally, it emphasizes Python's ease of use, portability, and object-oriented nature, making it suitable for both beginners and experienced developers.

Uploaded by

24h51a05v8
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

INDEX

[Link]. Name of the Program Page No.


1. Install Anaconda open-source framework for python 26
2. Write a program to display ‘Hello World’. 33
3. Explore various IDEs for python program development 34
4. The volume of a sphere with radius r is 4/3 πr 3. Write a Python 34
program to find the volume of a sphere with radius 5?

5. Write a python program to find minimum and maximum of given 44


three numbers
6. Suppose the cover price of a book is $24.95, but bookstores get a 45
40% discount. Shipping costs $3 for the first copy and 75 cents for
each additional copy. Write a python program to compute the total
wholesale cost for 60 copies?.
7. Write a Python Program to Find the Square Root of a number with 46
out using sqrt function.
8. Python Program to Convert Celsius To Fahrenheit 47
9. Python program to find the maximum of two numbers using ternary 48
operator.
10. Write a Python program to find area of circle. 57
11. Write a program to read Employee data from the keyboard and print 57
that data.
12. Write a program to read 3 float numbers from the keyboard with 58
comma separator and print their sum.
13 Write a program to display Command Line Arguments. 58
14. Write a Python program to take a single digit number from the key 73
board and print is value in English word?
15. Write a Python Program to check whether an n-digit integer is an 74
Armstrong number or not
16. Write a Python program to display *'s in pyramid style(also known 75
as equivalent triangle).

1
17. Write a Python Program to Display the multiplication Table. 76
18. Write a python function to find factorial of given number? 93
19. Write a program to create a lambda function to find square of given 94
number?

20. Lambda Function to find biggest of given values 94


21. Program to filter only even numbers from the list by using filter() 94
function?
22. Experiment-1: Write a program to accept some string from the 104
keyboard and display its characters by index wise (both positive and
negative index).
23. Experiment-2: Write a program to access each character of string in 104
forward and backward direction by using while loop?
24. Program to display all positions of substring in a given main string. 105
25. Write a program to reverse the given String. 106
26. Write a Python program to display unique vowels present in the 114
given word.
27. Write a Python program to Count the Occurrence of an Item in a 114
List.
28 Write a Python program to segregate even and odd numbers from 114
the given list of numbers.
29 Write a Python program to find the cumulative sum of elements of 115
the list.
30 Python program for adding a Tuple to List and Vice-Versa. 119
31 Write a Python program to perform the summation of all elements 121
of each tuple from the list of tuples
32 Write a Python program to multiply adjacent elements of a tuple 122
33 Write a Python program to find the maximum element in the tuple 123
list.
34 Write a Python program to perform set operations. 129
35 Write a program to print different vowels present in the given word? 130
36 Write a Python program to generate powers of 2 using set 130

2
comprehensions.
37 Write a program to eliminate duplicates present in the list using set 131
38 Write a Python program to enter name and percentage marks in a 131
dictionary and display information on the console.
39 Write a program to take dictionary from the keyboard and print the 132
sum of values?
40 Write a program to take dictionary from the keyboard and print the 133
sum of values?
41 Write a program to find number of occurrences of each letter present 133
in the given string using dictionary.
42 Write a program to accept student name and marks from the 160
keyboard and creates a dictionary. Also display student marks by
taking student name as input?
43 Create a module [Link] containing Fibonacci(n) function(s) and 161
import fibo module in a python script to print Fibonacci series
upton.
44 Write a python program to print all the contents of a given module 162
45 Write a python program to create a package containing two or 164
modules
46 Write a python program to import module from a package created in 164
Experiment 3.
47 Write a program to check whether the given file exists or not. If it is 165
available then print its content?
48 Write a python Program to print the number of lines,words and 165
characters present in the given file?
49 Program to read image file and write to a new image file? 168
50 Write a python program to read and write to a CSV file. 168

Lab1:

3
1. Python Language Fundamentals-Installation -Identifiers, Reserved
Words, Data Types, Type Casting, Immutability.
i) Write a simple program to display “Hello,World!” on the screen.

Problem Description:First learn the basic concept of python programming History and installation
process along with all supportive datatypes, keywords, and data conversion.

Definition:
Python is a high-level, interpreted, interactive and object-oriented scripting
[Link] is designed to be highly readable. It uses English keywords frequently where as
otherlanguagesusepunctuation,andithasfewersyntacticalconstructionsthanotherlanguages.
 Python is Interpreted: Python is processed at runtime by the interpreter. You do
[Link] toPERLandPHP.
 Python is Interactive: You can actually sit at a Python prompt and interact with
theinterpreterdirectlytowriteyourprograms.
 PythonisObject-Oriented:PythonsupportsObject-
Orientedstyleortechniqueofprogrammingthat encapsulates codewithinobjects.
 Python is a Beginner's Language: Python is a great language for the beginner-
levelprogrammers and supports the development of a wide range of applications from
simpletextprocessingtoWWWbrowsers togames.
HistoryofPython
 Python was developed by Guido van Rossum in the late
eightiesandearlyninetiesattheNationalResearchInstituteforMathematic
sand ComputerScienceintheNetherlands.
 Python is derived from many other languages, including
ABC,Modula-3, C, C++, Algol-68, SmallTalk, Unix shell, and
otherscriptinglanguages.
 At the time when he began implementing Python, Guido van Rossum was also readingthe
published scripts from "Monty Python's Flying Circus" (a BBC comedy series fromthe
seventies, in the unlikely case you didn't know). It occurred to him that he needed aname that
was short, unique, and slightly mysterious, so he decided to call the languagePython.
 Pythonisnowmaintainedbyacoredevelopmentteamattheinstitute,althoughGuidovanRossumstillh
oldsavital role indirectingitsprogress.
 Python1.0wasreleased on 20February,1991.
 Python2.0wasreleasedon16October2000andhadmanymajornewfeatures,including a cycle
detecting garbage collector and support for Unicode. With this releasethe development process
was changed and became more transparent and community-backed.
 Python 3.0 (which early in its development was commonly referred to as Python 3000
orpy3k), a major, backwards-incompatible release, was released on 3 December 2008

4
afteralong [Link]-
compatiblePython [Link] [Link].
 In January 2017 Google announced work on a Python 2.7 to go transcompiler, which
TheRegisterspeculatedwasinresponsetoPython 2.7'splanned end-of-life.
PythonFeatures:
Python'sfeaturesinclude:
 Easy-to-learn: Python has few keywords, simple structure, and a clearly defined
[Link] thestudenttopickup thelanguagequickly.
 Easy-to-read:Pythoncodeismoreclearlydefinedandvisible totheeyes.
 Easy-to-maintain:Python'ssourcecodeisfairlyeasy-to-maintain.
 A broad standard library: Python's bulk of the library is very portable and cross-
platformcompatibleonUNIX, Windows, andMacintosh.
 Interactive Mode: Python has support for an interactive mode which allows
interactivetestingand debuggingofsnippets ofcode.
 Portable: Python can run on a wide variety of hardware platforms and has the
sameinterfaceon allplatforms.
 Extendable: You can add low-level modules to the Python interpreter. These
modulesenableprogrammers toaddto or customizetheirtoolstobemore efficient.
 Databases:Pythonprovidesinterfacestoallmajorcommercialdatabases.
 GUI Programming: Python supports GUI applications that can be created and ported tomany
system calls, libraries, and windows systems, such as Windows MFC, Macintosh,andthe
XWindow systemofUNIX.
 Scalable: Python provides a better structure and support for large programs than
shellscripting.

NeedofPythonProgramming
 Softwarequality
Python code is designed to be readable, and hence reusable and maintainable—much
more so than traditional scripting languages. The uniformity of Python code makesit easy
tounderstand, even if you did not write it. In addition, Python has deep
supportformoreadvancedsoftwarereusemechanisms,suchasobject-
oriented(OO)andfunctionprogramming.
 Developerproductivity

Python boosts developer productivity many times beyond compiled or staticallytyped


languages such as C, C++, and Java. Python code is typically one-third to less
todebug,andlesstomaintain [Link]
programsalsorunimmediately,withoutthelengthycompileandlinkstepsrequiredbysomeothertools
,furtherboostingprogrammer speed. Program portability Most Python programs run

5
unchanged on
[Link],forexample, is
usuallyjusta matterof copyingascript‘s codebetween machines.
 Support libraries

Pythoncomeswithalargecollectionofprebuiltandportablefunctionality,knownasthestanda
[Link]-levelprogramming tasks, from text pattern
matching to network scripting. In addition, Pythoncan be extended with both home grown
libraries and a vast collection of [Link]‘sthird-
partydomainofferstoolsforwebsiteconstruction, numeric programming, serial port access, game
development, and muchmore(seeahead for asampling).
 Componentintegration

Python scripts can easily communicate with other parts of an application, using
avariety [Link] usedasaproduct
customization and extension tool. Today, Python code can invoke C and C++libraries, can be
called from C and C++ programs, can integrate with Java
and .NETcomponents,cancommunicateoverframeworkssuchasCOMandSilverlight,caninterfac
ewithdevicesoverserialports,andcaninteractovernetworkswithinterfaceslikeSOAP, XML-RPC,
[Link] a standalonetool.
 Enjoyment

Because of Python‘s easeofuse and built-in toolset, it can make the act ofprogramming
more pleasure than chore. Although this may be an intangible benefit, itseffect on
productivity is an important asset. Of these factors, the first two (quality
andproductivity)areprobablythemostcompellingbenefitstomostPythonusers,andmeritafullerdes
cription.
 It'sObject-Oriented
Pythonisanobject-orientedlanguage,[Link] advanced
notions such as polymorphism, operator overloading, and multipleinheritance; yet in the
context of Python's dynamic typing, object-oriented programming(OOP) is remarkably easy
toapply. Python's OOP nature makes it ideal as a scriptingtool for object-oriented systems
languages such as C++ and Java. For example, Pythonprogramscan subclass
(specialized)classes implementedinC++or Java.
 It'sFree
Python is freeware—something which has lately been come to be called opensource
software. As with Tcl and Perl, you can get the entire system for free over
[Link],embeddingit inyoursystems,orshipping it
withyour [Link] fact,you can even sell Python,if you're so [Link] don't get the

6
wrong idea: "free" doesn't mean "unsupported". On the contrary, thePython online community
responds to user queries with a speed that most commercialsoftwarevendorswoulddo
welltonotice.
 It'sPortable
Python is written in portable ANSI C, and compiles and runs on virtually
[Link],itrunsonUNIXsystems,Linux,MS-DOS,
MS-Windows (95, 98, NT), Macintosh, Amiga, Be-OS, OS/2, VMS, QNX, and [Link],
Python programs are automatically compiled to portable bytecode, which runsthe same on any
platform with a compatible version of Python installed (more on this inthe section "It's easy to
use"). What that means is that Python programs that use the corelanguage run the same on
UNIX, MS-Windows, and any other system with a Pythoninterpreter.
 It'sPowerful
From a features perspective, Python is something of a hybrid. Its tool set places
itbetween traditional scripting languages (such as Tcl, Scheme, and Perl), and
systemslanguages (such as C, C++, and Java). Python provides all the simplicity and ease of
useof a scripting language, along with more advanced programming tools typically found
insystemsdevelopment languages.
 Automaticmemorymanagement
Python automatically allocates and reclaims ("garbage collects") objects when
nolonger used, and most grow and shrink on demand; Python, not you, keeps track of low-
level memorydetails.
 Programming-in-the-largesupport
Finally,forbuildinglargersystems,Pythonincludestoolssuchasmodules,classes, and
exceptions; they allow you to organize systems into components, do OOP,andhandle
eventsgracefully.
 It'sMixable
Python programs can be easily "glued" to components written in other [Link]
technical terms, by employing the Python/C integration APIs, Python programs can beboth
extended by (called to) components written in C or C++, and embedded in (calledby) C or C+
+ programs. That means you can add functionality to the Python system asneededand
usePythonprograms within otherenvironments or systems.
 It'sEasy toUse
For many, Python's combination of rapid turnaround and language simplicitymake
programming more fun than work. To run a Python program, you simply typeitand run it.
There are no intermediate compile and link steps (as when using languagessuch as C or C++).
As with other interpreted languages, Python executes programsimmediately, which makes for
both an interactive programming experience and [Link]
speaking,Pythonprogramsarecompiled(translated)toanintermediateformcalledbytecode,whichis

7
thenrunbytheinterpreter.
 It'sEasy toLearn
Thisbringsustothetopicofthisbook:comparedtootherprogramminglanguages, the core
Python language is amazingly easy to learn. In fact In fact, you canexpect to be coding
significant Python programs in a matter of days (and perhaps in justhours,ifyou'realreadyan
experienced programmer).
 InternetScripting
Python comes with standard Internet utility modules that allow Python programsto
communicate over sockets, extract form information sent to a server-side CGI script,parse
HTML, transfer files by FTP, process XML files, and much more. There are also
[Link],the
HTMLGenandpythondocsystemsgenerateHTMLfilesfromPythonclass-
baseddescriptions,andtheJPythonsystemmentionedaboveprovidesforseamlessPython/
Javaintegration.
 DatabaseProgramming
Python's standard pickle module provides a simple object-persistence system: itallows
programsto easily save and restore entire Pythonobjects tofiles. For moretraditional database
demands, there are Python interfaces to Sybase, Oracle, Informix,ODBC, and more. There is
even a portable SQL database API for Python that runs thesame on a variety of underlying
database systems, and a system namedgadfly thatimplements an SQLdatabaseforPython
programs.
 ImageProcessing,AI,DistributedObjects,Etc.
Python is commonly applied in more domains than can be mentioned here. But
ingeneral, many are just instances of Python's component integration role in action. Byadding
Python as a frontend to libraries of components written in a compiled languagesuch as C,
Python becomes useful for scripting in a variety of domains. For instance,image processing for
Python is implemented as a set of library components implementedin a compiled language
such as C, along with a Python frontend layer on top used toconfigureand launch thecompiled
components.

WhoUsesPythonToday?
1. GooglemakesextensiveuseofPythoninitswebsearchsystems.
2. ThepopularYouTubevideosharingserviceislargelywritteninPython.
3. TheDropboxstorageservicecodesbothitsserveranddesktopclientsoftwareprimarilyinPython.
4. TheRaspberryPisingle-boardcomputerpromotesPythonasitseducationallanguage.
5. ThewidespreadBitTorrentpeer-to-peer filesharingsystembeganitslifeasaPythonprogram.
6. Google‘s App Engine web development framework uses Python as an
applicationlanguage.
7. Maya,apowerfulintegrated3Dmodelingandanimationsystem,providesaPythonscriptingA

8
PI.
8. Intel, Cisco, Hewlett-Packard, Seagate, Qualcomm, and IBM use Python for
hardwaretesting.
9. NASA, Los Alamos, Fermilab, JPL, and others use Python for scientific
programmingtasks.
BytecodeCompilation:
Python first compiles your source code (the statements in your file) into a formatknown as
byte code. Compilation is simply a translation step, and bytecodeisa lower-level, platform
independent representation of your source code. Roughly, Python translateseach of your source
statements into a group of byte code instructions by decomposing theminto individual steps. This
byte code translation is performed to speed execution —byte codecanberunmuch
morequicklythantheoriginalsourcecodestatementsinyourtextfile.

ThePythonVirtualMachine:
Onceyourprogramhasbeencompiledtobytecode(orthebytecodehasbeenloaded
[Link]),itisshippedoffforexecutiontosomethinggenerallyknownasthepythonvirtual
machine(PVM).

ApplicationsofPython:
1. SystemsProgramming
2. GUIs
3. InternetScripting
4. ComponentIntegration
5. DatabaseProgramming
6. RapidPrototyping
7. NumericandScientificProgramming

WhatArePython’sTechnicalStrengths?
1. It‘sObject-OrientedandFunctional
2. It‘sFree
3. It‘sPortable
4. It‘sPowerful
5. It‘sMixable

9
6. It‘s RelativelyEasytoUse
7. It‘s RelativelyEasytoLearn
Identifiers:
All the variables, class, object, functions, lists, dictionaries etc. in Python are together termed as Python
Identifiers. Identifiers are the basis of any Python program. Almost every Python Code uses some or
other identifiers.

Rules for using Python Identifiers:


 An identifier name should not be a keyword.
 An identifier name can begin with a letter or an underscore only.
 An identifier name can contain both numbers and letters along with underscores (A-z, 0-9, and _
).
 An identifier name in Python is case-sensitive i.e, sum and Sum are two different identifier.
Reserved Words:
Here is the list of all the reserved words in Python.
Note - This list may change with different versions of Python. Python 3 has 33 while Python 2 has 30
reserved words. The print was removed from Python 2 keywords and added as a built-in Python
function.

False def if raise


None del import return
True elif in try
and else is while
as except lambda with
assert finally nonlocal yield
break for not continue
class form or global
pass

All the keywords except True, False and None are in lowercase and they must be written as they are.
These cannot be used as variable names, function names, or any other identifiers.
If any of the keywords is used as a variable, then we will get the error message
Display all keywords
We can display the full list of all the keywords in the current version of Python by typing the following
command in the Python interpreter.
import keyword
print ([Link])

10
And to find out the number of reserved words in Python.
print (len([Link]))

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

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

Multiple Assignments to variables:

11
Python allows you to assign a single value to several variables simultaneously.
For example –
a=b=c=1

Here, an integer object is created with the value 1, and all three variables are assigned to the
same memory location. You can also assign multiple objects to multiple variables.
For example –
a, b, c = 1, 2.5, ”mothi”

Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively,
and one string object with the value "john" is assigned to the variable c.

Standard Data Types:

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

Number data types store numeric values. Number objects are created when you assign a
value to them.
Python supports four different numerical types:
 int (signedintegers)
 long (long integers, they can also be represented in octal andhexadecimal)
 float (floating point real values)
 complex (complexnumbers)
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 x
+ yj, where x is the real part and b is the imaginary part of the complex number.

For example:

12
Program:
a=3
b = 2.65
c = 98657412345L
d = 2+5j
print "int is",a print
"float is",b print
"long is",c
print "complex is",d
Output:
int is 3
float is 2.65
long is 98657412345
complex is (2+5j)
Type casting:
Type casting is a method used to change the variables/ values declared in a certain data type into a
different data type to match the operation required to be performed by the code snippet. In python, this
feature can be accomplished by using constructor functions like int( ), string( ), float( ), etc. The type
casting process’s execution can be performed by using two different types of type casting, such as
implicit type casting and explicit type casting

 int( ) - constructs an integer number from an integer literal, a float literal (by removing all
decimals), or a string literal (providing the string represents a whole number).
 float( ) - constructs a float number from an integer literal, a float literal or a string literal
(providing the string represents a float or an integer).
 str( ) - constructs a string from a wide variety of data types, including strings, integer literals and
float literals.

Python has two types of type conversion:


1. Implicit Type casting
Implicit type conversion is performed automatically by the interpreter, without user intervention.
Python automatically converts one data type to another data type. This process doesn’t need any user
involvement Python promotes the conversion of lower data type, for example, integer to higher data
type says float to avoid data loss. This type of conversion or type casting is called UpCasting.
Syntax:
(Required datatype)(Expression)

(Desired type)

x = int(1)
y = int(2.8)

13
z = int("3")
print(x)
print(y)
print(z)
output:
1
2
3
2. Explicit Type casting
In Explicit Type conversion, the user or programmer converts the data type of an object to the required
data type. In Python we use predefined functions like int( ), float( ), str( ), bool( ) etc to perform explicit
type conversion.
Syntax:
(Required datatype)(Expression)

(Desired type)
x = float(1)
y = float(2.8)
z = float("3")
w = float("4.2")
print(x) # x will be 1.0
print(y) # y will be 2.8
print(z) # z will be 3.0
print(w) # w will be 4.2

Immutability:
Immutable objects in Python can be defined as objects that do not change their values and attributes
over time. These objects become permanent once created and initialized, and they form a critical part of
data structures used in Python.
Python is used in numbers, tuples, strings, frozen sets, and user-defined classes with
someexceptions. They cannot change, and their values and it remains permanent once they are
initialized and hence called immutable.

Python Immutable Data Types:

Class Explanation Immutable or not


Bool Boolean value Immutable
Int Integer value (magnitude can be arbitrary) Immutable
Float Floating point number Immutable
List Sequence of objects of mutable nature Mutable

14
Tuple Sequence of objects of immutable nature Immutable
Str Character /string Immutable
Set set of distinct objects that are of Unordered nature Mutable
Frozenset Set class of immutable nature Immutable
Dict Dictionary or associative mapping Mutable

Demonstration:

Experiment-1: Install Anaconda open-source framework for python.


Experiment 1: Install Anaconda open-source framework for python.
Step1: Anaconda | The World's Most Popular Data Science Platform ([Link] )
Step2: select the download option
Step3: choose the operating system

Download the latest version of python ide 3.10


We can download installer of Anaconda3-2022.05-Windows-x86_64 executable file
Step4: double click one Anaconda3-2022.05-Windows-x86_64 installer ide or run as administrator.

Step5: follow the image

15
Click here on the next button

Click on I agree button

16
Select just me and click on next button
Note: if you select all users then it will use for admin privileges- a simple group of member work
together.

Select the location of path to install in our operating system after click on next button

17
Select the path environment variable as well as register anaconda as my default python
Click on install button
Note: if you select only the add path option then we need to add the default storage path through
the system variable.

It can show the installing process and it will take 1 to 2 minutes of time to install
After that click on the next button

18
After that click on the next button

19
Click on the finish Button.

Step6: open programme file and select anaconda navigator


RunningPython:
a. RunningPythonInterpreter:
Python comes with an interactive interpreter. When you type python in your shell
orcommand prompt, the python interpreter becomes active with a >>> prompt and waits
foryourcommands.

Now you can type any valid python expression at the prompt. Python reads the
typedexpression,evaluates it and prints the result.

20
b. RunningPythonScripts in command prompt

To check the version of python

21
To run the python IDE

Experiment-2: Write a program to display ‘Hello World’.


Experiment-2: Write a program to display ‘Hello World’.
3.
To print Hello world message using python prompt

22
Experimentation:
Experiment 3: Explore various IDEs for python program development.
Experiment 3: Explore various IDEs for python program development.
4.

The frame of anaconda navigator. After successful installation.

Experiment-4: The volume of a sphere with radius r is 4/3 πr 3. Write a Python


program to find the volume of a sphere with radius 5?
5.
Step1: take the variable radius as r with input value
Step2: apply the sphere formula directly and print the volume of sphere with radius.
Step3: expected output 523.33.

23
Lab 2:
(Arithmetic Operators, Relational Operators, Logical operators, Bitwise operators,
Assignment operators, Special operators)

Python Operators:
The operator can be defined as a symbol which is responsible for a particular operation between two
operands. Operators are the pillars of a program on which the logic is built in a particular programming
language. Python provides a variety of operators described as follows.
 Arithmetic operators
 Comparison operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators
 Ternary operator
Arithmetic operators
Arithmetic operators are used to perform arithmetic operations between two operands. It includes +
(addition), - (subtraction), *(multiplication), /(divide), %(reminder), //(floor division), and exponent
(**).
Consider the following table for a detailed explanation of arithmetic operators.
Operator Description
Operator Description
+ (Addition) It is used to add two operands. For example, if a = 20, b = 10 =>a+b = 30
It is used to subtract the second operand from the first operand. If the first operand is
- (Subtraction) less than the second operand, the value result negative. For example, if a = 20, b = 10
=>a ? b = 10
It returns the quotient after dividing the first operand by the second operand. For
/ (divide)
example, if a = 20, b = 10 => a/b = 2
* It is used to multiply one operand with the other. For example, if a = 20, b = 10 => a
(Multiplication) * b = 200
It returns the reminder after dividing the first operand by the second operand. For
% (reminder)
example, if a = 20, b = 10 =>a%b = 0
It is an exponent operator represented as it calculates the first operand power to
** (Exponent)
second operand.
// (Floor
It gives the floor value of the quotient produced by dividing the two operands.
division)

24
Example
Assume variable a holds 21 and variable b holds 10, then −
a = 21
b = 10
c=0
c=a+b
print("a+b - Value of c is ", c)
c=a-b
print("a-b - Value of c is ", c)
c=a*b
print("a*b - Value of c is ", c)
c=a/b
print("a/b - Value of c is ", c)
c=a%b
print("a%b - Value of c is ", c)
a=2
b=3
c = a**b
print("a**b - Value of c is ", c)
a = 10
b=5
c = a//b
print("a//b - Value of c is ", c)
When you execute the above program, it produces the following result −
a+b - Value of c is 31
a-b - Value of c is 11
a*b - Value of c is 210
a/b - Value of c is 2.1
a%b - Value of c is 1
a**b - Value of c is 8
a//b - Value of c is 2

Comparison (or) relation 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.

25
!= 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
Assume variable a holds 10 and variable b holds 20, then −
a = 21
b = 10
c=0
if ( a == b ):
print("a == b - a is equal to b")
else:
print("Line 1 - a is not equal to b")
if ( a != b ):
print("a != b - a is not equal to b")
else:
print("Line 2 - a is equal to b")
if ( a< b ):
print("a < b - a is less than b")
else:
print("Line 4 - a is not less than b")
if ( a> b ):
print("a > b - a is greater than b")
else:
print("Line 5 - a is not greater than b")
a = 5;
b = 20;
if ( a<= b ):
print("a <= b - a is either less than or equal to b")
else:
print("Line 6 - a is neither less than nor equal to b")
if ( b>= a ):
print("b >=a - b is either greater than or equal to b")

26
else:
print("Line 7 - b is neither greater than nor equal to b")
When you execute the above program it produces the following result −
Line 1 - a is not equal to b
a != b - a is not equal to b
Line 4 - a is not less than b
a > b - a is greater than b
a <= b - a is either less than or equal to b
b >=a - b is either greater than or equal to b

Python assignment operators


The assignment operators are used to assign the value of the right expression to the left operand. The
assignment operators are described in the following table.

Operator Description
= It assigns the the value of the right expression to the left operand.
It increases the value of the left operand by the value of the right operand and assign the
+= modified value back to left operand. For example, if a = 10, b = 20 => a+ = b will be equal to
a = a+ b and therefore, a = 30.
It decreases the value of the left operand by the value of the right operand and assign the
-= modified value back to left operand. For example, if a = 20, b = 10 => a- = b will be equal to
a = a- b and therefore, a = 10.
It multiplies the value of the left operand by the value of the right operand and assign the
*= modified value back to left operand. For example, if a = 10, b = 20 => a* = b will be equal to
a = a* b and therefore, a = 200.
It divides the value of the left operand by the value of the right operand and assign the
%= reminder back to left operand. For example, if a = 20, b = 10 => a % = b will be equal to a =
a % b and therefore, a = 0.
**= a**=b will be equal to a=a**b, for example, if a = 4, a b =2, **=b will assign 4**2 = 16 to a.
//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign 4//3 = 1 to a.
Example
Assume variable a holds 10 and variable b holds 20, then −
a=9
b=5
c=0
c=a+b
print("Line 1 - Value of c is ", c)
c += a

27
print("Line 2 - Value of c is ", c)
c *= a
print("Line 3 - Value of c is ", c)
c /= a
print("Line 4 - Value of c is ", c)
c = 10
c %= a
print("Line 5 - Value of c is ", c)
a,c=2,3
c **= a
print("Line 6 - Value of c is ", c)
c //= a
print("Line 7 - Value of c is ", c)
When you execute the above program, it produces the following result −
Line 1 - Value of c is 14
Line 2 - Value of c is 23
Line 3 - Value of c is 207
Line 4 - Value of c is 23.0
Line 5 - Value of c is 1
Line 6 - Value of c is 9
Line 7 - Value of c is 4

Bitwise operator
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 result.
and) Otherwise, 0 is copied.
| (binary or) The resulting bit will be 0 if both the bits are zero otherwise the resulting bit will be 1.
The resulting bit will be 1 if both the bits are different otherwise the resulting bit will be
^ (binary xor)
0.
It calculates the negation of each bit of the operand, i.e., if the bit is 0, the resulting bit
~ (negation)
will be 1 and vice versa.
<< (left shift) The left operand value is moved left by the number of bits present in the right operand.
>> (right
The left operand is moved right by the number of bits present in the right operand.
shift)

28
Example
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c=0
c = a &b; # 12 = 0000 1100
print("Line 1 - Value of c is ", c)
c = a | b; # 61 = 0011 1101
print("Line 2 - Value of c is ", c)
c = a ^ b; # 49 = 0011 0001
print("Line 3 - Value of c is ", c)
c = ~a; # -61 = 1100 0011
print("Line 4 - Value of c is ", c)
c = a <<2; # 240 = 1111 0000
print("Line 5 - Value of c is ", c)

29
c = a >>2; # 15 = 0000 1111
print("Line 6 - Value of c is ", c)
When you execute the above program it produces the following result −
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15

Logical Operators
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 : AND
x=5
print(x > 3 and x < 10)
# returns True because 5 is greater than 3 AND 5 is less than 10
Example: OR

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

Membership Operators
Python membership operators are used to check the membership of value inside a data structure. If the
value is present in the data structure, then the resulting value is true otherwise it returns false.

Operator Description
It is evaluated to be true if the first operand is found in the second operand (list, tuple, or
In
dictionary).
It is evaluated to be true if the first operand is not found in the second operand (list, tuple, or
not in
dictionary).

Example:

x = ["apple", "banana"]
print("banana" in x)
# returns True because a sequence with the value "banana" is in the list
print("pineapple" not in x)
# returns True because a sequence with the value "pineapple" is not in the list

Identity Operators
Identity operators compare the memory locations of two objects.
Operator Description
Is It is evaluated to be true if the reference present at both sides point to the same object.
is not It is evaluated to be true if the reference present at both side do not point to the same object.
.

Example:
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is z)

31
# returns True because z is the same object as x
print(x is y)
# returns False because x is not the same object as y, even if they have threw same content(because list
is mutable).
print(x == y)
# to demonstrate the difference between "is" and "==": this comparison returns True because x is equal
to y
Example :
print(x is not z)
# returns False because z is the same object as x
print(x is not y)
# returns True because x is not the same object as y, even if they have the same content
print(x != y)
# to demonstrate the difference between "is not" and "!=": this comparison returns False because x is
equal to y

Python Ternary operator


Python Ternary operator is used to select one of the two values based on a condition. It is a
miniature of if-else statement that assigns one of the two values to a variable.

The syntax of Python Ternary Operator is:


[statement_1] if [expression] else [statement_2]
statement_1 is selected if expression evaluates to True. Else if the expression evaluates to False,
statement_2 is selected.
You can either provide a value, variable or statement for the statement_1 and statement_2.

The ternary operator in the following program selects a or b based on the condition a>b evaluating
to True or False respectively.
Program:
a, b = 2, 5
#get maximum of a, b
max = a if a > b else b
print(max)
Output:
5
Demonstration
Experiment-1; Write a python program to find minimum and maximum of given three
numbers.

Program:

32
a=int(input("enter a value"))
b=int(input("enter b value"))
c=int(input("enter c value"))
max = a if a > b and a>c else b if b>c else c
print("Maximumbernumber",max)
min = a if a < b and a<c else b if b<c else c
print("Minimum number",min)
Output:

Experiment-2: Suppose the cover price of a book is $24.95, but bookstores get a 40% discount.
Shipping costs $3 for the first copy and 75 cents for each additional copy. Write a python
program to compute the total wholesale cost for 60 copies?

Program:
bookPrice = 24.95
discount = .60
shippingPriceRest = .75
shippingPriceFirst = 3.00
totalUnits = 60
totalCostBeforeShipping = (bookPrice * discount) * totalUnits
shipping = (shippingPriceRest * (totalUnits-1)) + shippingPriceFirst
result = totalCostBeforeShipping + shipping
print ('The total price for 60 books including shipping and discount is: ')
print ('Total price of the books is: ' + str(totalCostBeforeShipping))
print ('Total Shipping is: ' + str(shipping))

33
print ('The Total price is: ' + str(result))

output:

Experimentation
Experiment-3: Write a Python Program to Find the Square Root of a number with out using
sqrt function.

Algorithm:
Step-1:Read n value
Step-2:Calculate n**0.5 and storethe result in the resultvariable
For example, to find the square root of 49 use the following code: 49**0.5. Here 0.5 is the power
and 49 is the number.
Step-3:print the result in the output

Experiment-4: Python Program to Convert Celsius To Fahrenheit.


Given the temperature in degree Celsius. the task is to convert the value in the Fahrenheit
scale and display it.

34
Algorithm:
Step-1: Read values C, F
Step-2: Apply formula is used to convert a temperature given in Celcius to Fahrenheit.
F = (9/5)*C + 32
Step-3:print the result

Experiment-5: Python program to find the maximum of two numbers using ternary operator

Algorithm:
Step-1:Read the values a,b
Step-2:get maximum of a, b
max = a if a > b else b
Step-3:print max value

35
LAB 3:

Mathematical Functions, Input and Output statements, Command Line


Arguments, String Functions

Mathematical Functions:

ThemathModule:
Thismoduleprovides accesstothe mathematicalfunctionsdefined bytheCstandard.

These functions cannot be used with complex numbers; use the functions of the same name fromthe
cmath module if you require support for complex numbers. The distinction between
functionswhich support complex numbers and those which don‘t is made since most users do not
want tolearn quite as much mathematics as required to understand complex numbers. Receiving
anexception instead of a complex result allows earlier detection of the unexpected complex
numberused as a parameter, so that the programmer can determine how and why it was generated
in thefirstplace.

The following functions are provided by this module. Except when explicitly noted otherwise,
allreturnvaluesare floats.

[Link](x)
Returntheceilingofx,the smallestintegergreaterthan [Link] x is notafloat, [Link]( ),
which should return anIntegral value.

[Link](x,y)
Return a float with the magnitude (absolute value) of x but the sign of y. On platforms
thatsupportsigned zeros,copysign(1.0,-0.0) returns-1.0.

[Link](x)
Returntheabsolute value ofx.

[Link](x)
Returnx [Link].

[Link](x)
Returnthefloorofx,[Link],[Link]( ),which
should return anIntegral value.

[Link](x,y)
Return fmod(x, y), as defined by the platform C library. Note that the Python expression x % ymay
not return the same result. The intent of the C standard is that fmod(x, y) be exactly(mathematically;
to infinite precision) equal to x - n*y for some integer n such that the result

36
hasthesamesignasxandmagnitudelessthanabs(y).Python‘sx%yreturnsaresultwiththesignof y instead,
and may not be exactly computable for float arguments. For example, fmod(-1e-100, 1e100) is -1e-
100, but the result of Python‘s -1e-100 % 1e100 is 1e100-1e-100, whichcannot be represented
exactly as a float, and rounds to the surprising 1e100. For this reason,function fmod( ) isgenerally
preferred when working with floats,while Python‘s x%y ispreferredwhen workingwith integers.

[Link](x)
Return themantissaandexponentofxasthe pair(m, e).misafloatandeisanintegersuchthat
x= m*2**[Link],returns(0.0,0),otherwise0.5<=abs(m)<[Link]
―pick apart‖the internal representation ofa float inaportable way.

[Link](iterable)
[Link]
intermediate partial sums:

>>>
>>>sum([.1, .1, .1, .1, .1,.1, .1, .1, .1, .1])
0.9999999999999999
>>>fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
1.0
The algorithm‘s accuracy depends on IEEE-754 arithmetic guarantees and the typical case wherethe
rounding mode is half-even. On some non-Windows builds, the underlying C library
usesextendedprecisionadditionandmayoccasionallydouble-roundanintermediatesumcausingittobe off
in its least significant bit.

For further discussionand two alternative approaches,see the ASPN cookbook recipes
foraccuratefloatingpoint summation.

[Link](a,b)
Return the greatest common divisor of the integers a and b. If either a or b is nonzero, then
thevalueof gcd(a,b) isthe largestpositive integerthat dividesboth aand [Link](0,0)returns 0.

Newinversion3.10.

[Link](a,b,*,rel_tol=1e-09,abs_tol=0.0)
ReturnTrueifthevalues aand bareclose toeachotherandFalseotherwise.

Whether or not two values are considered close is determined according to given absolute
andrelativetolerances.
rel_tol is the relative tolerance – it is the maximum allowed difference between a and b, relativeto the
larger absolute value of a or b. For example, to set a tolerance of 5%, pass rel_tol=[Link]
default tolerance is 1e-09, which assures that the two values are the same within about
9decimaldigits. rel_tol must be greater than zero.

37
abs_tol is the minimum absolute tolerance – useful for comparisons near zero. abs_tol must be
atleastzero.

If noerrorsoccur,theresultwillbe:abs(a-b)<= max(rel_tol*max(abs(a),abs(b)), abs_tol).


Input,Processing,andOutput:
Howdoprogrammerssolveproblems?Theproblemisdividedintoinput,processing,andoutput.

Thefirst problemI'd like to solve isgettingPythonto ask [Link] 3.x,you canget


inputfrom theuserwiththe input( )function.
Let'sjustcallinput( ),and seewhathappens:

>>>input()Hell
o'Hello'

Icalledinput( ) fromthe Pythonshell,andtheinterpreterwaitedformetotypesomethingandthenpress'Enter'.


Theinterpreter thenprinted outmyinput.

Let's refinethatabit.
Problem:Get Pythontosay Hello
Weknow howto usethefunction print( )to printvariables:

x=5print(x)OU
TPUT:5

38
Canweusethattoprintourmessage?

message=Hello
print(message)OU
TPUT:

That didn't work too [Link] is our message?Python thinks that Hello is a
[Link] isastring. Pythonwill understandthatit isastringifwe wrap
itinquotes.
message='Hello'
print(messa)

OUTPUT:
Hello

[Link], andstillwork?What happens if wetryto print


thestringdirectly?

print('Hello')

OUTPUT:Hello

DisplayingOutputwiththePrintFunction:
The print( ) function prints the given object to the standard output device (screen) or tothetext stream
file.

Thefullsyntax ofprint( )is:


print(*objects,sep='', end='\n', file=[Link],flush=False)

print( )Parameters
objects-object to the printed.* indicates that theremaybemorethan oneobject
sep-objectsareseparated [Link] value:''
end -end isprinted atlast
file-mustbeanobjectwithwrite(string)[Link]
omittedit,[Link] on the screen.
flush- IfTrue,thestreamisforciblyflushed. Defaultvalue:False
Note:sep,end, fileandflusharekeywordarguments. Ifyou

39
wanttousesepargument,youhaveto use:
print(*objects,sep='separator')not
print(*objects,'separator')

Example1:Howprint( )worksinPython?
print("Pythonisfun.")a=5
#Twoobjectsarepassedprint("a =", a)
b =a
#Threeobjectsarepassedprint('a=', a,'=b')

Whenyouruntheprogram,theoutputwill be:

a=5 =b

Inthe aboveprogram,onlyobjectsparameteris passedtoprint( )function(in allthreeprintstatements).


Hence,
 ''separatoris used. Notice,the spacebetween twoobjects in output.
 endparameter '\
n'(newlinecharacter)[Link],eachprintstatementdisplaystheoutputinthene
w line.
 fileis [Link]. Theoutputis printed on thescreen.
 flushis [Link] isnot forciblyflushed.

Example2:print( )withseparatorandendparameters
a=5
print("a =", a, sep='00000', end='\n\n\n')print("a =", a, sep='0',end='')

Whenyouruntheprogram,theoutputwillbe:
a=000005
a=05

Wepassedthesepandendparametersinthe aboveprogram.

Comments:
 InPython,therearetwowaystoannotateyour code.
 The first is to include comments that detail or indicate what a section of code – orsnippet–
does.
 Thesecondmakesuse ofmulti-linecommentsor paragraphsthatserveasdocumentationfor
othersreadingyourcode.
 Thinkofthefirsttypeasacommentforyourself, andthesecondasacomment forothers. There is not
right or wrong way to add a comment, however. You can dowhatever feels comfortable.
Single-linecomments are created simplybybeginningalinewith thehash (#)character,and
theyareautomaticallyterminatedbytheend ofline.

40
Python Strings:

Strings in Python are identified as a contiguous set of characters represented in the


quotation marks. Python allows for either pairs of single or double quotes. Subsets of strings can
be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the
string and working their way from -1 at theend.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition
operator. For example:
Program:
str ="WELCOME"
print str # Prints complete string
print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 5th print
str[2:] # Prints string starting from 3rd character print str * 2
# Prints string two times
print str + "CSE" # Prints concatenated string
Output:
WELCOME W
LCO LCOME
WELCOMEWELCOME
WELCOMECSE
Built-in String methods for Strings:

SNO Method Name Description


1 capitalize( ) Capitalizes first letter of string.
Returns a space-padded string with the original
2 center(width, fillchar)
string centered to a total of width columns.
Counts how many times str occurs in string or in a
count(str, beg=
3 substring of string if starting index beg and ending
0,end=len(string))
index end are given.
Decodes the string using the codec registered for
decode(encoding='UTF-
4 encoding. Encoding defaults to the default string
8',errors='strict')
encoding.
Returns encoded string version of string; on error,
encode(encoding='UTF-
5 default is to raise a Value Error unless errors is
8',errors='strict')
given with 'ignore' or 'replace'.
Determines if string or a substring of string (if starting
6 endswith(suffix, beg=0, index beg and ending index end are given) ends with
end=len(string)) suffix; returns true if so and false
otherwise.
Expands tabs in string to multiple spaces; defaults
7 expandtabs(tabsize=8)
to 8 spaces per tab if tabsize not provided.

41
Determine if str occurs in string or in a substring of
find(str, beg=0
8 string if starting index beg and ending index end are
end=len(string))
given returns index if found and -1 otherwise.
index(str, beg=0, Same as find( ), but raises an exception if str not
9
end=len(string)) found.
Returns true if string has at least 1 character and all
10 isalnum( )
characters are alphanumeric and false otherwise.
Returns true if string has at least 1 character and all
11 isalpha( )
characters are alphabetic and false otherwise.
Returns true if string contains only digits and false
12 isdigit( )
otherwise.
Returns true if string has at least 1 cased character and
13 islower( ) all cased characters are in lowercase and false
otherwise.
Returns true if a unicode string contains only
14 isnumeric( )
numeric characters and false otherwise.
Returns true if string contains only whitespace
15 isspace( )
characters and false otherwise.
Returns true if string is properly "titlecased" and
16 istitle( )
false otherwise.
Returns true if string has at least one cased character
17 isupper( ) and all cased characters are in uppercase
and false otherwise.
Merges (concatenates) the string representations of
18 join(seq) elements in sequence seq into a string, with
separator string.
19 len(string) Returns the length of the string.
Returns a space-padded string with theoriginal
20 ljust(width[, fillchar])
string left-justified to a total of widthcolumns.
Converts all uppercase letters in string to
21 lower( )
lowercase.
22 lstrip( ) Removes all leading whitespace in string.
Returns a translation table to be used in translates
23 maketrans( )
function.
Returns the max alphabetical character from the
24 max(str)
string str.
Returns min alphabetical character from the string
25 min(str)
str.
Replaces all occurrences of old in string with new
26 replace(old, new [, max])
or at most max occurrences if max given.
rfind(str,
27 Same as find( ), but search backwards in string.
beg=0,end=len(string))
rindex( str, beg=0,
28 Same as index( ), but search backwards in string.
end=len(string))

42
Returns a space-padded string with the original
29 rjust(width,[, fillchar])
string right-justified to a total of width columns.
30 rstrip( ) Removes all trailing whitespace of string.
Splits string according to delimiter str (space if not
split(str="",
31 provided) and returns list of substrings; split into at
num=[Link](str))
most num substrings if given.
splitlines ( Splits string at all (or num) NEWLINEs and returns
32
num=[Link]('\n')) a list of each line with NEWLINEs removed.
Determines if string or a substring of string (if starting
33 startswith(str, index beg and ending index end are given) starts with
beg=0,end=len(string)) substring str; returns true if so and false
otherwise.
34 strip([chars]) Performs both lstrip( ) and rstrip( ) on string.
35 swapcase( ) Inverts case for all letters in string.
Returns "titlecased" version of string, that is, all words
36 title( ) begin with uppercase and the rest are
lowercase.
translate(table, Translates string according to translation table
37
deletechars="") str(256 chars), removing those in the del string.
38 upper( ) Converts lowercase letters in string to uppercase.
Returns original string leftpadded with zeros to a
39 zfill (width) total of width characters; intended for numbers,
zfill( ) retains any sign given (less one zero).
Returns true if a unicode string contains only
40 isdecimal( )
decimal characters and false otherwise.

43
Q) Write a python program to print the capitalize functions using string
Example:

Python Boolean:

44
Booleans are identified by True or False.
Example:
Program:
a = True b = False print a print b
Output:
True False

Demonastration:

Experiment-1: Write a Python program to find area of circle.


Program:
r = float(input("enter the area="))
area=3.14*r*r
print("area of circle=", area)
output:
enter the area=5
area of circle= 78.5

Experiment-2: Write a program to read Employee data from the keyboard and print that data.
Program:
Name=input(“enter your name”)
Eid=input(“enter your empid”)
DOJ=input(“enter your Date of joining”)
address=input(“enter your address”)
print(Name)
print(Eid)
print(DOJ)
print(address)
output:

enter your name=Rishikesh


enter your empid=858
enter your Date of joining=06/07/2017
enter your address=Flat No 156, Road No 8, Hastinapuram
Rishikesh
858
06/07/2017
Flat No 156, Road No 8, Hastinapuram

Experimentation:

45
Experiment-3:
Experiment-3:Write
Writeaaprogram
programtoto read
read 33 float
float numbers
numbers from
from the
the keyboard with ,, separator
keyboard with separator and
and
print
print their [Link] Statements their sum.

Step1: take the 3 different input keyword with floating point


Step2: add these three input values and store in the sum variable
Step3: print the sum

Experiment-4: Write a Program to display Command Line Arguments.


Step1: write any one programme or above program and mention the individual comment lines

Lab 4:

Flow Control Statements-Conditional Statements, Transfer Statements, Iterative


Statements 46
Week 4.
(Flow Control Statements-Conditional Statements, Transfer Statements, Iterative Statements)

Flow control describe the order in which statements will be executed at runtime.
These are of 3 types :
Conditional Statements/selection statements
Iterative Statements
Transfer Statements

Conditional Statements :
If we have to write a program in which we want to execute a code on behalf of conditions then we
come for Conditional Statements.

We have 3 types of Conditional Statements :

if:
if-else:
Nested if:
elif:

Python If-else statements

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
The if statement is used to test a specific condition. If the condition is true, a block of code
If Statement
(if-block) will be executed.
The if-else statement is similar to if statement except the fact that, it also provides the
If - else
block of the code for the false case of the condition to be checked. If the condition
Statement
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 if statement.
Statement

Indentation in Python

47
For the ease of programming and to achieve simplicity, python doesn't allow the use of parentheses for
the block level code. In Python, indentation is used to declare a block. If two statements are at the same
indentation level, then they are the part of the same block.
Generally, four spaces are given to indent the statements which are a typical amount of indentation in
python.
Indentation is the most used part of the python language since it declares the block of code. All the
statements of one block are intended at the same level indentation. We will see how the actual
indentation takes place in decision making and other stuff in python.

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.


if expression:
statement

Example 1
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? "));

48
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? "))

49
if age>=18:
print("You are eligible to vote !!")
else:
print("Sorry! you have to wait !!")

Output:
Enter your age? 90
You are eligible to vote !!
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

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

50
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
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? 44
You scored grade B ...

51
Python Loops
The flow of the programs written in any programming language is sequential by default. Sometimes we
may need to alter the flow of the program. The execution of a specific code may need to be repeated
several numbers of times.
For this purpose, The programming languages provide various types of loops which are capable of
repeating some specific code several numbers of times. Consider the following diagram to understand
the working of a loop statement.

Why we use loops in python?


The looping simplifies the complex problems into the easy ones. It enables us to alter the flow of the
program so that instead of writing the same code again and again, we can repeat the same code for a
finite number of times. For example, if we need to print the first 10 natural numbers then, instead of
using the print statement 10 times, we can print inside a loop which runs up to 10 iterations.

Advantages of loops
There are the following advantages of loops in Python.
It provides code re-usability.
Using loops, we do not need to write the same code again and again.
Using loops, we can traverse over the elements of data structures (array or linked lists).
There are the following loop statements in Python.
Loop
Description
Statement
The for loop is used in the case where we need to execute some part of the code until the
for loop given condition is satisfied. The for loop is also called as a per-tested loop. It is better to
use for loop if the number of iteration is known in advance.
The while loop is to be used in the scenario where we don't know the number of iterations
while loop in advance. The block of statements is executed in the while loop until the condition
specified in the while loop is satisfied. It is also called a pre-tested loop.
The do-while loop continues until a given condition satisfies. It is also called post tested
do-while
loop. It is used when it is necessary to execute the loop at least once (mostly menu driven
loop
programs).

Python for loop

52
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,n):
print(i,end = ' ')
Output:
Enter the number up to which you want to print the natural numbers? 10
0123456789

Python for loop 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

53
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 1

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 1

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.
Example 2

54
for i in range(0,5):
print(i)
break
else: print("for loop is exhausted")
print("The loop is broken due to break statement...came out of loop")

In the above example, the loop is broken due to break statement therefore the else statement will not be
executed. The statement present immediate next to else block will be executed.
Output:
0
The loop is broken due to break statement...came out of loop
Python while loop

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

55
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 1
while (1):
print("Hi! we are inside the infinite while loop");
Output:
Hi! we are inside the infinite while loop
(infinite times)

Example:

56
var = 1
while var != 2:
i = int(input("Enter the number?"))
print ("Entered value is %d"%(i))

Output:
Enter the number?102
Entered value is 102
Enter the number?102
Entered value is 102
Enter the number?103
Entered value is 103
Enter the number?103
(infinite loop)

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
Example 2
i=1;
while i<=5:
print(i)
i=i+1;
if(i==3):
break;
else:print("The while loop exhausted");

Output:

57
1
2
Transfer Statements :
These are the statements used to Continue or break the Execution of the loop while giving some
condition.

These are of 2 types :

break
continue
pass

Python 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 1
list =[1,2,3,4]
count = 1
for i in list:
if i == 4:
print("item matched")
count = count + 1;
break
print("found at",count,"location")

Output:
item matched
found at 2 location

Example 2
str = "python"
for i in str:
if i == 'o':
break

58
print(i);

Output:
p
y
t
h

Example 3: break statement with while loop


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

Python 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 1
i = 0;
while i!=10:
print("%d"%i);
continue;
i=i+1;

Output:
infinite loop

Example 2
i=1; #initializing a local variable

59
#starting a loop from 1 to 10
for i in range(1,11):
if i==5:
continue;
print("%d"%i);

Output:
1
2
3
4
6
7
8
9
10

Pass Statement
In Python, pass keyword is used to execute nothing; it means, when we don't want to execute code, the
pass can be used to execute empty. It is same as the name refers to. It just makes the control to pass by
without executing any code. If we want to bypass any code pass statement can be used.

Python Pass Syntax


pass
Python Pass Example
for i in [1,2,3,4,5]:
if i==3:
pass
print("Pass when value is",i)
print(i)

Output:
1
2
Pass when value is 3
3
4
5

Example
list = [1,2,3,4,5]
flag = 0
for i in list:
print("Current element:",i,end=" ");
if i==3:

60
pass;
print("\nWe are inside pass block\n");
flag = 1;
if flag==1:
print("\nCame out of pass\n");
flag=0;
Output:
Current element: 1 Current element: 2 Current element: 3
We are inside pass block

Came out of pass


Current element: 4 Current element: 5

Demonstration

Experiment-1. Write a Python program to take a single digit number from the key board and
print is value in English word?.

Program:
n=int(input("Enter the digit form 0 to 9 : "))
print("Entered Digit is : ",end='')
if n==0:
print("Zero")
elif n==1:
print("One")
elif n==2:
print("Two")
elif n==3:
print("Three")
elif n==4:
print("Four")
elif n==5:
print("Five")
elif n==6:
print("Six")
elif n==7:
print("Seven")
elif n==8:
print("Eight")
elif n==9:
print("Nine")
else:
print("Not a Digit")
Output:

61
Experiment-2. Write a Python Program to check whether an n-digit integer is an Armstrong
number or not.

Program:
num = int(input("Enter a number: "))
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")
output:

62
Experimentation
Experiment-3. Write a Python program to display *'s in pyramid style(also known as
equivalent triangle).

Approach:
print pyramid star pattern

Before you read further have a close look at the above pattern. The pattern consists of N (for this case
5) rows. Each row contain exactly 2 * N - 1 stars. In addition to stars the pattern has leading spaces.
Each row contain N - i spaces (where i is current row number). To count total spaces per row point your
mouse over the above pattern.

Step by step descriptive logic to print Pyramid star pattern.


Step-1:start
Step 2:Input number of rows to print from user. Store it in a variable say rows.
Step:3:To iterate through rows, run an outer loop from 1 to rows. The loop structure should look like
for(i=1; i<=rows; i++).

63
Step-4:To print spaces, run an inner loop from i to rows - 1. The loop structure should look like for(j=i;
j<rows; j++). Inside this loop print single space.
Note: Iterating from 1 to N - i or i to rows - 1 both are equal.

Step-5:To print star, run another inner loop from 1 to 2 * i - 1. The loop structure should look like
for(j=1; j<=(2*i - 1); j++). Inside this loop print star.
Step-6:After printing stars for current row, move to next line i.e. print new line.
Step-7:Stop

Experiment-4. Write a Python Program to Display the multiplication Table:

Approach:
# Multiplication table (from 1 to 10) in Python
Step-1:#start
Step-2:# To take input from the user
Step-3:# Iterate 10 times from i = 1 to 10
Step 4:#print the result in this format print (num, 'x', i, '=', num*i)
Step-5:#stop

64
Lab 5

Functions-Built in functions, user defined functions, Parameters, return statement, returning


multiple values from function, type of arguments, Types of variables-global, local. Recursive
functions, Lambda functions, filter function, reduce function, Function aliasing, Function
decorators, Generators

Built-in Functions in Python


One of the reasons for which Python is preferred over the other languages is the huge collection of
built-in functions. You would have come across some of these like print( ), int( ), etc.
In this article, we will discuss these built-in functions in Python with examples. So, let us begin.
Introduction to Built-in Functions in Python
Functions are the set of lines of code that work and behave together under a name. Built-in functions
are the ones whose functionality is predefined.
These get stored in the interpreter and come into action when they are called. These can be accessed
from any part of the program. The Python 3.6 version has 69 built-in functions and these are:
Table of built-in functions in Python:
abs( ) enumerate( ) iter( ) reversed( ) dict( ) int( )
all( ) eval( ) len( ) round( ) dir( ) isinstance( )
any( ) exec( ) list( ) set( ) dir( ) isinstance( )
ascii( ) filter( ) locals( ) setattr( ) divmod( ) issubclass( )
bin( ) float( ) map( ) slice( ) property( )
bool( ) format( ) max( ) sorted( ) range( )

breakpoint( ) frozenset( ) memoryview( ) staticmethod( ) repr( )

bytearray( ) getattr( ) min( ) str( )


bytes( ) globals( ) next( ) sum( )
callable( ) hasattr( ) object( ) super( )
chr( ) hash( ) oct( ) tuple( )

classmethod( ) help( ) open( ) type( )

compile( ) hex( ) ord( ) vars( )


complex( ) id( ) pow( ) zip( )
delattr( ) input( ) print( ) __import__( )

abs( )
This function takes the input of a number and gives the absolute value of it. That is, if the number is
positive it returns the same number and if the number is negative it gives the positive part of it. For
example,
Example of abs( ) function:
abs(4)
abs(-5.6)
Output:
4
5.6

65
all( )
This is a function that takes a sequence as an input and checks the elements. If any of the elements is
empty/ zero/ False, then it gives the output as False. Or else, it gives True. For example,
Example of all( ) function:
all([1,'t',7.9,[4,5]])
all({4,'','y'})
Output:
True
False

any( )
The function any( ) also takes a sequence as an input and checks its elements. It gives False only if all
the values of the container are empty/ zero/ False. Even if there is one nonzero/nonempty True value, it
returns True. For example,
Example of any( ) function:
any(('t',7,9,'',False))
any(['',False,0])
Output:
True
False

ascii( )
This function returns the printable form of any object passed as an argument. If we give any non-ascii
character, then the interpreter adds a backslash(\) and escapes it using another backslash(\). For
example,
Example of ascii( ) function:
ascii('r')
ascii('\t')
ascii('Hello \n world!')
ascii([3,'/'])
Output:
“‘r'”
“‘\\t'”
“‘Hello \\n world!'”
“[3, ‘/’]”

user-defined functions:
Functions that we define ourselves to do certain specific task are referred as user-defined functions. The
way in which we define and call functions in Python are already discussed.
Functions that readily come with Python are called built-in functions. If we use functions written by
others in the form of library, it can be termed as library functions.
All the other functions that we write on our own fall under user-defined functions. So, our user-defined
function could be a library function to someone else.
Advantages of user-defined functions

66
User-defined functions help to decompose a large program into small segments which makes program
easy to understand, maintain and debug.
If repeated code occurs in a program. Function can be used to include those codes and execute when
needed by calling that function.
Programmers working on large project can divide the workload by making different functions.

Example of a user-defined function

#Program to illustrate
#the use of user-defined functions
def add_number(x,y):
sum=x+y
return sum
num1= 5
num2 = 6
print(“The sum is”, add_numbers(num1, num2)
Output
Enter a number: 2.4
Enter another number: 6.5
The sum is 8.9

Default Parameter Values


Although the syntax is similar, these are not to be confused with keyword arguments.
Default parameter values appear within the function definition and allow us to conveniently set a
default value. This means that if any argument is omitted, its default value will be used as the argument.
deffoo(a=0, b=0, c=0):
print(a, b, c)
>>>foo()
000
>>>foo(1, 2, 3)
123
>>>foo(c=3, b=2)
023
>>>foo(1, c=3)
103
Using default parameter values does not change how a function can be invoked with arguments:
>>>foo(1, 2, a=3)
TypeError: foo() got multiple values for argument 'a'
>>>foo(1, b=2, b=3)
SyntaxError: keyword argument repeated
>>>foo(a=1, 2, 3)
SyntaxError: positional argument follows keyword argument
You must specify any parameters without a default value before those with default values:
deffoo(a=0, b):
SyntaxError: non-default argument follows default argument

67
Positional-only Parameters
Python 3.8 / PEP 570 introduces the possibility to specify which parameters are required to be
positional-only via a bare / parameter within a function definition.
deffoo(a=0, b=0, /, c=0, d=0):
print(a, b, c, d)
The parameters defined before the bare / are now considered to be positional-only and keyword
mapping will no longer work on them.
In the above function definition a and b are now positional-only parameters.
These function calls will still work:
>>>foo()
0000
>>>foo(1)
1000
>>>foo(1, 2, 3, 4)
1234
>>>foo(1, 2, d=4, c=3)
1234
>>>foo(1, d=4, c=3)
1034
>>>foo(c=3, d=4)
0034
However, attempting to pass keyword arguments for a or b will fail:
>>>foo(1, b=2, c=3, d=4)
TypeError: foo() got some positional-only arguments passed as keyword arguments: 'b'

Python return Statement


The python return statement is used in a function to return something to the caller program.
We can use the return statement inside a function only.
In Python, every function returns something. If there are no return statements, then it returns None.
If the return statement contains an expression, it’s evaluated first and then the value is returned.
The return statement terminates the function execution.
A function can have multiple return statements. When any of them is executed, the function terminates.
A function can return multiple types of values.
Python function can return multiple values in a single return statement.
Python return Statement Example
Let’s look at a simple example to add two numbers and return the total to the caller.
defadd(x, y):
total =x +y
returntotal
We can optimize the function by having the expression in the return statement.
defadd(x, y):
returnx +y

68
Return multiple values from functions:

You can return multiple values by bundling those values into a dictionary, tuple, or a list. These
data types let you store multiple similar values. You can extract individual values from them in your
main program. Or, you can pass multiple values and separate them with commas.
Python functions can return multiple values. To return multiple values, you can return either a
dictionary, a Python tuple, or a list to your main program.
Python: Return Multiple Values
You can return multiple values from a Python function using:
A list that contains multiple values.
A tuple with multiple values.
A dictionary with multiple records.
Multiple values separated by commas.
All the above data types let you store multiple values. The solution of returning multiple values
separated by commas is the most elegant. This is because this approach makes your intent clear: to
return multiple separate values back to your main program.
A Python return statement sends values from a function to a main program. This statement is most
commonly used to return one value to a main program. It can be used to return multiple values to a
main program.
Python: Return Multiple Values with Commas
You can return multiple values by separating the values you want to return with commas. These values
should appear after your Python return statement.
We’re going to write a program that calculates the number of sales made at an electronics store. We’re
only going to count sales worth more than $500. Our program will also calculate the average value of
each sale.
To start, let’s define a Python array that contains a list of sales:
sales = [59.99, 240.00, 655.25, 75.99]
Next, write a Python function that calculates the number of sales worth more than $500 and the
average value of a purchase:
defcalculate_data(sales):
over_limit = 0
for s in sales:
if s >500:
over_limit += 1
average_purchase = sum(sales) / len(sales)
returnover_limit, average_purchase
Our function iterates over every sale in our list using a for loop. If a sale is worth more than $500, our
“over_limit” Python variable is incremented by one. We then calculate the average value of purchase
by dividing the total value of all sales by the number of sales made.
At the end of our function, use a return statement to return the values of “over_limit” and
“average_purchase” to our main program.
Python: Return Multiple Values with a List or Tuple
Both lists and tuples let you store multiple values. This means we can use them to return multiple
values to our main program.

69
Using a list or a tuple is best if the values you are returning have some kind of relationship. But, you
can use this approach to return any collection of values.
We’re going to return the average purchase size and the number of purchases worth over $500 to our
main program. To do so, let’s refer back to our example from earlier and make a small change to use a
list:
defcalculate_data(sales):
over_limit = 0
for s in sales:
if s >500:
over_limit += 1
average_purchase = sum(sales) / len(sales)
return [over_limit, average_purchase]
We have just separated our values into a single list. Our list contains the number of purchases worth
over $500 and the value of an average purchase, respectively.
We could also return a tuple data structure. To do so, we would replace our square brackets with curly
brackets. The big factor to consider is that tuples cannot contain duplicate values. If there is a chance
two values you pass to your main program will be equal, avoid using a tuple.

To access these values in our main program, we have to use indexing:


values = calculate_data(sales)
print("{} sales were made over $500. The average purchase was ${}.".format(values[0],
round(values[1])))

We use the values[0] syntax to access the first value in the list our calculate_data() function returns.
This corresponds to the value of “over_limit” in our function. We use the values[1] syntax to access the
value of the average purchase.
Our code returns:
1 sales were made over $500. The average purchase was $258.
Our code works just like our last example, but this time we’ve used a list to separate the values in our
code.
Python: Return Multiple Values with a Dictionary
We can return multiple values from a function using a dictionary.
In our last example, we only returned two values to our main program. This made it convenient to use
unpacking syntax (where you “unpack” values into multiple variables ).
If we were working with more values, it may be easier to return a dictionary that associates each value
with a label. Let’s revise our last function to use a dictionary to return multiple values to our main
program:
defcalculate_data(sales):
over_limit = 0
for s in sales:
if s >500:
over_limit += 1
average_purchase = sum(sales) / len(sales)
return{ "limit": over_limit, "average": average_purchase }

70
Our function returns a dictionary with two keys and values. The keys, “limit” and “average”, can be
used to uniquely identify each value. Now we have to revise our function call and our print statement to
support this new syntax:

values = calculate_data(sales)
print("{} sales were made over $500. The average purchase was ${}.".format(values["limit"],
round(values["average"])))

We return a dictionary back to our main program. We assign this dictionary to the variable “values”.
Then, we use indexing to retrieve the values of “limit” and “average”.
Let’s run our program:
1 sales were made over $500. The average purchase was $258.

Types Of Arguments In Python Functions

Argument: An argument is a variable (which contains data) or a parameter that is sent to the function
as input. Before getting into argument types, let’s get familiar with words formal and actual arguments.
Formal arguments: When a function is defined it (may) has (have) some parameters within the
parentheses. These parameters, which receive the values sent from the function call, are called formal
arguments.
Actual arguments: The parameters which we use in the function call or the parameters which we use
to send the values/data during the function call are called actual arguments.
Example: formal and actual function arguments in python ([Link])
defsum(a, b):
c = a + b # a and b are formal arguments
print(c)
# call the function
x = 10
y = 15
sum(x, y)# x and y are actual arguments
Output: 25

Types of Arguments in Pythons:


In python, depending on the way or format we send the arguments to the function, the arguments can be
classified into four types:
Positional arguments
Keyword arguments
Default arguments
Variable-length arguments
keyword variable-length argument

Positional Arguments in Python:


If there are three arguments (formal arguments) in the function definition, then you need to send three
arguments(actual arguments) while calling the function. The actual arguments will be received by the
formal arguments in the same order as in the function call. Let’s understand this through an example.

71
In [Link] the actual arguments 10, 20 will be received in the same order sent i.e 10 will go into
variable ‘x’, and 20 will go into the variable ‘y’. If we send the arguments as 20,10 then 20 will go into
x and 10 will go into y. The number of arguments and position of arguments should be matched,
otherwise, we will get errors as shown in [Link]
Example: Positional arguments ([Link])
defsub(x, y):
print(x-y)
# calling function
sub(10, 20)
Output: -10
Example: Positional arguments ([Link])
defsub(x, y):
print(x-y)
# calling function
sub(10, 20,30)

Output: TypeError: sub() takes 2 positional arguments but 3 were given

Keyword Arguments in Python:


In the function call, if we send the values using keys then they are called keyword arguments. Here,
keys are nothing but the names of the variables. In a way, we can say that keyword arguments are
arguments that recognize the parameters by the name of the parameters. Let’s understand it by the
example [Link] where the name of the function is cart() and parameters are item and price can be
written as:
def cart(item, price):
At the time of calling this function, we must pass two values and we can write which value is for what
by using the name of the parameter, for example,
cart(item=”bangles”, price=20000)
cart(item=”handbag”, price=100000)
item and price are called keywords in this scenario. Here we can change the order of arguments.

Example: Keyword arguments ([Link])


defcart(item, price):
print(item, "cost is :" ,price)
cart(item="bangles", price=20000)
cart(item="handbag", price=100000)
cart(price=1200, item="shirt")
Output:

Example: Keyword arguments ([Link])


defdetails(id, name):
print("Emp id is: ",id)

72
print("Emp name is: ",name)
# calling function
details(id=1, name="Balayya Babu")
details(id=2, name="Chiru")
Output:

Note: We can use both positional and keyword arguments simultaneously. But first, we must take
positional arguments and then keyword arguments, otherwise, we will get syntax errors as shown in
[Link]
Example: Positional and keyword arguments in Python ([Link])
defdetails(id, name):
print("Emp id is: ",id)
print("Emp name is: ",name)
# calling function
details(1, name="Anushka")
Output:

Example: Positional and keyword arguments in Python ([Link])


defdetails(id, name):
print("Emp id is: ",id)
print("Emp name is: ",name)
# calling function
details(name="Anushka",1)

Output: SyntaxError: non-keyword arg after keyword arg

Default Arguments in Python Function with Examples:


In the function definition, while declaring parameters, we can assign some value to the parameters,
which are called default values. Such default values will be considered when the function call does not
send any data to the parameter. Let’s take the function from [Link] as an example. There, the
function cart has parameters as items and price. Let’s say the price of many items is 20 rupees. In this
case, we can set the price param to the default value of 20 rupees
def cart(items, price=20):
In the above example items have no default value, so we should provide. price has a default value of
20. Still, if we provide the value at the time of calling then default values will be overridden with
passed value.

Example: Default Arguments in Python ([Link])


defcart(item, price=20):
print(item, "cost is :" ,price)

73
cart(item="pen")
cart(item="handbag", price=10000)
cart(price=500, item="shirt")
Output:

Note: If we are not passing any value, then only the default value will be considered. While defining a
function, after default arguments we should not take non-default arguments.

Example: Default arguments ([Link])


defcart(item=1, price):
print(item, "cost is :" ,price)
cart(item="pen")
cart(item="handbag", price=10000)
cart(price=500, item="shirt")
Output: SyntaxError: non-default argument follows default argument

Variable Length Arguments in Python Function:

Sometimes, the programmer does not know how many values need to pass to function. In that
case, the programmer cannot decide how many arguments to be given in the function definition.
Therefore, we use variable-length arguments to accept n number of arguments.
The variable-length argument is an argument that can accept any number of values. The variable-length
argument is written with a ‘*’ (one star) before the variable in the function definition.
Syntax:

x is a formal argument, *y is a variable-length argument. Now we can pass any number of values to this
*y. Internally the provided values will be represented in the tuple.
Example: Variable-length argument in python ([Link])
deftotal_cost(x, *y):
sum=0
foriin y:
sum+=i
print(x + sum)
#calling function
total_cost(100, 200)#valid
total_cost(110, 226, 311)#valid
total_cost(11,)#valid
Output:

74
keyword variable-length argument (**variable) in Python:
Just as variable length arguments, there are keyword variable length arguments that are n key-
value pairs. The syntax is given below.

**x represents as keyword variable argument. Internally it represents a dictionary object. A dictionary
stores the data in the form of key-value pairs.

Example: keyword variable length argument (**variable) in Python ([Link])


defprint_kwargs(**kwargs):
print(kwargs)
print_kwargs(id=1, name="Nireekshan", qualification="MCA")
Output:

Example: keyword variable-length argument (**variable) ([Link])


defm1(**x):
for k, v [Link]():
print(k,"=",v)
m1(a=10, b=20, c=30)
m1(id=100, name="Subbalaxmi")
Output:

Function vs Module vs Library in Python:


A group of lines with some name is called a function
A group of functions saved to a file is called Module
A group of Modules is nothing but Library
Types of variables in Python: Global and local variables
Variables are of two types Global and local variables. The reason for this categorization of variables is
their different levels of accessibility. The type of variable depends on whether we are able to access a
variable on a certain block of code or not
To understand the concept of global and local variables, you should be familiar with functions in a
programming language. No! function here doesn't mean 'what a programming language can
do.' Instead, it is a block of code in a programming language.
A block of code to perform a specified operation is known as function. For example, a function of
addition can have a code block that specifies variables, values, logic and display output after addition.
Syntax of a function in Python

75
def function_name():
code block inside function
The def keyword defines a function. Now, you know what a function is, it will be helpful for you to
understand global and local variables easily.

Python Local Variables


A function can have variables inside it called local variables. A local variable is the one that gets
declared inside a function. The important thing to notice is that, this local variable is unavailable for the
code outside the function in which it is declared. Here, declaration means assigning a value to a
variable for the first time.
In python, a function's scope/body is defined by the indentations. The scope of a function is its whole
body, i.e., all the code written in a function within indentation is its scope. So, the local variables can
only be used within a function's scope.
Let's look at an example of local variables in python:
Example: Python Local Variables

#This function prints value of a global variable

defdisplay_string(): #start of function scope


print(s)
#end of function scope
#Global scope
s = "Welcome to CodeRepublics"
display_string() #calling the function

Outputelcome to CodeRepublics

Python Global Variables


Python Global variables are accessible all over a python script. In simple terms, if you declare a
variable outside a function, then it is not limited within the scope of any function, as it is not declared
inside a function. The advantage of the Global variable is that it can be accessed from inside or outside
of a function.
Using global variable is helpful if there is a common value getting used multiple times in a python
script. For example: Let's take a Global variable, name="Jack". This name, 'jack,' will be used by
multiple functions for their own operation. So instead of creating several local variables with value
'Jack', functions can use a global variable. It saves memory space and time also.
Let's see an example of how a global variable is created in Python.

Example: Create a Global Variable


x = "global variable"

deffunc_display():
print("x inside:", x)

76
func_display
print("x outside:", x)

Output
x inside: global variable
x outx outside: global variable
e: global variable
Recursive function

A recursive function is a function that calls itself during its execution. This enables the function
to repeat itself several times, outputting the result and the end of each iteration. Recursion has
something to do with infinity.
Following is an example of recursive function to find the factorial of an integer.
In the above program factorial() is a recursive functions as it calls itself. Each function call multiples
the number with the factorial of number 1 until the number is equal to one.
For example to place two parallel mirrors facing each other. Any object in between them would be
reflected recursively.

Example 1
defFunction(x):
if(x <1):
return
else:
print(x,end=" ")
Function(x-1)
print(x,end=" ")
return
x =5
Function(x)
Output
5432112345

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
Add 10 to argument a, and return the result:
x = lambda a : a + 10
print(x(5))
output:
15

77
Lambda functions can take any number of arguments:
Example
Multiply argument a with argument b and return the result:
x = lambda a, b : a * b
print(x(5, 6))
output:
30
filter()
This function is used along with the lambda(). This checks the condition for every element of the
iterable and adds only those values that satisfy the condition.

Example of filter() function:


list(filter(lambda i:i%2,range(10)))
Output:
[1, 3, 5, 7, 9]

Reduce functions:
The reduce() function in python is a part of the functools module and doesn't return multiple
values; it just returns a single value.
Steps of how to reduce function works in python:
The function passed as an argument is applied to the first two elements of the iterable.
After this, the function is applied to the previously generated result and the next element in the iterable.
This process continues until the whole iterable is processed.
The single value is returned as a result of applying the reduce function on the iterable.
Examples of Reduce Function in Python
Example using lambda function (Summing Numeric Values)
In this example, we have defined a lambda function that calculates the sum of two numbers on the
passed list as an iterable using the reduce function.
Code:
from functools import reduce
nums = [1, 2, 3, 4]
ans = reduce(lambda x, y: x + y, nums)
print(ans)
Output:
10

Aliasing and Cloning Lists


Giving a new name to an existing list is called 'aliasing'. The new name is called 'alias name'.
For example, take a list 'x' with 5 elements as

To provide a new name to this list, we can simply use assignment operator as:

In this case, we are having only one list of elements but with two different names 'x' and 'y'. Here, 'x' is
the original name and 'y' is the alias name for the same list. Hence, any modifications done to 'x' will

78
also modify 'y' and vice versa. Observe the following statements where an element x[1] is modified
with a new value.

Hence, if the programmer wants two independent lists, he should not go for aliasing. On the other hand,
he should use cloning or copying.
Obtaining exact copy of an existing object (or list) is called 'cloning'. To clone a list, we can take help
of the slicing operation as:

y = x[:] #x is cloned as y

When we clone a list like this, a separate copy of all the elements is stored into 'y'. The lists 'x' and 'y'
are independent lists. Hence, any modifications to 'x' will not affect 'y' and vice versa. Consider the
following statements:
x = [10,20,30,40,50]

y = x[:] #x is cloned as y

print(x) will display [10,20,30,40,50]

print(y) will display [10,20,30,40,50]

x[1] = 99 #modify 1st element in x

print(x) will display [10,99,30,40,50]

print(y) will display [10,20,30,40,50]

79
We can observe that in cloning, modifications to a list are confined only to that list. The same can be
achieved by copying the elements of one list to another using copy() method. For example, consider the
following statement:
y = [Link]() #x is copied as y
When we copy a list like this, a separate copy of all the elements is stored into 'y'. The lists 'x' and 'y'
are independent. Hence, any modifications to 'x' will not affect 'y' and vice versa.

Decorator
Decorators are one of the most helpful and powerful tools of Python. These are used to modify
the behavior of the function. Decorators provide the flexibility to wrap another function to expand the
working of wrapped function, without permanently modifying it.
In Decorators, functions are passed as an argument into another function and then called inside the
wrapper function.
It is also called meta programming where a part of the program attempts to change another part of
program at compile time.
Before understanding the Decorator, we need to know some important concepts of Python.

Generators:
Introduction to Python generators
Typically, Python executes a regular function from top to bottom based on the run-to-completion
model.
It means that Python cannot pause a regular function midway and then resumes the function after that.
For example:
defgreeting():
print('Hi!')

80
print('How are you?')
print('Are you there?')
Code language:Python(python)
When Python executes the greeting() function, it executes the code line by line from top to bottom.
Also, Python cannot pause the function at the following line:
print('How are you?')

Code language:Python(python)
… and jumps to another code and resumes the execution from that line.
To pause a function midway and resume from where the function was paused, you use
the yield statement.
When a function contains at least one yield statement, it’s a generator function.
By definition, a generator is a function that contains at least one yield statement.
When you call a generator function, it returns a new generator object. However, it doesn’t start the
function.
Generator objects (or generators) implement the iterator protocol. In fact, generators are lazy iterators.
Therefore, to execute a generator function, you call the next() built-in function on it.
A simple Python generator example
See the following example:
defgreeting():
print('Hi!')
yield1
print('How are you?')
yield2
print('Are you there?')
yield3

DEMONSTRATION
Experiment-1: Write a python function to find factorial of given number?

Factorial of a number is the product of all the integers from 1 to that number.
For example, the factorial of 9 (denoted as 9!) is 1*2*3*4*5*6*7*8*9 = 362880.
(Or)
Problem Description:N factorial is represented as N! where the exclamation point means factorial. For
example,
1! = 1
2! = 1*2 = 2
3! = 1*2*3 = 6
4! = 1*2*3*4 = 24
...
N! = 1*2*3...*N

Algorithm:

81
1. Start
2. Declare variables n, factorial and i.
3. Initialize variables
factorial←1
i←1
4. Read value of n
5. Repeat the steps until i=n
5.1: factorial←factorial*i
5.2: i←i+1
6. Display factorial
7. Stop
Program
def factorial(i):
ifi==1:
return1
else:
return(i* factorial(i-1))
number =9
print("The factorial of", number,"is", factorial(number))
Output
The factorial of 9 is 362880

Experiment 2: Write a program to create a lambda function to find square of given number?

def lambda_square(x):
return x*x
print(lambda_square(5))
output:
25

EXPERIMENTATION

Experiment-3: Lambda Function to find biggest of given values.

Step1: create a list using tuple


Step2: map the list with another list and use the key word max
Step3: expected output maximum value from given input data.

Experiment-4: Program to filter only even numbers from the list by using filter() function?

82
Step1: a list contain both even and odd numbers
Ex: seq=[1,2,3,4,5,6,7,…….]
Step2: Results contains only even numbers from the list
Step3: result =filter(lambdax: x %2==0, seq)
print(list(result))
step4: output print the even numbers only.

83
Lab 6
Working with Strings-Defining String, Multi-line Strings, Accessing characters of a string, Mathematical
operators for strings, Membership operator, Comparison of Strings, Removing spaces from the string,
Finding Substring, String replacement, Splitting of Strings, Changing cases of a string, Formatting the
strings

Python Strings:
Strings in Python are identified as a contiguous set of characters represented in the quotation
marks. Python allows for either pairs of single or double quotes. Subsets of strings can be taken using
the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their
way from -1 at theend.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator. For
example:
Program:
str ="WELCOME"
print str # Prints complete string
print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 5th print str[2:] # Prints string starting from 3rd
character print str * 2 # Prints string two times
print str + "CSE" # Prints concatenated string
Output:
WELCOME W
LCO LCOME
WELCOMEWELCOME WELCOMECSE

Built-in String methods for Strings:


Python Strings:
What is String in Python?
A string is a sequence of characters.
A character is simply a symbol. For example, the English language has 26 characters.
Computers do not deal with characters, they deal with numbers (binary). Even though you may see
characters on your screen, internally it is stored and manipulated as a combination of 0s and 1s.
This conversion of character to a number is called encoding, and the reverse process is decoding.
ASCII and Unicode are some of the popular encodings used.
In Python, a string is a sequence of Unicode characters. Unicode was introduced to include every
character in all languages and bring uniformity in encoding. You can learn about Unicode from Python
Unicode.

How to create a string in Python?


Strings can be created by enclosing characters inside a single quote or double-quotes. Even triple
quotes can be used in Python but generally used to represent multiline strings and docstrings.
# defining strings in Python

84
# all of the following are equivalent
my_string = 'Hello'
print(my_string)

my_string = "Hello"
print(my_string)

my_string = '''Hello'''
print(my_string)

# triple quotes string can extend multiple lines


my_string = """Hello, welcome to
the world of Python"""
print(my_string)

When you run the program, the output will be:

Hello
Hello
Hello
Hello, welcome to
the world of Python

How to access characters in a string?


We can access individual characters using indexing and a range of characters using slicing. Index starts
from 0. Trying to access a character out of index range will raise an IndexError. The index must be an
integer. We can't use floats or other types, this will result into TypeError.

Python allows negative indexing for its sequences.

The index of -1 refers to the last item, -2 to the second last item and so on. We can access a range of
items in a string by using the slicing operator :(colon).

#Accessing string characters in Python


str = 'cmrcet'
print('str = ', str)

#first character
print('str[0] = ', str[0])

#last character
print('str[-1] = ', str[-1])

#slicing 2nd to 5th character


print('str[1:5] = ', str[1:5])

85
#slicing 6th to 2nd last character
print('str[5:-2] = ', str[5:-2])

Output:
str = cmrcet
str[0] = c
str[-1] = t
str[1:5] = mrce
str[5:-2] =
If we try to access an index out of the range or use numbers other than an integer, we will get errors.

# index must be in range


>>>my_string[15]
...
IndexError: string index out of range

# index must be an integer


>>>my_string[1.5]
...
TypeError: string indices must be integers
Slicing can be best visualized by considering the index to be between the elements as shown below.

If we want to access a range, we need the index that will slice the portion from the string.

Element Slicing in Python

String Slicing in Python

Strings are immutable. This means that elements of a string cannot be changed once they have been
assigned. We can simply reassign different strings to the same name.

>>>my_string = 'programiz'
>>>my_string[5] = 'a'
...
TypeError: 'str' object does not support item assignment
>>>my_string = 'Python'
>>>my_string

86
'Python'
We cannot delete or remove characters from a string. But deleting the string entirely is possible using
the del keyword.

>>> del my_string[1]


...
TypeError: 'str' object doesn't support item deletion
>>> del my_string
>>>my_string
...
NameError: name 'my_string' is not defined
Python String Operations
There are many operations that can be performed with strings which makes it one of the most used data
types in Python.

To learn more about the data types available in Python visit: Python Data Types

Concatenation of Two or More Strings


Joining of two or more strings into a single one is called concatenation.

The + operator does this in Python. Simply writing two string literals together also concatenates them.

The * operator can be used to repeat the string for a given number of times.

# Python String Operations


str1 = 'Hello'
str2 ='World!'

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

# using *
print('str1 * 3 =', str1 * 3)
Run Code
When we run the above program, we get the following output:

str1 + str2 = HelloWorld!


str1 * 3 = HelloHelloHello
Writing two string literals together also concatenates them like + operator.

If we want to concatenate strings in different lines, we can use parentheses.

>>> # two string literals together


>>> 'Hello ''World!'
'Hello World!'

87
>>> # using parentheses
>>> s = ('Hello '
... 'World')
>>> s
'Hello World'
Iterating Through a string
We can iterate through a string using a for loop. Here is an example to count the number of 'l's in a
string.

# Iterating through a string


count = 0
for letter in 'Hello World':
if(letter == 'l'):
count += 1
print(count,'letters found')
Run Code
When we run the above program, we get the following output:

3 letters found
String Membership Test
We can test if a substring exists within a string or not, using the keyword in.

>>> 'a' in 'program'


True
>>> 'at' not in 'battle'
False
Built-in functions to Work with Python
Various built-in functions that work with sequence work with strings as well.

Some of the commonly used ones are enumerate() and len(). The enumerate() function returns an
enumerate object. It contains the index and value of all the items in the string as pairs. This can be
useful for iteration.

Similarly, len() returns the length (number of characters) of the string.

str = 'cold'

# enumerate()
list_enumerate = list(enumerate(str))
print('list(enumerate(str) = ', list_enumerate)

#character count
print('len(str) = ', len(str))
Run Code

88
When we run the above program, we get the following output:

list(enumerate(str) = [(0, 'c'), (1, 'o'), (2, 'l'), (3, 'd')]


len(str) = 4
Python String Formatting
Escape Sequence
If we want to print a text like He said, "What's there?", we can neither use single quotes nor double
quotes. This will result in a SyntaxError as the text itself contains both single and double quotes.

>>>print("He said, "What's there?"")


...
SyntaxError: invalid syntax
>>>print('He said, "What's there?"')
...
SyntaxError: invalid syntax
One way to get around this problem is to use triple quotes. Alternatively, we can use escape sequences.

An escape sequence starts with a backslash and is interpreted differently. If we use a single quote to
represent a string, all the single quotes inside the string must be escaped. Similar is the case with double
quotes. Here is how it can be done to represent the above text.

# using triple quotes


print('''He said, "What's there?"''')

# escaping single quotes


print('He said, "What\'s there?"')

# escaping double quotes


print("He said, \"What's there?\"")
Run Code
When we run the above program, we get the following output:

He said, "What's there?"


He said, "What's there?"
He said, "What's there?"
Here is a list of all the escape sequences supported by Python.

Escape Sequence Description


\newline Backslash and newline ignored
\\ Backslash
\' Single quote
\" Double quote
\a ASCII Bell
\b ASCII Backspace

89
\f ASCII Formfeed
\n ASCII Linefeed
\r ASCII Carriage Return
\t ASCII Horizontal Tab
\v ASCII Vertical Tab
\ooo Character with octal value ooo
\xHH Character with hexadecimal value HH
Here are some examples

>>> print("C:\\Python32\\Lib")
C:\Python32\Lib

>>>print("This is printed\nin two lines")


This is printed
in two lines

>>>print("This is \x48\x45\x58 representation")


This is HEX representation
Raw String to ignore escape sequence
Sometimes we may wish to ignore the escape sequences inside a string. To do this we can place r or R
in front of the string. This will imply that it is a raw string and any escape sequence inside it will be
ignored.

>>>print("This is \x61 \ngood example")


This is a
good example
>>>print(r"This is \x61 \ngood example")
This is \x61 \ngood example
The format() Method for Formatting Strings
The format() method that is available with the string object is very versatile and powerful in formatting
strings. Format strings contain curly braces {} as placeholders or replacement fields which get replaced.

We can use positional arguments or keyword arguments to specify the order.

# Python string format() method

# default(implicit) order
default_order = "{}, {} and {}".format('John','Bill','Sean')
print('\n--- Default Order ---')
print(default_order)

# order using positional argument


positional_order = "{1}, {0} and {2}".format('John','Bill','Sean')
print('\n--- Positional Order ---')

90
print(positional_order)

# order using keyword argument


keyword_order = "{s}, {b} and {j}".format(j='John',b='Bill',s='Sean')
print('\n--- Keyword Order ---')
print(keyword_order)
Run Code
When we run the above program, we get the following output:

--- Default Order ---


John, Bill and Sean

--- Positional Order ---


Bill, John and Sean

--- Keyword Order ---


Sean, Bill and John
The format() method can have optional format specifications. They are separated from the field name
using colon. For example, we can left-justify <, right-justify > or center ^ a string in the given space.

We can also format integers as binary, hexadecimal, etc. and floats can be rounded or displayed in the
exponent format. There are tons of formatting you can use. Visit here for all the string formatting
available with the format() method.

>>> # formatting integers


>>> "Binary representation of {0} is {0:b}".format(12)
'Binary representation of 12 is 1100'

>>> # formatting floats


>>> "Exponent representation: {0:e}".format(1566.345)
'Exponent representation: 1.566345e+03'

>>> # round off


>>> "One third is: {0:.3f}".format(1/3)
'One third is: 0.333'

>>> # string alignment


>>> "|{:<10}|{:^10}|{:>10}|".format('butter','bread','ham')
'|butter | bread | ham|'
Old style formatting
We can even format strings like the old sprintf() style used in C programming language. We use the %
operator to accomplish this.

>>> x = 12.3456789
>>>print('The value of x is %3.2f' %x)

91
The value of x is 12.35
>>>print('The value of x is %3.4f' %x)
The value of x is 12.3457
Common Python String Methods
There are numerous methods available with the string object. The format() method that we mentioned
above is one of them. Some of the commonly used methods are lower(), upper(), join(), split(), find(),
replace() etc. Here is a complete list of all the built-in methods to work with strings in Python.

Demonstration
Experiment-1: Write a program to accept some string from the keyboard and display its characters
by index wise (both positive and negative index).

Program:
str=input("enter any string")
for i in range(0,len(str),1):
print("positve index is ",i,"value is",str[i])
for i in range(-1,-(len(str))-1,-1):
print("negative index is ",i,"value is",str[i])

Output:

Experiment-2: Write a program to access each character of string in forward and backward
direction by using while loop?
Program:
str=input("enter any string")

92
i=0
while i<len(str):
print("|",str[i])
i=i+1
print("V")
j=-1
print("^")
while(j>(-(len(str))-1)):
print("|",str[j])
j=j-1;
Output:

Experimentation
Experiment-3: Program to display all positions of substring in a given main string.?

Approach:
# Python3 code to demonstrate working of
# All occurrences of substring in string
# Using list comprehension + startswith()
Step-1: start
Step-2: # initializing string
test_str = """CMR COLLEGE OF ENGINEERING & TECHNOLOGY
CMR GROUP
CMR EC
CMR IT
CMR P

93
CMR TE"""

Step-3:# initializing substring


test_sub = "CMR"

Step-4:# printing original string


Step-5:# printing substring
# using list comprehension + startswith()
Step-6: # All occurrences of substring in string
res = [i for i in range(len(test_str)) if test_str.startswith(test_sub, i)]
Step-7:# printing result
print res
Step-8:stop
Experiment-4: Write a program to reverse the given String.

Approach -1:
Step-1: Firstly the user will enter a string.
Step-2: Empty string str = ‘ ‘ is created which will hold the reversed string.
Step-3: The for loop iterate every element of the given string
Step-4: At last, it will return the reversed string and the result will be printed.
Approach-2:
Using Extended Slice syntax
The extended slice syntax has three parameters, [starts,end,step]. Giving no fields as start and end by
default means 0 as start and length of the string as [Link] step as ‘-1’ means starting from the
end and stop at the [Link], we get the reversed string.

94
Lab 7:

Python Data Structures-List: Creating a list- Accessing elements of a List, Traversing the List,
List Manipulation, Ordering the elements of a List, Mathematical Operators for List objects,
Membership Operator, Nested Lists, List Comprehensions

List:

A list is similar to an array that consists of a group of elements or items. Just like an array, a list can
store elements. But, there is one major difference between an array and a list. An array can store only
one type of elements whereas a list can store different types of elements. Hence lists are more versatile
and useful than an array.

Creating a List:

Creating a list is as simple as putting different comma-separated values between square brackets.
student = [556, “Mothi”, 84, 96, 84, 75, 84 ]

We can create empty list without any elements by simply writing empty square brackets as: student=[ ]

We can create a list by embedding the elements inside a pair of square braces []. The elements in the
list should be separated by a comma (,).
Accessing Values in list:
To access values in lists, use the square brackets for slicing along with the index or indices to obtain
value available at that index. To view the elements of a list as a whole, we can simply pass the list name
to print function.

Ex:
student = [556, “Mothi”, 84, 96, 84, 75, 84 ] print student
print student[0] # Access 0th element
print student[0:2] # Access 0th to 1st elements

95
print student[2: ] # Access 2nd to end of list elements print student[ :3] # Access starting to 2nd
elements print student[ : ] # Access starting to ending elements print student[-1] # Access last
index value
print student[-1:-7:-1] # Access elements in reverse order

Output:
[556, “Mothi”, 84, 96, 84, 75, 84]
Mothi
[556, “Mothi”]
[84, 96, 84, 75, 84]
[556, “Mothi”, 84]
[556, “Mothi”, 84, 96, 84, 75, 84]
84
[84, 75, 84, 96, 84, “Mothi”]

Creating lists using range() function:

We can use range() function to generate a sequence of integers which can be stored in a list. To store
numbers from 0 to 10 in a list as follows.
numbers = list( range(0,11) )
print numbers # [0,1,2,3,4,5,6,7,8,9,10]

To store even numbers from 0 to 10in a list as follows. numbers = list( range(0,11,2) )
print numbers # [0,2,4,6,8,10]

Looping on lists:

We can also display list by using for loop (or) while loop. The len( ) function useful to know the
numbers of elements in the list. while loop retrieves starting from 0th to the last element i.e.n-1
Ex-1:
numbers = [1,2,3,4,5] for i in numbers:
print i,

Output:
12345

Updating and deleting lists:


Lists are mutable. It means we can modify the contents of a list. We can append, update or delete the
elements of a list depending upon our requirements.
Appending an element means adding an element at the end of the list. To, append a new element to the
list, we should use the append() method.

Example:

96
lst=[1,2,4,5,8,6]
printlst # [1,2,4,5,8,6] [Link](9)
printlst # [1,2,4,5,8,6,9]

Updating an element means changing the value of the element in the list. This can be done by accessing
the specific element using indexing or slicing and assigning a new value.

Example:
lst=[4,7,6,8,9,3]
printlst #[4,7,6,8,9,3]
lst[2]=5 # updates 2nd element in the list printlst # [4,7,5,8,9,3]
lst[2:5]=10,11,12 # update 2nd element to 4th element in the list printlst # [4,7,10,11,12,3]

Deleting an element from the list can be done using ‘del’ statement. The del statement takes the
position number of the element to be deleted.

Example:
lst=[5,7,1,8,9,6]
dellst[3] # delete 3rd element from the list i.e., 8 printlst # [5,7,1,9,6]

If we want to delete entire list, we can give statement like del lst.

Concatenation of Two lists:


Wecansimplyuse„+‟[Link],„x‟and„y‟are two [Link]
wewrtex+y,the list „y‟ isjoined at the end ofthe list „x‟.

Example:
x=[10,20,32,15,16]
y=[45,18,78,14,86]
print x+y # [10,20,32,15,16,45,18,78,14,86]

Repetition of Lists:
Wecanrepeattheelementsofalist„n‟numberoftimesusing„*‟operator. x=[10,54,87,96,45]
print x*2 # [10,54,87,96,45,10,54,87,96,45]

Membership in Lists:
Wecancheckifanelementisamemberofalistbyusing„in‟and„notin‟[Link]
theelementisamemberofthelist,then„in‟[Link]
theelementisnotinthelist,then„notin‟operatorreturnsTrueotherwisereturnsFalse.
Example:
x=[10,20,30,45,55,65] a=20
print ain x # True a=25
print ain x # False a=45
print a not in x # False a=40
print a not in x # True

97
Aliasing and Cloning Lists:
Giving a new name to an existing list is called ‘aliasing’. The new name is called
‘alias name’. To provide a new name to this list, we can simply use assignment operator (=).

Example:
x = [10, 20, 30, 40, 50, 60]
y=x # x is aliased asy
printx #[10,20,30,40,50,60]
printy #[10,20,30,40,50,60]
x[1]=90 # modify 1st element in x printx # [10,90,30,40,50,60]
printy #[10,90,30,40,50,60]

Inthiscasewearehavingonlyonelistofelementsbutwithtwodifferentnames„x‟and„y‟.Here,
„x‟istheoriginalnameand„y‟[Link],any modifications doneto x‟will also
modify„y‟andviceversa.
Obtaining exact copy of an existing object (or list) is called „cloning‟. To Clone a list, we can take help
of the slicing operation [:].

Example:
x = [10, 20, 30, 40, 50, 60]
y=x[:] # x is cloned asy
printx #[10,20,30,40,50,60]
printy #[10,20,30,40,50,60]
x[1]=90 # modify 1st element in x printx # [10,90,30,40,50,60]
printy #[10,20,30,40,50,60]

When we clone a list like this, a separate copy of all the elements is stored into „y‟. The lists „x‟ and „y‟
are independent lists. Hence, any modifications to „x‟ will not affect „y‟ and vice versa.

98
Methods in Lists:

Method Description
[Link](x) Returns the first occurrence of x in the list.
[Link](x) Appends x at the end of the list.
[Link](i,x) Inserts x to the list in the position specified by i.
[Link]() Copies all the list elements into a new list and returns it.
[Link](lst2) Appends lst2 to list.
[Link](x) Returns number of occurrences of x in the list.
[Link](x) Removes x from the list.
[Link]() Removes the ending element from the list.
[Link]() Sorts the elements of list into ascending order.
[Link]() Reverses the sequence of elements in the list.
[Link]() Deletes all elements from the list.
max(lst) Returns biggest element in the list.
min(lst) Returns smallest element in the list.

Example:
lst=[10,25,45,51,45,51,21,65]
[Link](1,46)
printlst # [10,46,25,45,51,45,51,21,65]
[Link](45) #2

Finding Common Elements in Lists:


Sometimes, it is useful to know which elements are repeated in two lists. For example, there is a
scholarship for which a group of students enrolled in a college. There is another scholarship for which
another group of students got enrolled. Now, we wan to know the names of the students who enrolled
for both the scholarships so that we can restrict them to take only one scholarship. That means, we are
supposed to find out the common students (or elements) both thelists.
First of all, we should convert the lists into lists into sets, using set( ) function, as: set(list). Then we
should find the common elements in the two sets using intersection() method.

Example:
scholar1=[„mothi‟,„sudheer‟,„happy‟,„narasimha‟, „ramakoteswararao‟]
scholar2=[ „happy‟, „narasimha‟,„ramesh‟]
s1=set(scholar1)
s2=set(scholar2)
s3=[Link](s2)
common =list(s3)
print common # display[„vinay‟,„narendra‟ ]

99
Nested Lists:
A list within another list is called a nested list. We know that a list contains several elements.
When we take a list as an element in another list, then that list is called a nested list.

Example:
a=[10,20,30]
b=[45,65,a]
printb # display [ 45, 65, [ 10, 20, 30 ]] printb[1] # display65
printb[2] # display [ 10, 20, 30 ] printb[2][0] # display10
print b[2][1] # display 20
print b[2][2] # display 30
for x in b[2]:
print x, # display 10 2030

Nested Lists as Matrices:


Suppose we want to create a matrix with 3 rows 3 columns, we should create a list with 3 other lists as:
mat = [ [ 1, 2, 3 ] , [ 4, 5, 6 ] , [ 7, 8, 9 ] ]
Here, „mat‟ is a list that contains 3 lists which are rows of the „mat‟ list. Each row contains again 3
elements as:
[ [ 1, 2, 3], # first row
[ 4, 5, 6], # second row
[ 7, 8, 9]] # third row

Example:
mat=[[1,2,3],[4,5,6],[7,8,9]]
for r in mat: print r
print ""
m=len(mat) n=len(mat[0])

for i in range(0,m): for j in range(0,n):


print mat[i][j], print ""

print ""

One of the main use of nested lists is that they can be used to represent matrices. A matrix
represents a group of elements arranged in several rows and columns. In python, matrices are created as
2D arrays or using matrix object in NumPy. We can also create a matrix using nested lists.

100
Q) Write a program to perform multiplication of twomatrices.
a=[[1,2,3],[4,5,6]]
b=[[4,5],[7,8],[1,2]] c=[[0,0],[0,0]]
m1=len(a) n1=len(a[0]) m2=len(b) n2=len(b[0])

for i in range(0,m1): for j in range(0,n2):


print
for i"\t",c[i][j], print ""
in range(0,m1): for j in range(0,n2):
for k in range(0,n1): c[i][j] +=a[i][k]*b[k][j]

List Comprehensions:
List comprehensions represent creation of new lists from an iterable object (like a list, set, tuple,
dictionary or range) that satisfy a given condition. List comprehensions contain very compact code
usually a single statement that performs the task.
We want to create a list with squares of integers from 1 to 100. We can write code as:
squares=[ ]
for i in range(1,11):
[Link](i**2)
The preceding code will create „squares‟ list with the elements as shown below:
[ 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
The previous code can rewritten in a compact way as:
squares=[x**2 for x inrange(1,11)]
This is called list comprehension. From this, we can understand that a list comprehension consists of
square braces containing an expression (i.e., x**2). After the expression, a fro loop and then zero or
more if statements can be written.
[ expression for item1 in iterable if statement1
for item1 in iterable if statement2
for item1 in iterable if statement3…..]

Example:
Even_squares = [ x**2 for x in range(1,11) ifx%2==0] It will display the list even
squares aslist.
[ 4, 16, 36, 64, 100]

101
Demonstration:

Experiment-1: Write a Python program to display unique vowels present in the given word.

Experiment-2: Write a Python program to Count the Occurrence of an Item in a List.

Experimentation:
Experiment-3: Write a Python program to segregate even and odd numbers from the given list of
numbers.

Step1: Python Program to Put Even and Odd Numbers in Separate List

102
Step2: create 3 empty list variable
Step3: create how many elements want to enter through key board
Step4: create loop to control the first list
foriinrange(1, Number +1):
value =int(input("Please enter the Value of %d Element :- "%i))
[Link](value)
Step5:
forj inrange(Number):
if(NumList[j] %2==0):
[Link](NumList[j])
else:
[Link](NumList[j])
Step6: print even and odd numbers separately

Experimnet-4: Write a Python program to find the cumulative sum of elements of the list.

Step1: create the empty list variable like a[]


Step2:create new list for number of elements required as input
Stpe3: generate the loop to control the list 0 to n
Step4: enter the new element and add that element into next elemet
Ex: element=int(input("Enter element" + str(x+1) + ":"))
Step5: append the element with list
Step6: create new element to add the index o to new added list of element
Ex: b=[sum(a[0:x+1]) for x in range(0,len(a))]
Step7: print the element a and b individually.
Expected output:

103
Lab-8:

(Python Data Structures-Tuple: Creating a Tuple, Accessing the elements of a tuple, mathematical
operators for tuple,Tuple packing and Unpacking)

TUPLE:
A Tuple is a python sequence which stores a group of elements or items. Tuples are similar to lists but the main difference is
tuples are immutable whereas lists are mutable. Once we create a tuple we cannot modify its elements. Hence, we cannot
perform operations like append(), extend(), insert(), remove(), pop() and clear() on tuples. Tuples are generally used to store
data which should not be modified and retrieve that data on demand.

Creating Tuples:
We can create a tuple by writing elements separated by commas inside parentheses( ).
The elements can be same datatype or different types.
To create an empty tuple, we can simply write empty parenthesis, as:
To create a tuple with only one element, we can, mention that element in parenthesis and after that a comma is needed. In
the absence of comma, python treats the element assign ordinary data type.
tup = (10) tup = (10,)
print tup # display 10 print tup # display 10
print type(tup) # display <type „int‟> print type(tup) # display<type „tuple‟>
To create a tuple with different types of elements:
If we do not mention any brackets and write the elements separating them by comma, then they are taken by default as a
tuple.
It is possible to create a tuple from a list. This is done by converting a list into a tuple using tuple function.
Another way to create a tuple by using range( ) function that returns a sequence.

Accessing the tuple elements:


Accessing the elements from a tuple can be done using indexing or slicing. This is same as that of a list. Indexing represents
the position number of the element in the tuple. The position starts from 0.

Updating and deleting elements:


Tuples are immutable which means you cannot update, change or delete the values of tuple elements.

Example-1:
However, you can always delete the entire tuple by using the statement.

Note that this exception is raised because you are trying print the deleted element.

Operations on tuple:
Operation Description
len(t) Return the length of tuple.
tup1+tup2 Concatenation of two tuples.
Tup*n Repetition of tuple values in n number of times.
x in tup Return True if x is found in tuple otherwise returns False.
cmp(tup1,tup2) Compare elements of both tuples
max(tup) Returns the maximum value in tuple.
min(tup) Returns the minimum value in tuple.
tuple(list) Convert list into tuple.
[Link](x) Returns how many times the element „x‟ is found in

104
tuple.
[Link](x) Returns the first occurrence of the element „x‟ in tuple.
Raises ValueError if „x‟ is not found in the tuple.
sorted(tup) Sorts the elements of tuple into ascending order.
sorted(tup,reverse=True) will sort in reverse order.
cmp(tuple1, tuple2)
The method cmp() compares elements of two tuples.
Syntax
cmp(tuple1, tuple2)
Parameters
tuple1 -- This is the first tuple to be compared
tuple2 -- This is the second tuple to be compared
Return Value
If elements are of the same type, perform the compare and return the result. If elements are different types, check to see if
they are numbers.
 If numbers, perform numeric coercion if necessary and compare.
 If either element is a number, then the other element is "larger" (numbers are "smallest").
 Otherwise, types are sorted alphabetically by name.

If we reached the end of one of the tuples, the longer tuple is "larger." If we exhaust both tuples and share the same data, the
result is a tie, meaning that 0 is returned.
Example:

Nested Tuples:
Python allows you to define a tuple inside another tuple. This is called a nested tuple.

Output: (“RAVI”, “CSE”, 92.00)


(“RAMU”, “ECE”, 93.00)
(“RAJA”, “EEE”, 87.00)

Packing and unpacking tuples:


Packing is one of the things which sets tuples apart from lists.

Packing a tuple
Packing is a simple syntax which lets you create tuples "on the fly" without using the normal notation:

a = 1, 2, 3
This creates a tuple of 3 values and assigned it to a. Comparing this to the "normal" way:

a = (1, 2, 3)
OK, maybe it doesn't seem like much, but read on.

Unpacking a tuple
You can also go the other way, and unpack the values from a tuple into separate variables:

a = 1, 2, 3
x, y, z = a
After running this code, we will have x set to 1, y set to 2 and z set to 3. The value of the tuple a is unpacked into the 3
variables x, y and z. Note that the number of variables has to exactly match the number of elements in the tuple, or there will
be an error.

Real-life examples

105
Here is where it gets interesting. In the code above, the variable a is just used as a temporary store for the tuple. Why not
leave out the middle-man and do this:

x, y, z = 1, 2, 3
After running this code, as before, we will have x set to 1, y set to 2 and z set to 3.

Now it would be easy to look at that code and say, sure, Python has a special syntax for setting up multiple variables. But
that isn't what is really happening. First the values are packed into a tuple:

Next, the tuple is assigned to the left-hand side of the = sign:

Finally, the tuple is unpacked into the variables:

Here is another example:

a=5
b=7
b, a = a, b
So what does that do? At first, you might scratch your head and wonder what on earth is going on.

But in fact, it is quite simple. First, a and b get packed into a tuple. Then the tuple gets unpacked again, but this time into
variables b then a. So the values get swapped!

For a final example, let's see how tuple packing can be used with functions. A function is a bit of code that you can call to
calculate a value. It can only return a single value. In this case, it is today's date (as a string):

def getDate():
#Get the date from the system in some way
return(date)
We can call it like this:

s = getDate()
print(s)
Now suppose we wanted to create a function that returns the current screen position of the mouse cursor. Clearly, this
requires two values, the (x, y) position. Here is a neat way to do it:

def getMousePos():
#Get the mouse position the system in some way
return x, y

Do you recognise this? It is the tuple packing notation. x and y are packed into a tuple, which is a single value that can be
returned by the function.

When you call the function, you can do the same thing in reverse:

u, v = getMousePos()
print(u, v)
Here you are unpacking the two values into variables u and v. It might look as if Python has some special syntax for passing
back multiple values, but it doesn't … it is just tuples.

Tuple operations
Tuples use the same functions and constructs as lists, except of course you cannot do anything to modify a tuple.

106
Tuple slices
You can uses slices with tuples:

a = ['a', 'b', 'c', 'd', 'e']


y = a[1:4] #slice: ('b', 'c', 'd'), an list of elements 1, 2, and 3
If you take a slice of a tuple, you get a new tuple (and of course, if you take a slice of a list, you get a new list).

You cannot delete a slice of a tuple, because that would change the tuple itself, which isn't allowed - tuples are immutable.

Adding elements to a tuple


You cannot use append(), insert() or extend() to add extra elements to a tuple, because that would be changing the tuple.

You can add two tuples, because that just creates a new tuple (it doesn't change a or b):

a = (1, 2, 3)
b = (10, 20, 30)
c=a+b
print c #(1, 2, 3, 10, 20, 30)
You can do something a bit like the insert() function using slices:

a = (10, 20, 30, 40, 50)


x = a[:2] + ['apple', 'pear'] + a[2:] #x = (10, 20, 'apple', 'pear', 30, 40, 50)
Once again, this creates a new tuple, rather than modifying the existing tuple.

Finding elements
You can use the count() and index() functions to find elements in a tuple. You can use the in and not in operators to check
for membership. The len() function also works with tuples.

Removing elements
You cannot use remove(), del or clear() on a tuple, for the obvious reason, again, that you cannot change a tuple. You can
create a new tuple, with some of the elements removed.

Looping
The list looping techniques work perfectly well with tuples:

t = ('red', 'yellow', 'green', 'blue')


for x in t
print(x)
In case of emergency…
If you really must use list functions with a tuple, there is a function list() which will make a list out of anything it can,
including a tuple:

t = ('red', 'yellow', 'green', 'blue')


k = list(t)
[Link]()
print(k)

Even in this case, you are not actually changing the tuple, only the list copy of it.

Demonstration

Experiment-1: Python program for adding a Tuple to List and Vice-Versa.

107
Program to add a tuple to a list in Python
# Python program to add a tuple to list
# Creating the List
myList = [9, 3, 1, 4]
# Printing the List
print("Initially List : " + str(myList))
# Creating Tuple
myTuple = (2, 6)
# Adding the tuple to list
myList += myTuple
# Printing resultant List
print("List after Addition : " + str(myList))
Output:

Adding a list to a Tuple


Program:
# Python program to add a tuple to list
# Creating the List
myTuple = (9, 3, 1, 4)
# Printing the List
print("Tuple Initially : " + str(myTuple))
# Creating Tuple
myList = [2, 6]
# Adding the tuple to list
addList = list(myTuple)
addList += myList
myTuple = tuple(addList)
# Printing resultant List
print("Tuple after Addition : " + str(myTuple))
Output:

108
Experiment-2: Write a Python program to perform the summation of all elements of each tuple from
the list of tuples.

Program:
def test(lst):
result = map(sum, lst)
return list(result)
nums = ((1,2), (2,3), (3,4))
print("Original list of tuples:")
print(nums)
print("\nSum of all the elements of each tuple stored inside the said list of tuples:")
print(test(nums))
nums = ((1,2,6), (2,3,-6), (3,4), (2,2,2,2))
print("\nOriginal list of tuples:")
print(nums)
print("\nSum of all the elements of each tuple stored inside the said list of tuples:")
print(test(nums))
Output:

109
Experimentation

Experiment-3: Write a Python program to multiply adjacent elements of a tuple.

a tuple with integer elements. In our program, we need to create a tuple from the elements of the initial tuple where each
tuple is the product of the element at that index and next index.

Input:
(5, 1, 8, 3, 7)

Output:
(5, 8, 24, 21)

Method 1:
One method to solve the problem is by zipping the current element and the next one for each element of the tuple. Then
using the generator expression along with tuple method to create a tuple with the resulting values.

# Python program to multiply adjacent


# elements of a tuple

Step-1:# Initializing and printing tuple value


myTup = (5, 1, 8, 3, 7)
step-2:print str(myTup)
step-3:# Multiplying adjacent elements of the tuple
adjProd = tuple(val1 * val2 for val1, val2 in zip(myTup, myTup[1:]))
step-4:print str(adjProd)
Output:
The elements of tuple : (5, 1, 8, 3, 7)

110
The multiplication values are (5, 8, 24, 21)

Method 2:
Another method to solve the problem is by creating a map that uses a lambda function to multiply the current index element
and the next index element of the tuple and then convert this map to a tuple.

# Python program to multiply adjacent


# elements of a tuple
Step-1:# Initializing and printing tuple value
myTup = (5, 1, 8, 3, 7)
step-2:print str(myTup)
step-3:# Multiplying adjacent elements of the tuple
adjProd = tuple(map(lambda val1, val2 : val1 * val2, myTup[1:], myTup[:-1]))
step-4:print str(adjProd)
Output:
The elements of tuple : (5, 1, 8, 3, 7)
The multiplication values are (5, 8, 24, 21)

Experiment-4: Write a Python program to find the maximum element in the tuple list.

Here, we use the Tuple max function to return the largest Tuple item.
# Tuple Max Item
Step-1:intilise tuple
mxTuple = (3, 78, 67, 34, 88, 11, 23, 19)
step-2:#print list
print mxTuple
step-3:find max element with max() function and display
print max(mxTuple)

111
Lab 9:

Python Data Structures-Set: Creating a Set object, functions of set, Mathematical operations on
set, Membership Operators, Set Comprehension, Python Data Structures-Dictionary: Creating a
Dictionary Object, accessing data from the dictionary, updating dictionaries, Deleting from
dictionary, Functions on dictionary, dictionary comprehension

SET:
with a difference that sets are lists with no duplicate entries. Technically a set is a mutable and
unordered collection of items. This means that we can easily add or remove items fromit.
Creating a Set:
A set is created by placing all the elements inside curly brackets {}. Separated by comma or by using
the built-in function set( ).
Syntax:
Set_variable_name={var1, var2, var3, var4, …….}

Example:
s={1, 2.5, “abc” }
print (s) # display set( [ 1, 2.5, “abc” ] )
Converting a list into set:
A set can have any number of items and they may be of different data types. set()
function is used to converting list into set.
s=set( [ 1, 2.5, “abc” ] )
print (s)# display set( [ 1, 2.5, “abc” ])

We can also convert tuple or string into set.


tup= ( 1, 2, 3, 4, 5)
print set(tup) # set( [ 1, 2, 3, 4, 5 ] ) str=“HAPPY”
print (str)# set( [ 'i', 'h', 'm', 't', 'o' ])

Operations on set:

Sno Operation Result


1 len(s) number of elements in set s (cardinality)
2 x in s test x for membership in s
3 x not in s test x for non-membership in s
[Link](t) (or) test whether every element in s is in t
4 s <= t
[Link](t) (or) test whether every element in t is in s
5 s >= t

112
6 s==t Returns True if two sets are equivalent and returns False.
7 s!=t Returns True if two sets are not equivalent andreturns False.
[Link](t) (or) new set with elements from both s and t
8 s|t
[Link](t) (or) new set with elements common to s and t
9 s&t
[Link](t) (or) new set with elements in s but not in t
10 s-t
s.symmetric_difference(t) (or) new set with elements in either s or t but not both
11 s^t
12 [Link]() new set with a shallow copy of s
13 [Link](t) return set s with elements added from t
14 s.intersection_update(t) return set s keeping only elements also found in t
15 s.difference_update(t) return set s after removing elements found in t
16 s.symmetric_difference_update(t) return set s with elements from s or t but not both
17 [Link](x) add element x to set s
18 [Link](x) remove x from set s; raises KeyError if not present
19 [Link](x) removes x from set s if present
20 [Link]() remove and return an arbitrary element from s; raises KeyError if empty
21 [Link]() remove all elements from set s
22 max(s) Returns Maximum value in a set
23 min(s) Returns Minimum value in a set
24 sorted(s) Return a new sorted list from the elements in theset.

Note:
To create an empty set you cannot write s={}, because python will make this adirectory. Therefore, to
create an empty set use set( )function.

Updating a set:
s=set( )
printtype(s)# display <type„set‟>
s={}
printtype(s)#display<type„dict‟>

Since sets are unordered, indexing has no meaning. Set operations do not allow users to access or
change an element using indexing or slicing.

Dictionary:

A dictionary represents a group of elements arranged in the form of key-value pairs. The
firstelement is considered as „key‟and the immediate next element is taken as its“value‟. The key and
its value are separated by a colon (:). All the key-value pairs in a dictionary are inserted in curly braces
{}.
d= { „[Link]‟: 556, „Name‟:‟Mothi‟, „Branch‟: „CSE‟ }

Here, the name of dictionary is „dict‟. The first element in the dictionary is a string„[Link]‟. So, this
is called „key‟. The second element is 556 which is taken as its „value‟.

113
Example:
d={“[Link]‟:556,“Name‟:‟Mothi‟,“Branch‟:“CSE‟ }
printd[“[Link]‟]# 556
printd[“Name‟]# Mothi
printd[“Branch‟]# CSE

To access the elements of a dictionary, we should not use indexing or slicing. For example,
dict[0] or dict[1:3] etc. expressions will give error. To access the value associated with a key, we can
mention the key name inside the square braces, as: dict[„Name‟].
If we want to know how many key-value pairs are there in a dictionary, we can use the len( ) function,
as shown
d={“[Link]‟:556,“Name‟:‟Mothi‟,“Branch‟:“CSE‟ }
print len(d) # 3
We can also insert a new key-value pair into an existing dictionary. This is done by mentioning the key
and assigning a value to it.
d={'[Link]':556,'Name':'Mothi','Branch':'CSE'}
printd#{'Branch': 'CSE', 'Name': 'Mothi', '[Link]': 556}
d['Gender']="Male"
print(d) # {'Gender': 'Male', 'Branch': 'CSE', 'Name': 'Mothi', '[Link]': 556}

Suppose, we want to delete


a key-value pair from the dictionary, we can use del statementas:

del dict[„[Link]‟] #{'Gender': 'Male', 'Branch': 'CSE', 'Name': 'Mothi'}

To Testwhethera „key‟is available in a dictionary or not, we can use „in‟and „notin‟operators. These
operators return either True orFalse.
“Name‟in d # check if„Name‟ is akeyind andreturns True / False
We can use any datatypes for value. For example, a value can be a number, string, list, tuple or another
dictionary. But keys should obey the rules:
Keys should be unique. It means, duplicate keys are not allowd. If we enter same key again, the old key
will be overwritten and only the new key will beavailable.
emp={'nag':10,'vishnu':20,'nag':20} print emp # {'nag': 20, 'vishnu': 20}

Keys should be immutable type. For example, we can use a number, string or tuples as keys since they
are immutable. We cannot use lists or dictionaries as keys. If they are used as keys, we will
get“TypeError‟.

114
emp={['nag']:10,'vishnu':20,'nag':20}
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module> emp={['nag']:10,'vishnu':20,'nag':20}
TypeError: unhashable type: 'list'

Dictionary Methods:
Method Description
[Link]() Removes all key-value pairs from dictionary„d‟.
d2=[Link]() Copies all elements from„d‟ into a new dictionary d2.
[Link](s [,v] ) Create a new dictionary with keys from the sequence„s‟ and
values all set to „v‟.
[Link](k [,v] ) Returns the value associated with key „k‟. If key is not
found, it returns „v‟.
[Link]() Returns an object that contains key-value pairs of„d‟. The
pairs are stored as tuples in the object.
[Link]() Returns a sequenceof keysfrom the dictionary„d‟.
[Link]() Returns a sequence of values from the dictionary„d‟.
[Link](x) Addsall elements from dictionary„x‟to„d‟.
Removesthekey„k‟anditsvaluefrom„d‟andreturnsthe [Link] keyis not
[Link](k [,v] ) found, then the value „v‟ is [Link] keyis not foundand „v‟isnot
mentioned then „KeyError‟
is raised.
[Link](k [,v] ) Ifkey„k‟ is found, itsvalueis [Link] keyis not
found, then thek, v pair isstored into the dictionary„d‟.

Using for loop with Dictionaries:


[Link]‟stakeasimple dictionary that contains
color code and its nameas:
colors = { 'r':"RED", 'g':"GREEN", 'b':"BLUE", 'w':"WHITE" }
Here, “r‟, “g‟, “b‟and “w” are represents keys and „RED‟,„GREEN‟,„BLUE‟ and „WHITE‟indicate
values.

colors = { 'r':"RED", 'g':"GREEN", 'b':"BLUE", 'w':"WHITE" }


for k incolors:
print k # displays only keys for k incolors:
print colors[k] # keys to to dictionary and display the values

Converting Lists into Dictionary:


When we have two lists, it is possible to convert them into a dictionary. For example, we have
two lists containing names of countries and names of their capital cities.
There are two steps involved to convert the lists into a dictionary. The first step is to create a „zip‟ class
object by passing the two lists to zip( ) function. The zip( ) function is useful to convert the sequences

115
into a zip class object. The second step is to convert the zip object into a dictionary by using dict( )
function.
Example:
countries = [ 'USA', 'INDIA', 'GERMANY', 'FRANCE' ]
cities = [ 'Washington', 'New Delhi', 'Berlin', 'Paris' ] z=zip(countries, cities)
d=dict(z) print d

Output:
{'GERMANY': 'Berlin', 'INDIA': 'New Delhi', 'USA': 'Washington', 'FRANCE': 'Paris'}

converting Strings into Dictionary:

When a string is given with key and value pairs separated by some delimiter like a comma ( , ) we can
convert the string into a dictionary and use it as dictionary.

s="Vijay=23,Ganesh=20,Lakshmi=19,Nikhil=22" s1=[Link](',')
s2=[]
d={}
for i in s1: [Link]([Link]('='))
print (d)

Output:
{'Ganesh': '20', 'Lakshmi': '19', 'Nikhil': '22', 'Vijay': '23'}

Q) A Python program to create a dictionary and find the sum of values.

Q) A Python program to create a dictionary with cricket player’s names and scores in a match.
Also we are retrieving runs by entering the player’s name.

116
Demonstration:
Experiment-1. Write a Python program to perform set operations.

Experiment-2: Write a program to print different vowels present in the given word?

117
Experiment-3: Write a Python program to generate powers of 2 using set comprehensions.

Experiment-4:
Experiment-4:Write
Writeaaprogram
programtotoeliminate
eliminateduplicates
duplicatespresent
presentininthe
thelist
listusing
usingset
set?

118
Experiment-5:
Experiment-5:Write
WriteaaPython
Pythonprogram
programtotoenter
entername
nameand
andpercentage
percentagemarks
marksininaadictionary
dictionaryand
and
display information on the console.
display information on the console.?

Program:

119
Experiment
Experiment 6:6: Write
Write a program
a program toto take
take a dictionary
a dictionary from
from the
the keyboard
keyboard and
and print
print the
the sum
sum ofof
values?
values?

120
Experimentation:

Experiment-7:
Experiment-7: Write
Write a program
a program to find
to find the number
the number of occurrences
of occurrences ofletter
of each each present
letter present
in the in the
given
given string
string using
using a dictionary.
a dictionary.

Step1:initializing string
Step2:using set() + count() to get count of each element in string
Step3: printing result

Expected output:
Occurrence of all characters in well come to cmrcetis :
{'w': 1, 'e': 3, 'l': 2, ' ': 3, 'c': 3, 'o': 2, 'm': 2, 't': 2, 'r': 1}

Experiment-8:
Experiment-8:Write
Writeaaprogram
programtotoaccept
acceptstudent
studentname
nameand
andmarks
marksfrom
fromthe
thekeyboard
keyboardand
and creates a
creates a dictionary. Also display student marks by taking student name
dictionary. Also display student marks by taking student name as input? as input?

Step1: as follow the experiment 5 and show the output

121
Lab 10:
Python Modules-Creating Modules, Accessing members, module aliasing, member aliasing,
reloading a module,
The special variable: __name___. Working with Math, random modules, Python
[Link]-File Handling-Types of Files, Opening a file, closing a file, properties of File
object, writing data to text file, Reading character data from text files, seek (), tell() functions.)

Python 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 [Link] which contains a function func that contains
a code to print some message on the console.

Let's create the module named as [Link].


#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.
The import statement
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.

122
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 [Link], 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?")
[Link](name)

Output:
Enter the name?John
Hi John

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.
[Link]:
#place the code in the [Link]
def summation(a,b):
return a+b

def multiplication(a,b):
return a*b;
def divide(a,b):
return a/b;
[Link]:
from calculation import summation

#it will import only the summation() from [Link]


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 s
ummation()

Output:
Enter the first number10

123
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 = ",[Link](a,b))

Output:
Enter a?10
Enter b?20
Sum = 30

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

124
'_default_decoder', '_default_encoder', 'decoder', 'dump', 'dumps',
'encoder', 'load', 'loads', 'scanner']

The reload() function:


As we have already stated that, a module is loaded once regardless of the number of times it is
imported into the python source file. However, if you want to reload the already imported module to re-
execute the top-level code, python provides us the reload() function.
The syntax to use the reload() function is given below.
reload(<module-name>)

for example, to reload the module calculation defined in the previous example, we must use the
following line of code.
reload(calculation)

Scope of variables:
In Python, variables are associated with two types of scopes. All the variables defined in a
module contain the global scope unless or until it is defined within a function.

All the variables defined inside a function contain a local scope that is limited to this function itself. We
can not access a local variable globally.

If two variables are defined with the same name with the two different scopes, i.e., local and global,
then the priority will always be given to the local variable.

Consider the following example.


Example
name = "john"
def print_name(name):
print("Hi",name) #prints the name that is local to this function only.
name = input("Enter the name?")
print_name(name)

Output:
Hi David

Python packages :
The packages in python facilitate the developer with the application development environment
by providing a hierarchical directory structure where a package contains sub-packages, modules, and
sub-modules. The packages are used to categorize the application level code efficiently.

Let's create a package named Employees in your home directory. Consider the following steps.
1. Create a directory with name Employees on path /home.
2. Create a python source file with name [Link] on the path /home/Employees.

[Link]

125
def getITNames():
List = ["Varun", "Joel", "Shailu", "Snigdha"]
return List;

3. Similarly, create one more python file with name [Link] and create a function
getBPONames().

4. Now, the directory Employees which we have created in the first step contains two python modules.
To make this directory a package, we need to include one more file here, that is __init__.py which
contains the import statements of the modules defined in this directory.
__init__.py
from ITEmployees import getITNames
from BPOEmployees import getBPONames

5. Now, the directory Employees has become the package containing two python modules. Here we
must notice that we must have to create __init__.py inside a directory to convert this directory to a
package.

6. To use the modules defined inside the package Employees, we must have to import this in our
python source file. Let's create a simple python source file at our home directory (/home) which uses
the modules defined in this package.

[Link]
import Employees
print([Link]())

Output:
[‘Varun’, ‘Joel’, ‘Shailu’, ’Snigdha’]

Aliasing with ‘as’ keyword:


In Python, the as keyword can be used to give an alternative name as an alias for a Python module or
function.

# Aliasing [Link] as plt


from matplotlib import pyplot as plt
[Link](x, y)

# Aliasing calendar as c
import calendar as c
print(c.month_name[1])

Aliasing in Python :
In python programming, the second name given to a piece of data is known as an alias. Aliasing
happens when the value of one variable is assigned to another variable because variables are just names
that store references to actual value.

126
Consider a following example:

first_variable = "PYTHON"
print("Value of first:", first_variable)
print("Reference of first:", id(first_variable))
print("--------------")
second_variable = first_variable # making an alias
print("Value of second:", second_variable)
print("Reference of second:", id(second_variable))

In the example above, first_variable is created first and then string ‘PYTHON’ is assigned to it.
Statement first_variable = second_variable creates an alias of first_variable because first_variable =
second_variable copies reference of first_variable to second_variable.

To verify, let’s have look at the output of the above program:

Value of first_variable: PYTHON


Reference of first_variable: 2904215383152
--------------
Value of second_variable: PYTHON
Reference of second_variable: 2904215383152
From the output of the above program, it is clear that first_variable and second_variable have the same
reference id in memory.
Python math Module
Python Math Module:
Mathematical calculations may occasionally be required when dealing with certain fiscal or
rigorous scientific tasks. Python has a math module that can handle these complex calculations. Both
simple mathematical calculations like addition (+), and subtraction (-), and advanced mathematical
calculations like trigonometric operations, and logarithmic operations can be performed by the
functions in the math module.

This tutorial teaches us about applying the math module from fundamentals to more advanced concepts
with the support of easy examples to understand the concepts fully. We have included the list of all
built-in functions defined in this module for better understanding.

What is Math Module in Python?


Python has a built-in math module. It is a standard module, so we don't need to install it
separately. We only have to import it into the program we want to use. We can import the module, like
any other module of Python, using import math to implement the functions to perform mathematical
operations.

Since the source code of this module is in the C language, it provides access to the functionalities of the
underlying C library. For instance,

127
Code

# This program will show the calculation of square root using the math module
# importing the math module
import math
print([Link]( 9 ))
Output:

3.0
This Python module does not accept complex data types. The more complicated equivalent is the cmath
module.

We can, for example, calculate all trigonometric ratios for any given angle using the built-in functions
in the math module. We must provide angles in radians to these trigonometric functions (sin, cos, tan,
etc.). However, we are accustomed to measuring angles in terms of degrees. The math module provides
two methods to convert angles from radians to degrees and vice versa.

Constants in Math Module :


The value of numerous constants, including pi and tau, is provided in the math module so that we do
not have to remember them. Using these constants eliminates the need to precisely and repeatedly write
down the value of each constant. The math module includes the following constants:

Euler's Number
Tau
Infinity
Pi
Not a Number (NaN)
Let's go over each of them one by one.

Euler's Number
The value 2.71828182845 of Euler's number is returned by the math.e constant.

Syntax of this is:

math.e
Code

# importing the required library


import math

# printing the value of Euler's number using the math module


print( "The value of Euler's Number is: ", math.e )

128
Output:

The value of Euler's Number is: 2.718281828459045


Tau
The ratio of a circle's circumference to its radius is known as tau. The value tau returned by the tau
constant is 6.283185307179586.

Syntax of this is:

[Link]
Code

# Importing the required library


import math

# Printing the value of tau using math module


print ( "The value of Tau is: ", [Link] )
Output:

The value of Tau is: 6.283185307179586


Infinity
Infinity refers to anything limitless or never-ending in both directions of the actual number line.
Numbers cannot adequately represent it. The [Link] returns positive infinity constant. We can use -
[Link] to print negative infinity.

Syntax of this is:

[Link]
Code

# Importing the required library


import math

# Printing the value of positive infinity using the math module


print( [Link] )

# Printing the value of negative infinity using the math module


print( -[Link] )
Output:

inf
-inf

129
Further, we are comparing a very large floating-point number with positive and negative infinity
values.

Code

# Importing the required library


import math

# comparing the value of infinity


print( [Link]> 10e109 )
print( -[Link]< -10e109 )
Output:

True
True
Pi
Pi is known to everyone. It is mathematically represented as either the fraction 22/7 or the decimal
number 3.14. [Link] gives the most accurate value of pi.

Syntax of this is:

[Link]
Code

# Importing the required library


import math

# Printing the value of pi using the math module


print( "The value of pi is ", [Link] )
Output:

The value of pi is 3.141592653589793


Let us calculate the circumference of a circle.

Code

# Importing the required library


import math

# radius of the circle


r=4

# value of pi
pi_value = [Link]

130
# circumference of the circle
print(2 * pi_value * r)
Code

25.132741228718345
NaN
The [Link] gives us a floating-point nan (Not a Number) value. This amount is not a valid numeric
value. Float("nan") and the nan constant are comparable.

Code

# Importing the required library


import math

# Printing the value of nan using the math module


print( [Link] )
Output:

nan
Mathematical Operations with Math Module
The functions that are required in representation theory and number theory, such as calculating the
factorial of an integer, will be covered in this part.

Calculating the Ceiling and the Floor Value


The terms "ceiling value" and "floor value" refer to the smallest integral value larger than the number
and the largest integral value less than the number, respectively. The ceil() and floor() methods simplify
calculating this.

Code

# Python program to show how to use floor() and ceil() functions.

# importing the math module


import math

x = 4.346

# returning the ceiling value of 4.346


print("The ceiling value of 4.346 is : ", end="")
print( [Link](x) )

# returning the floor value of 4.346


print("The floor value of 4.346 is : ", end="")
print( [Link](x) )

131
Output:

The ceiling value of 4.346 is : 5


The floor value of 4.346 is : 4
Calculating the Factorial of the Number
We may determine the factorial of a given integer in a one-liner code by using the [Link]()
function. The Python interpreter will send a message if the given number is not integral.

Code

# Python program to show how to use function() functions.

# importing the math module


import math

x=6

# returning the factorial of 6


print( "The factorial of 6 is : ", [Link](x) )

# passing a non integral number


try:
print( "The factorial of 6.5 in: ", [Link](6.5) )
except:
print( "Cannot calculate factorial of a non-integral number" )
Output:

The factorial of 6 is : 720


Cannot calculate factorial of a non-integral number
Calculating the Absolute Value
The method [Link]() returns the absolute number of the number given to the function.

Code

# Python program to show how to use fabs() functions.

# importing the math module


import math

x = -45

# returning x's absolute value.


print( "The absolute value of -45 is: ", [Link](x) )
Output:

132
The absolute value of -45 is: 45.0
Calculating the Exponential
x to the power of e, often known as the exponential of a number x, is calculated using the exp()
function.

Code

# Python program to show how to use the exp() function.

# importing the math module


import math

# declaring some value


num1 = 4
num2 = -3
num3 = 0.00

# passing above values to the exp() function


print( f"Theexponenetial value of {num1} is: ", [Link](num1) )
print( f"Theexponenetial value of {num2} is: ", [Link](num2) )
print( f"Theexponenetial value of {num3} is: ", [Link](num3) )
Output:

The exponenetial value of 4 is: 54.598150033144236


The exponenetial value of -3 is: 0.049787068367863944
The exponenetial value of 0.0 is: 1.0
Calculating the Power of a Number
x**y is computed via the pow() function. This function calculates the value of the power after
converting its inputs into floats.

Code

# Python program to show how to use the pow() function.

# importing the math module


import math

x=4
y=5
# returning x to the power of y.
print( f"The value of {x} to the power of {y} is: ", [Link](x,y) )
Output:

The value of 4 to the power of 5 is: 1024.0


Calculating Sine, Cosine, and Tangent

133
The values of sine, cosine, and tangent of an angle, which are supplied as an input to the function, are
returned by the sin(), cos(), and tan() methods. This function expects a value that is provided in radians.

Code

# Python program to show how to use the sin(), cos(), tan() function.

# importing the math module


import math

angle = [Link] / 4

# returning the sine of pi/4


print( "The sine of pi/4 is : ", [Link]( angle ) )

# returning the cosine of pi/4


print( "The cosine of pi/4 is : ", [Link]( angle ) )

# returning the tangent of pi/4


print("The tangent of pi/4 is : ", [Link]( angle ))
Output:

The sine of pi/4 is : 0.7071067811865475


The cosine of pi/4 is : 0.7071067811865476
The tangent of pi/4 is : 0.9999999999999999
The dir( ) Function
A sorted list of strings comprising the identifiers of the functions defined by a module is what the built-
in method dir() delivers.

The list includes the names of modules, each specified constants, functions, and methods. Here is a
straightforward illustration:

Code

# Importing the math module


import math

functions = dir(math)
print( functions )
Output:

['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan',
'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs',
'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan',

134
'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow',
'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc', 'ulp']

Description of all the Functions in Python Math Module

Here is a list of all the properties and functions specified in the math module, along with a brief
description of what each one does.

Function Description

ceil(x) The lowest integer bigger than or equal to x is returned.

copysign(x, gives x back with the sign of y.


y)

fabs(x) gives x's absolute value back.

factorial(x) provides the x factorial back.

floor(x) gives back the biggest integer that is less than or equal to x.

fmod(x, y) returns the leftover value after dividing x by y.

frexp(x) returns the pair of the mantissa and exponent of x. (m, e)

fsum(iterab returns the iterable's correct floating point sum of all values.
le)

isfinite(x) If x is neither an infinity nor a NaN, it returns True (Not a Number)

isinf(x) If x is a positive or negative infinity, it returns True.

isnan(x) If x is a NaN, it returns True.

ldexp(x, i) gives back x * (2**i).

modf(x) gives x's fractional and integer components back.

trunc(x) x's shortened integer value is returned.

exp(x) delivers e**x

135
expm1(x) yields e**x - 1

log(x[, b]) gives back the x logarithm in base b. (defaults to e)

log1p(x) the natural logarithm of 1 + x is returned.

log2(x) gives x's base-2 logarithm back.

log10(x) provides x's base-10 logarithm.

pow(x, y) gives x raised to the power of y back.

sqrt(x) gives x's square root back.

acos(x) gives the arc cosine of x back.

asin(x) gives the arc sine of x back.

atan(x) gives the arc tangent of x back.

atan2(y, x) gives back atan(y / x).

cos(x) returns the x's cosine.

hypot(x, y) returns sqrt(x*x + y*y), the Euclidean norm.

sin(x) gives the sine of x back.

tan(x) gives the tangent of x back.

degrees(x) Angle x is transformed from radians to degrees.

radians(x) Angle x is transformed from degrees to radians.

acosh(x) x's inverse hyperbolic cosine is returned.

asinh(x) x's inverse hyperbolic sine is returned.

atanh(x) x's inverse hyperbolic tangent is returned.

cosh(x) gives x's hyperbolic cosine.

sinh(x) gives x's hyperbolic cosine.

tanh(x) gives x's hyperbolic tangent back.

136
erf(x) the error function at x is returned.

erfc(x) a function that gives the complementary error at x

gamma(x) the Gamma function at x is returned.

lgamma(x) gives the natural logarithm of the gamma function's absolute


value at x.

pi The ratio of a circle's circumference to its diameter is a


mathematical constant (3.14159...)

e e is a constant in mathematics (2.71828...)

Python Random Module:


Python Random module is an in-built module of Python which is used to generate random
numbers. These are pseudo-random numbers means these are not truly random. This module can be
used to perform random actions such as generating random numbers, print random a value for a list or
string, etc.

Example: Printing a random value from a list


# import random
import random

# prints a random value from the list


list1 = [1, 2, 3, 4, 5, 6]
print([Link](list1))

output:
2

Creating random integers:


# Python3 program explaining work
# of randint() function

# import random module


import random

# Generates a random number between


# a given positive range
r1 = [Link](5, 15)
print("Random number between 5 and 15 is % s" % (r1))

137
# Generates a random number between
# two given negative range
r2 = [Link](-10, -2)
print("Random number between -10 and -2 is % d" % (r2))

Output:
Random number between 5 and 15 is 7
Random number between -10 and -2 is -9

Python File Handling :

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.
We will learn all about file handling in python including,
creating a file,
opening a file,
closing a file,
Reading, Writing and appending the file, etc.

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
2 rb
the 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.

138
It opens the file to write only. It overwrites the file if previously exists or creates a new
5 w
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 only in binary format. It overwrites the file if it exists previously
6 wb or 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
11 a+
file 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.
It opens a file in exclusive mode, only for write operation. It causes an error a file exists
13 X
with the same name..
It opens a file in exclusive mode, only for binary write operation. It causes an error a file
14 xb
exists with the same name..

Let's look at the simple example to open a file named "[Link]" (stored in the same directory) in read
mode and printing its content on the console.

Example
#opens the file [Link] in read mode
fileptr = open("[Link]","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.

139
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.

[Link]()

Consider the following example.

Example
# opens the file [Link] in read mode
fileptr = open("[Link]","r")

if fileptr:
print("file is opened successfully")

#closes the opened file


[Link]()

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.

[Link](<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 [Link] in read mode. Causes error if no such file exists.
fileptr = open("[Link]","r");

#stores all the data of the file into the variable content
content = [Link](9);

# prints the type of the data stored in the file


print(type(content))

#prints the content of the file


print(content)

140
#closes the opened file
[Link]()

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
"[Link]" containing three lines.

Example
#open the [Link] in read mode. causes error if no such file exists.
fileptr = open("[Link]","r");

#stores all the data of the file into the variable content
content = [Link]();

# 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


[Link]()

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 [Link] in read mode. causes an error if no such file exists.
fileptr = open("[Link]","r");

#running a for loop


for i in fileptr:
print(i) # i contains each line of the file

141
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 [Link] in append mode. Creates a new file if no such file exists.
fileptr = open("[Link]","a");

#appending the content to the file


[Link]("Python is the modern day language. It makes things so simple.")
#closing the opened file
[Link]();
Now, we can see that the content of the file is modified.

[Link]:
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 [Link] in write mode.
fileptr = open("[Link]","w");

#overwriting the content of the file


[Link]("Python is the modern day language. It makes things so simple.")

#closing the opened file


[Link]();
Now, we can check that all the previously written content of the file is overwritten with the new text we
have passed.

[Link]:
Python is the modern day language. It makes things so simple.

142
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 [Link] in read mode. causes error if no such file exists.
fileptr = open("[Link]","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. It is useful in the case of manipulating the
files. It 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("[Link]",'r') as f:
content = [Link]();
print(content)

Output:
Python is the modern day language. It makes things so simple.

143
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 [Link] in read mode
fileptr = open("[Link]","r")

#initially the filepointer is at 0


print("The filepointer is at byte :",[Link]())

#reading the content of the file


content = [Link]();

#after the read operation file pointer modifies. tell() returns the location of the fileptr.

print("After reading, the filepointer is at:",[Link]())

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 [Link] in read mode

144
fileptr = open("[Link]","r")

#initially the filepointer is at 0


print("The filepointer is at byte :",[Link]())

#changing the file pointer location to 10.


[Link](10);

#tell() returns the location of the fileptr.


print("After reading, the filepointer is at:",[Link]())

Output:
The filepointer is at byte : 0
After reading, the filepointer is at 10

Python osmodule OR Built in Modules


The os module provides us the functions that are involved in file processing operations like
renaming, deleting, etc.
Let's look at some of the os module functions.

Renaming the file

The os module provides us the rename() method which is used to rename the specified file to a new
name.

The syntax to use the rename() method is given below.

rename(?current-name?, ?new-name?)
Example
import os;

#rename [Link] to [Link]


[Link]("[Link]","[Link]")

Removing the file

The os module provides us the remove() method which is used to remove the specified file. The syntax
to use the remove() method is given below.
remove(?file-name?)

Example
import os;
#deleting the file named [Link]
[Link]("[Link]")
Creating the new directory

145
The mkdir() method is used to create the directories in the current working directory. The syntax to
create the new directory is given below.
mkdir(?directory name?)

Example
import os;

#creating a new directory with the name new


[Link]("new")

Changing the current working directory


The chdir() method is used to change the current working directory to a specified directory.
The syntax to use the chdir() method is given below.
chdir("new-directory")
Example
import os;

#changing the current working directory to new

[Link]("new")

The getcwd() method

This method returns the current working directory.


The syntax to use the getcwd() method is given below.
[Link]()

Example
import os;

#printing the current working directory


print([Link]())

Deleting directory

The rmdir() method is used to delete the specified directory.


The syntax to use the rmdir() method is given below.
[Link](?directory name?)

Example
import os;

#removing the new directory


[Link]("new")

146
Writing python output to the files
In python, there are the requirements to write the output of a python script to a file.
The check_call() method of module subprocess is used to execute a python script and write the output
of that script to a file.
The following example contains two python scripts. The script [Link] executes the script [Link] and
writes its output to the text file [Link]
[Link]:
temperatures=[10,-20,-289,100]
def c_to_f(c):
if c< -273.15:
return "That temperature doesn't make sense!"
else:
f=c*9/5+32
return f
for t in temperatures:
print(c_to_f(t))

[Link]:
import subprocess

with open("[Link]", "wb") as f:


subprocess.check_call(["python", "[Link]"], stdout=f)
Output:
50
-4
That temperature doesn't make sense!
212

The file related methods

The file object provides the following methods to manipulate the files on various operating systems.
SN Method Description
It closes the opened file. The file once closed, it can't be read or write any
1 [Link]()
more.
2 [Link]() It flushes the internal buffer.
It returns the file descriptor used by the underlying implementation to
3 [Link]()
request I/O from the OS.
It returns true if the file is connected to a TTY device, otherwise returns
4 [Link]()
false.
5 [Link]() It returns the next line from the file.
6 [Link]([size]) It reads the file for the specified size.
7 [Link]([size]) It reads one line from the file and places the file pointer to the beginning of

147
the new line.
It returns a list containing all the lines of the file. It reads the file until the
8 [Link]([sizehint])
EOF occurs using readline() function.
It modifies the position of the file pointer to a specified offset with the
9 [Link](offset[,from)
specified reference.
10 [Link]() It returns the current position of the file pointer within the file.
11 [Link]([size]) It truncates the file to the optional specified size.
12 [Link](str) It writes the specified string to a file
13 [Link](seq) It writes a sequence of the strings to a file.

Demonstration

Experiment-1: Create a module [Link] containing Fibonacci(n) function(s) and import fibo module
in a python script to print Fibonacci series upto n.
Program:
Folder Layout:

Step-1-create folder fib and it’s consist following two following files [Link] and __main__.py that
mentioned below

Output:

148
Experiment-2: Write a python program to print all the contents of a given module.
Program:
# Import libraries
import os
import time
# Insert the directory path in here
path="C:/Users/CMR/Desktop/pp"
# Extracting all the contents in the directory corresponding to path
l_files = [Link](path)
# Iterating over all the files
for file in l_files:
# Instantiating the path of the file
file_path = f'{path}\\{file}'
# Checking whether the given file is a directory or not
if [Link](file_path):
try:
# Printing the file pertaining to file_path
[Link](file_path, 'print')
print(f'Printing {file}')

# Sleeping the program for 5 seconds so as to account the


# steady processing of the print operation.
[Link](5)
except:
# Catching if any error occurs and alerting the user

149
print(f'ALERT: {file} could not be printed! Please check\
the associated softwares, or the file type.')
else:
print(f'ALERT: {file} is not a file, so can not be printed!')

print('Task finished!')
Output:

Experiment-3: Write a python program to create a package containing two or modules.


Create following program structure and programs:

150
Program’s:

__main__.py:

Output:

151
Experiment-4:
Experiment-4:Write
Writea python program
a python to import
program module
to import from afrom
module package createdcreated
a package in Experiment-3.
in Experiment-3.

Program:

Output:

152
Experimentation
Experiment-5: Write a Python program to check whether the given file exists or not. If it is available
then print its content?
Approach:
Example
Step-1:#open the [Link] in read mode. Causes error if no such file exists.
fileptr = open("[Link]","r");

step-2:#stores all the data of the file into the variable content
content = [Link](9);

step-3: # prints the type of the data stored in the file


print type(content)

step-4:#prints the content of the file


print content

step-5:#closes the opened file


fileptr close()

Experiment-6: Write a python Program to print the number of lines,words and characters present
in the given file?

Approach:
# Python implementation to compute
# number of characters, words, spaces
# and lines in a file

Step-2 # Function to count number


# of characters, words, spaces
# and lines in a file
def counter(fname):

# variable to store total word count


num_words = 0

# variable to store total line count


num_lines = 0

# variable to store total character count


num_charc = 0

# variable to store total space count

153
num_spaces = 0

Step-3 # opening file using with() method


# so that file gets closed
# after completion of work
with open(fname, 'r') as f:

Step-4 # loop to iterate file


# line by line
for line in f:

Step-5 # incrementing value of


# num_lines with each
# iteration of loop to
# store total line count
num_lines += 1

Step-6 # declaring a variable word


# and assigning its value as Y
# because every file is
Step-7 # supposed to start with
# a word or a character
word = 'Y'

Step-8 # loop to iterate every


# line letter by letter
for letter in line:

Step-9 # condition to check


# that the encountered character
# is not white space and a word
if (letter != ' ' and word == 'Y'):

# incrementing the word


# count by 1
num_words += 1

# assigning value N to
# variable word because until
# space will not encounter
# a word can not be completed
word = 'N'

Step-10 # condition to check


# that the encountered character

154
# is a white space
elif (letter == ' '):

Step-11 # incrementing the space


# count by 1
num_spaces += 1

Step-12 # assigning value Y to


# variable word because after
# white space a word
# is supposed to occur
word = 'Y'

Step-13 # loop to iterate every


# letter character by
# character
for i in letter:

Step-14 # condition to check


# that the encountered character
# is not white space and not
# a newline character
if(i !=" " and i !="\n"):

# incrementing character
# count by 1
num_charc += 1

Step-15 # printing total word count


print("Number of words in text file: ",
num_words)

Step-16 # printing total line count


print("Number of lines in text file: ",
num_lines)

Step-17 # printing total character count


print('Number of characters in text file: ',
num_charc)

# printing total space count


print('Number of spaces in text file: ',
num_spaces)

Step -1# Driver Code:

155
if __name__ == '__main__':
fname = '[Link]'
try:
counter(fname)
except:
print('File not found')

Experiment-7:
Experiment-7:Program to read
Program image
to read file file
image and and
writewrite
to a new
to a image file? file?
new image

Approach -1:
Using ImageIO :Imageio is a Python library that provides an easy interface to read and write a wide
range of image data, including animated images, video, volumetric data, and scientific formats.
# Python program to read an write an image
Step-1:#import imageio module
import imageio as iio

step-2:# read an image with imread function


img = [Link]("[Link]")

step-3:# write it in a new format


[Link]("firstjpg", img)

Experiment-8: Write a python program to read and write to a CSV file.

Approach:
What Is a CSV File?
A CSV file (Comma Separated Values file) is a type of plain text file that uses specific structuring to
arrange tabular data. Because it’s a plain text file, it can contain only actual text data—in other words,
printable ASCII or Unicode characters.

The structure of a CSV file is given away by its name. Normally, CSV files use a comma to separate
each specific data value. Here’s what that structure looks like:

column 1 name,column 2 name, column 3 name


first row data 1,first row data 2,first row data 3
second row data 1,second row data 2,second row data 3
...
Notice how each piece of data is separated by a comma. Normally, the first line identifies each piece of
data—in other words, the name of a data column. Every subsequent line after that is actual data and is
limited only by file size constraints.

156
In general, the separator character is called a delimiter, and the comma is not the only one used. Other
popular delimiters include the tab (\t), colon (:) and semi-colon (;) characters. Properly parsing a CSV
file requires us to know which delimiter is being used.

Example:

Consider the below CSV file –

Step-1:#Load import csv

Step-2:# opening the CSV file


with open('[Link]', mode ='r')as file:

Step-3:# reading the CSV file


csvFile = [Link](file)

Step-4 # displaying the contents of the CSV file


for lines in csvFile:
print(lines)
Output:

[['Steve', 13, 'A'],


['John', 14, 'F'],
['Nancy', 14, 'C'],
['Ravi', 13, 'B']]

157

You might also like