Python Programming Basics and Examples
Python Programming Basics and Examples
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?
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
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.
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 –
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.
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.
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.
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:
15
Click here on the next 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.
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
21
To run the python IDE
22
Experimentation:
Experiment 3: Explore various IDEs for python program development.
Experiment 3: Explore various IDEs for python program development.
4.
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
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
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
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
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:
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.
>>>input()Hell
o'Hello'
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
print('Hello')
OUTPUT:Hello
DisplayingOutputwiththePrintFunction:
The print( ) function prints the given object to the standard output device (screen) or tothetext stream
file.
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
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:
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-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:
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.
Lab 4:
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.
if:
if-else:
Nested if:
elif:
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.
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
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 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.
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.
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).
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
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.
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
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)
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.
break
continue
pass
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.
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
Output:
0 1 2 3 4 5 6 7 8 9 came out of while loop
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.
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.
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
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.
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
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
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.
#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
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'
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.
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.
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
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)
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:
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.
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.
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.
Outputelcome to CodeRepublics
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.
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
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
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-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
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)
Hello
Hello
Hello
Hello, welcome to
the world of Python
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).
#first character
print('str[0] = ', str[0])
#last character
print('str[-1] = ', str[-1])
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.
If we want to access a range, we need the index that will slice the portion from the string.
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.
To learn more about the data types available in Python visit: Python Data Types
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.
# 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:
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.
3 letters found
String Membership Test
We can test if a substring exists within a string or not, using the keyword in.
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.
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:
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.
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
# default(implicit) order
default_order = "{}, {} and {}".format('John','Bill','Sean')
print('\n--- Default Order ---')
print(default_order)
90
print(positional_order)
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.
>>> 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"""
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”]
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
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.
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
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
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])
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])
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.
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.
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.
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.
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:
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:
You cannot delete a slice of a tuple, because that would change the tuple itself, which isn't allowed - tuples are immutable.
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:
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:
Even in this case, you are not actually changing the tuple, only the list copy of it.
Demonstration
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:
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
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.
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.
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” ])
Operations on set:
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}
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‟.
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'}
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 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?
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.
Here, we need to include this module into our main module to call the method displayMsg() defined in
the module named file.
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
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
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 *.
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.
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
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']
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.
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 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.
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.
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.
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.
math.e
Code
128
Output:
[Link]
Code
[Link]
Code
inf
-inf
129
Further, we are comparing a very large floating-point number with positive and negative infinity
values.
Code
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.
[Link]
Code
Code
# 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
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.
Code
x = 4.346
131
Output:
Code
x=6
Code
x = -45
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
Code
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:
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.
angle = [Link] / 4
The list includes the names of modules, each specified constants, functions, and methods. Here is a
straightforward illustration:
Code
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']
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
floor(x) gives back the biggest integer that is less than or equal to x.
fsum(iterab returns the iterable's correct floating point sum of all values.
le)
135
expm1(x) yields e**x - 1
136
erf(x) the error function at x is returned.
output:
2
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
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.
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
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.
[Link]()
Example
# opens the file [Link] in read mode
fileptr = open("[Link]","r")
if fileptr:
print("file is opened successfully")
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.
[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);
140
#closes the opened file
[Link]()
Output:
<class 'str'>
Hi, I am
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]();
Output:
<class 'str'>
Hi, I am the file and being used as
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");
141
Output:
Hi, I am the file and being used as
an example to read a
file in python.
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");
[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");
[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
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")
#after the read operation file pointer modifies. tell() returns the location of the fileptr.
Output:
The filepointer is at byte : 0
After reading, the filepointer is at 26
<file-ptr>.seek(offset[, from)
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.
144
fileptr = open("[Link]","r")
Output:
The filepointer is at byte : 0
After reading, the filepointer is at 10
The os module provides us the rename() method which is used to rename the specified file to a new
name.
rename(?current-name?, ?new-name?)
Example
import os;
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;
[Link]("new")
Example
import os;
Deleting directory
Example
import os;
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
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}')
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:
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);
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
153
num_spaces = 0
# assigning value N to
# variable word because until
# space will not encounter
# a word can not be completed
word = 'N'
154
# is a white space
elif (letter == ' '):
# incrementing character
# count by 1
num_charc += 1
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
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:
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:
157