0% found this document useful (0 votes)
52 views169 pages

Python Book R-22

The document outlines a comprehensive Python programming course designed for beginners, including a vision and mission statement for the academic institution and the Computer Science department. It details program educational objectives, lab objectives, course outcomes, and a weekly syllabus with various programming experiments. Additionally, it provides reference books and web links for further learning resources.

Uploaded by

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

Python Book R-22

The document outlines a comprehensive Python programming course designed for beginners, including a vision and mission statement for the academic institution and the Computer Science department. It details program educational objectives, lab objectives, course outcomes, and a weekly syllabus with various programming experiments. Additionally, it provides reference books and web links for further learning resources.

Uploaded by

Abhinay Gude
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 169

1

PYTHON PROGRAMMING
A Comprehensive Smart Approach for Beginners to Learn
Python Language Using Best Practices

AUTHORS

Dr. K. VIJAYA KUMAR


Professor of CSE & Dean Academics
CMR College of Engineering & Technology
Hyderabad -501401

V. NARASIMHA
Assistant Professor of CSE
CMR College of Engineering & Technology
Hyderabad -501401

M. SHIVA KUMAR
Assistant Professor of CSE
CMR College of Engineering & Technology
Hyderabad -501401

2
Vision
Our Vision is to remain a premier academic institution striving continuously for excellence
in technical education, research and render technological services to the nation.

Mission
• Our Mission is to create and sustain a community of learning in which students
acquire knowledge and learn to apply it professionally with a concern for the society.
• Pursue and Disseminate Research Findings and Offer Knowledge-Based
Technological Services to Satisfy the Needs of Society and the Industry.
• Promote Professional Ethics, Leadership Qualities and Social Responsibilities.

Vision of the Department CSE

• To evolve as a centre of academic excellence in Computer Science &


Engineering by building strong teaching and research environment.

Mission of the Department CSE

• To offer high quality graduate and post graduate programs in computerscience


education and to prepare students for professional career and/orhigher studies
globally.
• To develop self learning abilities and professional ethics to serve thesociety.

3
Program Educational Objectives (PEOs)

Excel in their professional career and higher education in Computer Science &
PEO - I Engineering and chosen fields.

Demonstrate leadership qualities, team work and professional ethics to serve the
PEO - II society

Adapt to state of art technology through continuous learning


PEO - III in the areas of interest.

4
LAB OBJECTIVES

S.No. Lab Objectives

1 To train the students in solving computational problems


2 To elucidate solving mathematical problems using Python programming
language.
3 To understand the fundamentals of Python programming concepts and their
applications.
4 To understand the object-oriented concepts using Python in problem-
solving
5 To train the students in solving computational problems

COURSE (LAB)OUTCOMES

S.No. Course (Lab) Outcomes

1 Design solutions to computational problems using Python programming


language constructs.
2 Write python programs to manipulate string objects.
3 Use appropriate Data structures to organize and manipulate data items.
4 Design modular application using python module & package concepts.
5 Develop application to read and write from various file formats.

5
SYLLABUS

WEEK NAME OF THE PROGRAM


(Python Language Fundamentals-Installation -Identifiers, Reserved
Words, Data Types, Type Casting, Immutability)
Demonstration
WEEK - 1 Experiment-1: Install Anaconda open-source framework for python.
Experiment-2: Write a program to display ‘Hello World’.
Experimentation
Experiment-3: Explore various IDEs for python program
development.
Experiment-4: The volume of a sphere with radius r is 4/3 πr3. Write a
Python program to find the volume of a sphere with radius 5?
(Arithmetic Operators, Relational Operators, Logical operators,
WEEK - 2 Bitwise operators, Assignment operators, Special operators)

Demonstration
Experiment-1; Write a python program to find minimum and
maximum of given three numbers.
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?.

Experimentation
Experiment-3: Write a Python Program to Find the Square Root of a
number with out using sqrt function.
Experiment-4: Python Program to Convert Celsius To Fahrenheit.
Experiment-5: Python program to find the maximum of two numbers
using ternary operator.
(Mathematical Functions, Input and Output statements, Command
WEEK - 3 Line Arguments, String Functions)

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

6
Experiment-2: Write a program to read Employee data from the
keyboard and print that data.

Experimentation
Experiment-3: Write a program to read 3 float numbers from the
keyboard with comma separator and print their sum. Experiment-4:
Write a Program to display Command Line Arguments.
(Flow Control Statements-Conditional Statements, Transfer
Statements, Iterative Statements)

Demonstration
WEEK - 4 Experiment-1. Write a Python program to take a single digit number
from the key board and print is value in English word?.
Experiment-2. Write a Python Program to check whether an n-digit
integer is an Armstrong number or not.

Experimentation
Experiment-3. Write a Python program to display *'s in pyramid
style(also known as equivalent triangle).
Experiment-4. Write a Python Program to Display the multiplication
Table.
(Functions-Built in functions, user defined functions, Parameters,
return statement, returning multiple values from function, type of
WEEK - 5 arguments, Types of variables-global, local. Recursive functions,
Lambda functions, filter function, reduce function, Function aliasing,
Function decorators, Generators)

Demonstration
Experiment-1: Write a python function to find factorial of given
number?
Experiment-2: Write a program to create a lambda function to find
square of given number?

Experimentation
Experiment-3: Lambda Function to find biggest of given values.
Experiment-4: Program to filter only even numbers from the list by
using filter() function?

7
(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
WEEK - 6 cases of a string, Formatting the strings)

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).
Experiment-2: Write a program to access each character of string in
forward and backward direction by using while loop?

Experimentation
Experiment-3: Program to display all positions of substring in a given
main string.
Experiment-4: Write a program to reverse the given String.
(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)
WEEK -7
Demonstration
Experiment-1: Write a Python program to display unique vowels
present in the given word.
Experiment-2: Write a Python program to Count the Occurrence of an
Item in a List.

Experimentation
Experiment-3: Write a Python program to segregate even and odd
numbers from the given list of numbers.
Experimnet-4: Write a Python program to find the cumulative sum of
elements of the list.

(Python Data Structures-Tuple: Creating a Tuple, Accessing the


elements of a tuple, mathematical operators for tuple,Tuple packing
WEEK - 8 and Unpacking)

8
Demonstration
Experiment-1: Python program for adding a Tuple to List and Vice-
Versa.
Experiment-2: Write a Python program to perform the summation of
all elements of each tuple from the list of tuples.

Experimentation
Experiment-3: Write a Python program to multiply adjacent elements
of a tuple.
Experiment-4: Write a Python program to find the maximum element
in the tuple list.
(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
WEEK - 9 Dictionary Object, accessing data from the dictionary, updating
dictionaries, Deleting from dictionary, Functions on dictionary,
dictionary comprehension)

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?
Experiment-3: Write a Python program to generate powers of 2 using
set comprehensions.
Experiment-4: Write a program to eliminate duplicates present in the
list using set
Experiment-5: Write a Python program to enter name and percentage
marks in a dictionary and display information on the console.

Experimentation
Experiment-6: Write a program to take dictionary from the keyboard
and print the sum of values?
Experiment-7: Write a program to find number of occurrences of each
letter present in the given string using dictionary.
Experiment-8: Write a program to accept student name and marks
from the keyboard and creates a dictionary. Also display student
marks by taking student name as input?

9
(Python Modules-Creating Modules, Accessing members, module
aliasing, member aliasing, reloading a module,
WEEK - 10 The special variable: __name___. Working with Math, random
modules, Python Packages.Python-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.)

Demonstration
Experiment-1: Create a module fibo.py containing Fibonacci(n)
function(s) and import fibo module in a python script to print
Fibonacci series upto n.
Experiment-2: Write a python program to print all the contents of a
given module.
Experiment-3: Write a python program to create a package containing
two or modules.
Experiment-4: Write a python program to import module from a
package created in Experiment-3.

Experimentation
Experiment-5: Write a program to check whether the given file exists
or not. If it is available then print its content?
Experiment-6: Write a python Program to print the number of lines,
words, and characters present in the
given file?
Experiment-7: Program to read image file and write to a new image
file?
Experiment-8: Write a python program to read and write to a CSV
file.

10
Reference Books for solving the problems:
1. Allen B. Downey, “Think Python”, 2nd edition, SPD/O’Reilly, 2016.
2. Martin C.Brown, “The Complete Reference: Python”, McGraw-Hill, 2018.
3. Kenneth A. Lambert, B.L. Juneja, “Fundamentals of Python”, CENGAGE, 2015.
4. R. Nageswara Rao, “Core Python Programming”, 2nd edition, Dreamtech Press, 2019.

Web links:
1. https://docs.python.org/3/tutorial/modules.html#packages
2. https://www.includehelp.com/python/programs.aspx.
3. https://www.anaconda.com/products/individual
4. https://www.jetbrains.com/pycharm/

11
INDEX

S.No. Name of the Program Page No.


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

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


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

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

20. Lambda Function to find biggest of given values 94


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

13
36 Write a Python program to generate powers of 2 using set 130
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 keyboard 160
and creates a dictionary. Also display student marks by taking student
name as input?
43 Create a module fibo.py containing Fibonacci(n) function(s) and 161
import fibo module in a python script to print Fibonacci series upto
n.
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

14
Lab1:

1. Python Language Fundamentals-Installation -Identifiers, Reserved


i) Words,
Write Data program
a simple Types, Type Casting,
to display “Hello,Immutability.
World!” on the screen.
2.
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 language. Python
is designed to be highly readable. It uses English keywords frequently where as other languages use
punctuation, and it has fewer syntactical constructions than other languages.
➢ Python is Interpreted: Python is processed at runtime by the interpreter. You do not need to
compile your program before executing it. This is similar to PERL and PHP.
➢ Python is Interactive: You can actually sit at a Python prompt and interact with the interpreter
directly to write your programs.
➢ Python is Object-Oriented: Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
➢ Python is a Beginner's Language: Python is a great language for the beginner-level
programmers and supports the development of a wide range of applications from simple text
processing to WWW browsers to games.
History of Python
➢ Python was developed by Guido van Rossum in the late eightiesand
early nineties at the National Research Institute forMathematics and
Computer Science in the Netherlands.
➢ Python is derived from many other languages, including ABC, Modula-
3, C, C++, Algol-68, SmallTalk, Unix shell, and other scripting
languages.
➢ At the time when he began implementing Python, Guido van Rossum was also reading the
published scripts from "Monty Python's Flying Circus" (a BBC comedy series from the
seventies, in the unlikely case you didn't know). It occurred to him that he needed a name that
was short, unique, and slightly mysterious, so he decided to call the language Python.
➢ Python is now maintained by a core development team at the institute, although Guido van
Rossum still holds a vital role in directing its progress.
➢ Python 1.0 was released on 20 February, 1991.
➢ Python 2.0 was released on 16 October 2000 and had many major new features, including a
cycle detecting garbage collector and support for Unicode. With this release the 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 or py3k),

15
a major, backwards-incompatible release, was released on 3 December 2008 aftera long period
of testing. Many of its major features have been back ported to the backwards-compatible
Python 2.6.x and 2.7.x version series.
➢ In January 2017 Google announced work on a Python 2.7 to go transcompiler, which The
Register speculated was in response to Python 2.7's planned end-of-life.
Python Features:
Python's features include:
➢ Easy-to-learn: Python has few keywords, simple structure, and a clearly defined syntax. This
allows the student to pick up the language quickly.
➢ Easy-to-read: Python code is more clearly defined and visible to the eyes.
➢ Easy-to-maintain: Python's source code is fairly easy-to-maintain.
➢ A broad standard library: Python's bulk of the library is very portable and cross-
platform compatible on UNIX, Windows, and Macintosh.
➢ Interactive Mode: Python has support for an interactive mode which allows interactivetesting
and debugging of snippets of code.
➢ Portable: Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
➢ Extendable: You can add low-level modules to the Python interpreter. These modulesenable
programmers to add to or customize their tools to be more efficient.
➢ Databases: Python provides interfaces to all major commercial databases.
➢ GUI Programming: Python supports GUI applications that can be created and ported to many
system calls, libraries, and windows systems, such as Windows MFC, Macintosh, and the X
Window system of UNIX.
➢ Scalable: Python provides a better structure and support for large programs than shell scripting.

Need of Python Programming


➢ Software quality
Python code is designed to be readable, and hence reusable and maintainable— much
more so than traditional scripting languages. The uniformity of Python code makes it easy to
understand, even if you did not write it. In addition, Python has deep support for more advanced
software reuse mechanisms, such as object-oriented (OO) and function programming.

➢ Developer productivity

Python boosts developer productivity many times beyond compiled or statically typed
languages such as C, C++, and Java. Python code is typically one-third to less to debug, and
less to maintain after the fact. Python programs also run immediately, without the lengthy
compile and link steps required by some other tools, further boosting programmer speed.
Program portability Most Python programs run unchanged on all major computer platforms.

16
Porting Python code between Linux and Windows, for example, is usually just a matter of
copying a script‘s code between machines.

➢ Support libraries

Python comes with a large collection of prebuilt and portable functionality, known as
the standard library. This library supports an array of application-level programming tasks,
from text pattern matching to network scripting. In addition, Python can be extended with both
home grown libraries and a vast collection of third-party application support software. Python‘s
third-party domain offers tools for website construction, numeric programming, serial port
access, game development, and much more (see ahead for a sampling).

➢ Component integration

Python scripts can easily communicate with other parts of an application, using a variety
of integration mechanisms. Such integrations allow Python to be used as a product
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 .NET components, can
communicate over frameworks such as COM and Silverlight, can interface with devices over
serial ports, and can interact over networks with interfaces like SOAP, XML-RPC, and
CORBA. It is not a standalone tool.

➢ Enjoyment

Because of Python‘s ease of use and built-in toolset, it can make the act of programming
more pleasure than chore. Although this may be an intangible benefit, its effect on productivity
is an important asset. Of these factors, the first two (quality and productivity) are probably the
most compelling benefits to most Python users, and merita fuller description.
➢ It's Object-Oriented
Python is an object-oriented language, from the ground up. Its class model supports
advanced notions such as polymorphism, operator overloading, and multiple inheritance; yet in
the context of Python's dynamic typing, object-oriented programming (OOP) is remarkably easy
to apply. Python's OOP nature makes it ideal as a scripting tool for object-oriented systems
languages such as C++ and Java. For example, Python programs can subclass (specialized)
classes implemented in C++ or Java.
➢ It's Free
Python is freeware—something which has lately been come to be called open source
software. As with Tcl and Perl, you can get the entire system for free over the Internet. There
are no restrictions on copying it, embedding it in your systems, or shipping it with your products.
In fact, you can even sell Python, if you're so inclined. But don't get the wrong idea: "free"

17
doesn't mean "unsupported". On the contrary, the Python online community responds to user
queries with a speed that most commercial software vendors would do well to notice.
➢ It's Portable
Python is written in portable ANSI C, and compiles and runs on virtually every major
platform in use today. For example, it runs on UNIX systems, Linux, MS-DOS,
MS-Windows (95, 98, NT), Macintosh, Amiga, Be-OS, OS/2, VMS, QNX, and more. Further,
Python programs are automatically compiled to portable bytecode, which runs the same on any
platform with a compatible version of Python installed (more on this in the section "It's easy to
use"). What that means is that Python programs that use the core language run the same on UNIX,
MS-Windows, and any other system with a Python interpreter.
➢ It's Powerful
From a features perspective, Python is something of a hybrid. Its tool set places it
between traditional scripting languages (such as Tcl, Scheme, and Perl), and systems languages
(such as C, C++, and Java). Python provides all the simplicity and ease of use of a scripting
language, along with more advanced programming tools typically found in systems
development languages.
➢ Automatic memory management
Python automatically allocates and reclaims ("garbage collects") objects when no longer
used, and most grow and shrink on demand; Python, not you, keeps track of low- level memory
details.
➢ Programming-in-the-large support
Finally, for building larger systems, Python includes tools such as modules,classes, and
exceptions; they allow you to organize systems into components, do OOP, and handle events
gracefully.
➢ It's Mixable
Python programs can be easily "glued" to components written in other languages. In
technical terms, by employing the Python/C integration APIs, Python programs can be both
extended by (called to) components written in C or C++, and embedded in (called by) C or C++
programs. That means you can add functionality to the Python system as needed and use Python
programs within other environments or systems.
➢ It's Easy to Use
For many, Python's combination of rapid turnaround and language simplicity make
programming more fun than work. To run a Python program, you simply type it and run it.
There are no intermediate compile and link steps (as when using languages such as C or C++).
As with other interpreted languages, Python executes programs immediately, which makes for
both an interactive programming experience and rapid turnaround after program changes.
Strictly speaking, Python programs are compiled (translated) to an intermediate form called
bytecode, which is then run by the interpreter.

18
➢ It's Easy to Learn
This brings us to the topic of this book: compared to other programming languages, the
core Python language is amazingly easy to learn. In fact In fact, you can expect to be coding
significant Python programs in a matter of days (and perhaps in just hours, if you're already an
experienced programmer).
➢ Internet Scripting
Python comes with standard Internet utility modules that allow Python programs to
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 a number of
peripheral tools for doing Internet programming in Python. For instance, the
HTMLGen and pythondoc systems generate HTML files from Python class-based descriptions,
and the JPython system mentioned above provides for seamless Python/Java integration.
➢ Database Programming
Python's standard pickle module provides a simple object-persistence system: it allows
programs to easily save and restore entire Python objects to files. For more traditional 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 the same on a variety of underlying
database systems, and a system named gadfly that implements an SQL database for Python
programs.
➢ Image Processing, AI, Distributed Objects, Etc.
Python is commonly applied in more domains than can be mentioned here. But in
general, many are just instances of Python's component integration role in action. By adding
Python as a frontend to libraries of components written in a compiled language such 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 implemented in a compiled language such
as C, along with a Python frontend layer on top used to configure and launch the compiled
components.

Who Uses Python Today?


1. Google makes extensive use of Python in its web search systems.
2. The popular YouTube video sharing service is largely written in Python.
3. The Dropbox storage service codes both its server and desktop client software primarilyin
Python.
4. The Raspberry Pi single-board computer promotes Python as its educational language.
5. The widespread BitTorrent peer-to-peer file sharing system began its life as a Python
program.
6. Google‘s App Engine web development framework uses Python as an application
language.
7. Maya, a powerful integrated 3D modeling and animation system, provides a Python

19
scripting API.
8. Intel, Cisco, Hewlett-Packard, Seagate, Qualcomm, and IBM use Python for hardware
testing.
9. NASA, Los Alamos, Fermilab, JPL, and others use Python for scientific programmingtasks.
Byte code Compilation:
Python first compiles your source code (the statements in your file) into a format known as
byte code. Compilation is simply a translation step, and byte code is a lower- level, platform
independent representation of your source code. Roughly, Python translates each of your source
statements into a group of byte code instructions by decomposing them into individual steps. This
byte code translation is performed to speed execution —byte code can be run much more quickly
than the original source code statements in your text file.

The Python Virtual Machine:


Once your program has been compiled to byte code (or the byte code has been loaded
from existing .pyc file), it is shipped off for execution to something generally known as thepython virtual
machine (PVM).

Applications of Python:
1. Systems Programming
2. GUIs
3. Internet Scripting
4. Component Integration
5. Database Programming
6. Rapid Prototyping
7. Numeric and Scientific Programming

What Are Python’s Technical Strengths?


1. It‘s Object-Oriented and Functional
2. It‘s Free
3. It‘s Portable
4. It‘s Powerful
5. It‘s Mixable
6. It‘s Relatively Easy to Use

20
7. It‘s Relatively Easy to Learn
Identifiers:
All the variables, class, object, functions, lists, dictionaries etc. in Python are together termed as Python
Identifiers. Identifiers are the basis of any Python program. Almost every Python Code uses some or
other identifiers.

Rules for using Python Identifiers:


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

False def if raise


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

All the keywords except True, False and None are in lowercase and they must be written as they are.
These cannot be used as variable names, function names, or any other identifiers.
If any of the keywords is used as a variable, then we will get the error message

Display all keywords

We can display the full list of all the keywords in the current version of Python by typing the following
command in the Python interpreter.
import keyword
print (keyword.kwlist)

21
And to find out the number of reserved words in Python.
print (len(kewyord.kwlist))

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 to variables.
The operand to the left of the = operator is the name of the variable and the operand to the right
of the = operator is the value stored in the variable. For example –

22
Multiple Assignments to variables:

Python allows you to assign a single value to several variables simultaneously.


For example –

a=b=c=1

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

a, b, c = 1, 2.5, ”mothi”

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

Standard Data Types:

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

Python Numbers:

Number data types store numeric values. Number objects are created when you assign a value
to them.
Python supports four different numerical types:
• int (signed integers)
• long (long integers, they can also be represented in octal and hexadecimal)
• float (floating point real values)
• complex (complex numbers)
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.

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

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

Python has two types of type conversion:


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

(Desired type)

24
x = int(1)
y = int(2.8)
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 some
exceptions. They cannot change, and their values and it remains permanent once they are initialized
and hence called immutable.

Python Immutable Data Types:

Class Explanation Immutable or not

Bool Boolean value Immutable

Int Integer value (magnitude can be arbitrary) Immutable

25
Float Floating point number Immutable

List Sequence of objects of mutable nature Mutable

Tuple Sequence of objects of immutable nature Immutable

Str Character /string Immutable

Set set of distinct objects that are of Unordered nature Mutable

Frozenset Set class of immutable nature Immutable

Dict Dictionary or associative mapping Mutable

Demonstration:

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


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

Download the latest version of python ide 3.10


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

Step5: follow the image

26
Click here on the next button

Click on I agree button

27
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

28
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

29
After that click on the next button

30
Click on the finish Button.

Step6: open programme file and select anaconda navigator


Running Python:
a. Running Python Interpreter:
Python comes with an interactive interpreter. When you type python in your shell or
command prompt, the python interpreter becomes active with a >>> prompt and waits for your
commands.

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

31
b. Running Python Scripts in command prompt

To check the version of python

32
To run the python IDE

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


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

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

The frame of anaconda navigator. After successful installation.

Experiment-4: The volume of a sphere with radius r is 4/3 πr3. Write a Python
program to find the volume of a sphere with radius 5?
5.
Step1: take the variable radius as r with input value
Step2: apply the sphere formula directly and print the volume of sphere with radius.
Step3: expected output 523.33.

34
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
- (Subtraction) is 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 =>
(Multiplication) a * 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.

35
// (Floor
It gives the floor value of the quotient produced by dividing the two operands.
division)

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

Comparison (or) relation operator


Comparison operators are used to comparing the value of the two operands and returns Boolean true or
false accordingly. The comparison operators are described in the following table.

36
Operator Description
== If the value of two operands is equal, then the condition becomes true.
!= If the value of two operands is not equal then the condition becomes true.
If the first operand is less than or equal to the second operand, then the condition becomes
<=
true.
If the first operand is greater than or equal to the second operand, then the condition
>=
becomes true.
<> If the value of two operands is not equal, then the condition becomes true.
> If the first operand is greater than the second operand, then the condition becomes true.
< If the first operand is less than the second operand, then the condition becomes true.

Example
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:

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

Python assignment operators


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

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

38
b=5
c=0
c=a+b
print("Line 1 - Value of c is ", c)
c += a
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.
^ (binary The resulting bit will be 1 if both the bits are different otherwise the resulting bit will be
xor) 0.

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

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

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

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.

41
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
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"]

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

Python Ternary operator


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

The syntax of Python Ternary Operator is:

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

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

Program:
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("Maximumber number",max)
min = a if a < b and a<c else b if b<c else c
print("Minimum number",min)
Output:

44
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))
print ('The Total price is: ' + str(result))

output:

45
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 store the result in the result variable
For example, to find the square root of 49 use the following code: 49**0.5. Here 0.5 is the power
and 49 is the number.
Step-3: print the result in the output

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


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

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

46
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

47
LAB 3:

Mathematical Functions, Input and Output statements, Command Line


Arguments, String Functions

Mathematical Functions:

The math Module :


This module provides access to the mathematical functions defined by the C standard.

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

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

Number-theoretic and representation functionsmath.ceil(x)


Return the ceiling of x, the smallest integer greater than or equal to x. If x is not a float, delegatesto x.
ceil ( ), which should return an Integral value.

math.copysign(x, y)
Return a float with the magnitude (absolute value) of x but the sign of y. On platforms that support
signed zeros, copysign(1.0, -0.0) returns -1.0.

math.fabs(x)
Return the absolute value of x.

math.factorial(x)
Return x factorial as an integer. Raises ValueError if x is not integral or is negative.

math.floor(x)
Return the floor of x, the largest integer less than or equal to x. If x is not a float, delegates tox.
floor ( ), which should return an Integral value.

math.fmod(x, y)
Return fmod(x, y), as defined by the platform C library. Note that the Python expression x % y may
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 has the same sign as x and

48
magnitude less than abs(y). Python‘s x % y returns a result with the signof 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, which cannot be represented exactly as a float, and
rounds to the surprising 1e100. For this reason, function fmod( ) is generally preferred when working
with floats, while Python‘s x % y is preferred when working with integers.

math.frexp(x)
Return the mantissa and exponent of x as the pair (m, e). m is a float and e is an integer such that
x = m * 2**e exactly. If x is zero, returns (0.0, 0), otherwise 0.5 <= abs(m) < 1. This is used to
―pick apart‖ the internal representation of a float in a portable way.

math.fsum(iterable)
Return an accurate floating point sum of values in the iterable. Avoids loss of precision by
tracking multiple 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 where the
rounding mode is half-even. On some non-Windows builds, the underlying C library uses extended
precision addition and may occasionally double-round an intermediate sum causing itto be off in its
least significant bit.

For further discussion and two alternative approaches, see the ASPN cookbook recipes for accurate
floating point summation.

math.gcd(a, b)
Return the greatest common divisor of the integers a and b. If either a or b is nonzero, then the value
of gcd(a, b) is the largest positive integer that divides both a and b. gcd(0, 0) returns 0.

New in version 3.10.

math.isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)


Return True if the values a and b are close to each other and False otherwise.

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

49
abs_tol is the minimum absolute tolerance – useful for comparisons near zero. abs_tol must be atleast
zero.

If no errors occur, the result will be: abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol).
Input, Processing, and Output:
How do programmers solve problems? The problem is divided into input, processing, and output.

The first problem I'd like to solve is getting Python to ask me for my name.In Python 3.x, you can get
input from the user with the input( ) function.
Let's just call input( ), and see what happens:

>>> input()
Hello
'Hello'

I called input( ) from the Python shell, and the interpreter waited for me to type something andthen press
'Enter'. The interpreter then printed out my input.

Let's refine that a bit.


Problem: Get Python to say Hello
We know how to use the function print( ) to print variables:

50
x = 5 print(x)
OUTPUT: 5

Can we use that to print our message?

message = Hello
print(message)
OUTPUT:

That didn't work too well. What is our message? Python thinks that Hello is a variable.
The word Hello is a string. Python will understand that it is a string if we wrap it in quotes.

message ='Hello'
print(messa)

OUTPUT:
Hello

Not much of a program. Can it be changed, and still work?What happens if we try to print the string
directly?

print('Hello')

OUTPUT:
Hello
Displaying Output with the Print Function:
The print( ) function prints the given object to the standard output device (screen) or to the text stream
file.

The full syntax of print( ) is:


print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

print( ) Parameters
objects - object to the printed. * indicates that there may be more than one object
sep - objects are separated by sep. Default value: ' '
end - end is printed at last

51
file - must be an object with write(string) method. If omitted it, sys.stdout will be used
whichprints objects on the screen.
flush - If True, the stream is forcibly flushed. Default value: False
Note: sep, end, file and flush are keyword arguments. If you want to use sep argument,
youhave to use:
print(*objects, sep = 'separator')not
print(*objects, 'separator')

Example 1: How print( ) works in Python?


print("Python is fun.")a = 5
# Two objects are passedprint("a =", a)
b=a
# Three objects are passedprint('a =', a, '= b')

When you run the program, the output will be:

a=5=b

In the above program, only objects parameter is passed to print( ) function (in all three print
statements).
Hence,
➢ ' ' separator is used. Notice, the space between two objects in output.
➢ end parameter '\n' (newline character) is used. Notice, each print statement
displays theoutput in the new line.
➢ file is sys.stdout. The output is printed on the screen.
➢ flush is False. The stream is not forcibly flushed.

Example 2: print( ) with separator and end parameters


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

When you run the program, the output will


be:a =000005
a =05

We passed the sep and end parameters in the above program.

Comments:
➢ In Python, there are two ways to annotate your code.
➢ The first is to include comments that detail or indicate what a section of code – orsnippet – does.
➢ The second makes use of multi-line comments or paragraphs that serve asdocumentation for
others reading your code.
➢ Think of the first type as a comment for yourself, and the second as a comment forothers. There

52
is not right or wrong way to add a comment, however. You can do whatever feels comfortable.
Single-line comments are created simply by beginning a line with the hash (#)character, and they are
automatically terminated by the end of line.

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 the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition
operator. For example:
Program:
str ="WELCOME"
print str # Prints complete string
print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 5th print
str[2:] # Prints string starting from 3rd character print str * 2
# Prints string two times
print str + "CSE" # Prints concatenated string
Output:
WELCOME W
LCO LCOME
WELCOMEWELCOME
WELCOMECSE

Built-in String methods for Strings:

SNO Method Name Description


1 capitalize( ) Capitalizes first letter of string.
Returns a space-padded string with the original
2 center(width, fillchar)
string centered to a total of width columns.
Counts how many times str occurs in string or in a
count(str, beg=
3 substring of string if starting index beg and ending
0,end=len(string))
index end are given.
Decodes the string using the codec registered for
decode(encoding='UTF-
4 encoding. Encoding defaults to the default string
8',errors='strict')
encoding.
Returns encoded string version of string; on error,
encode(encoding='UTF-
5 default is to raise a Value Error unless errors is
8',errors='strict')
given with 'ignore' or 'replace'.

53
Determines if string or a substring of string (if starting
6 endswith(suffix, beg=0, index beg and ending index end are given) ends with
end=len(string)) suffix; returns true if so and false
otherwise.
Expands tabs in string to multiple spaces; defaults
7 expandtabs(tabsize=8)
to 8 spaces per tab if tabsize not provided.
Determine if str occurs in string or in a substring of string
find(str, beg=0
8 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 the original
20 ljust(width[, fillchar])
string left-justified to a total of width columns.
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.

54
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))
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 most
num=string.count(str))
num substrings if given.
splitlines ( Splits string at all (or num) NEWLINEs and returns
32
num=string.count('\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 total
39 zfill (width) 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.

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

56
Python Boolean:

Booleans are identified by True or False. Example:


Program:
a = True b = False print a print b
Output:
True False

Demonastration:

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


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

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

enter your name=Rishikesh


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

57
Experimentation:

Experiment-3: Write a program to read 3 float numbers from the keyboard with , separator and
Experiment-3: Write a program to read 3 float numbers from the keyboard with , separator
print their sum.
and print their sum. Iterative Statements

Step1: take the 3 different input keyword with floating point


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

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


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

58
Lab 4:

Flow Control Statements-Conditional Statements, Transfer Statements,


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

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

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

We have 3 types of Conditional Statements :

if:
if-else:
Nested if:
elif:

Python If-else statements

Decision making is the most important aspect of almost all the programming languages. As the name
implies, decision making allows us to run a particular block of code for a particular decision. Here, the
decisions are made on the validity of the particular conditions. Condition checking is the backbone of
decision making.
In python, decision making is performed by the following statements.
Statement Description
The if statement is used to test a specific condition. If the condition is true, a block of
If Statement
code (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

59
Indentation in Python

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

The if statement
The if statement is used to test a particular condition and if the condition is true, it executes a block of
code known as if-block. The condition of if statement can be any valid logical expression which can be
either evaluated to true or false.

The syntax of the if-statement is given below.


if expression:
statement

Example 1
num = int(input("enter the number?"))
if num%2 == 0:
print("Number is even")

Output:
enter the number?10
Number is even
Example 2 : Program to print the largest of the three numbers.

60
a = int(input("Enter a? "));
b = int(input("Enter b? "));
c = int(input("Enter c? "));
if a>b and a>c:
print("a is largest");
if b>a and b>c:
print("b is largest");
if c>a and c>b:
print("c is largest");

Output:

Enter a? 100
Enter b? 120
Enter c? 130
c is largest

The if-else statement


The if-else statement provides an else block combined with the if statement which is executed in the
false case of the condition.
If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.

The syntax of the if-else statement is given below.


if condition:
#block of statements
else:
#another block of statements (else-block)

61
Example 1 : Program to check whether a person is eligible to vote or not.
age = int (input("Enter your age? "))
if age>=18:
print("You are eligible to vote !!")
else:
print("Sorry! you have to wait !!")

Output:
Enter your age? 90
You are eligible to vote !!
Example 2: Program to check whether a number is even or not.
num = int(input("enter the number?"))
if (num%2 == 0):
print("Number is even...")
else:
print("Number is odd...")

Output:
enter the number?10
Number is even

The elif statement

The elif statement enables us to check multiple conditions and execute the specific block of statements
depending upon the true condition among them. We can have any number of elif statements in our
program depending upon our need. However, using elif is optional.

The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if
statement.

The syntax of the elif statement is given below.

if expression 1:
# block of statements

elif expression 2:
# block of statements

elif expression 3:
# block of statements

else:
# block of statements

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

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

Why we use loops in python?


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

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

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

Example:
i=1
n=int(input("Enter the number up to which you want to print the natural numbers?"))
for i in range(0,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

65
Nested for loop in python
Python allows us to nest any number of for loops inside a for loop. The inner loop is executed n number
of times for every iteration of the outer loop. The syntax of the nested for loop in python is given
below.

for iterating_var1 in sequence:


for iterating_var2 in sequence:
#block of statements
#Other statements

Example 1

n = int(input("Enter the number of rows you want to print?"))


i,j=0,0
for i in range(0,n):
print()
for j in range(0,i+1):
print("*",end="")
Output:
Enter the number of rows you want to print?5
*
**
***
****
*****

Using else statement with for loop


Unlike other languages like C, C++, or Java, python allows us to use the else statement with the for
loop which can be executed only when all the iterations are exhausted. Here, we must notice that if the
loop contains any of the break statement then the else statement will not be executed.
Example 1

for i in range(0,5):
print(i)
else:print("for loop completely exhausted, since there is no break.");

In the above example, for loop is executed completely since there is no break statement in the loop. The
control comes out of the loop and hence the else block is executed.
Output:
0
1
2
3
4
for loop completely exhausted, since there is no break.

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

67
4
5
6
7
8
9
10

Example 2
i=1
number=0
b=9
number = int(input("Enter the number?"))
while i<=10:
print("%d X %d = %d \n"%(number,i,number*i));
i = i+1;

Output:
Enter the number?10
10 X 1 = 10
10 X 2 = 20
10 X 3 = 30
10 X 4 = 40
10 X 5 = 50
10 X 6 = 60
10 X 7 = 70
10 X 8 = 80
10 X 9 = 90
10 X 10 = 100

Infinite while loop


If the condition given in the while loop never becomes false then the while loop will never terminate
and result into the infinite while loop.
Any non-zero value in the while loop indicates an always-true condition whereas 0 indicates the
always-false condition. This type of approach is useful if we want our program to run continuously in
the loop without any disturbance.
Example 1
while (1):
print("Hi! we are inside the infinite while loop");
Output:
Hi! we are inside the infinite while loop
(infinite times)

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

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

Using else with Python while loop

Python enables us to use the while loop with the while loop also. The else block is executed when the
condition given in the while statement becomes false. Like for loop, if the while loop is broken using
break statement, then the else block will not be executed and the statement present after else block will
be executed.
Consider the following example.
i=1;
while i<=5:
print(i)
i=i+1;
else:print("The while loop exhausted");

Output:
1
2
3
4
5
The while loop exhausted
Example 2
i=1;
while i<=5:
print(i)
i=i+1;
if(i==3):
break;
else:print("The while loop exhausted");

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

These are of 2 types :

break
continue
pass

Python break statement

The break is a keyword in python which is used to bring the program control out of the loop. The break
statement breaks the loops one by one, i.e., in the case of nested loops, it breaks the inner loop first and
then proceeds to outer loops. In other words, we can say that break is used to abort the current
execution of the program and the control goes to the next line after the loop.
The break is commonly used in the cases where we need to break the loop for a given condition.

The syntax of the break is given below.


#loop statements
break

Example 1
list =[1,2,3,4]
count = 1
for i in list:
if i == 4:
print("item matched")
count = count + 1;
break
print("found at",count,"location")

Output:
item matched
found at 2 location

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

70
break
print(i);

Output:
p
y
t
h

Example 3: break statement with while loop


i=0
while 1:
print(i," ",end="")
i=i+1
if i == 10:
break
print("came out of while loop")

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

Python continue Statement

The continue statement in python is used to bring the program control to the beginning of the loop. The
continue statement skips the remaining lines of code inside the loop and start with the next iteration. It
is mainly used for a particular condition inside the loop so that we can skip some specific code for a
particular condition.

The syntax of Python continue statement is given below.


#loop statements
continue;
#the code to be skipped
Example 1
i = 0;
while i!=10:
print("%d"%i);
continue;
i=i+1;

Output:
infinite loop

Example 2

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

Output:
1
2
3
4
6
7
8
9
10

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

Python Pass Syntax


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

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

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

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

Came out of pass


Current element: 4 Current element: 5

Demonstration

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

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

73
Output:

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:

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

Approach:
print pyramid star pattern

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

Step by step descriptive logic to print Pyramid star pattern.


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

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

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

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

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

76
Lab 5

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


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

Built-in Functions in Python


One of the reasons for which Python is preferred over the other languages is the huge collection of built-
in functions. You would have come across some of these like print( ), int( ), etc.
In this article, we will discuss these built-in functions in Python with examples. So, let us begin.
Introduction to Built-in Functions in Python
Functions are the set of lines of code that work and behave together under a name. Built-in functions are
the ones whose functionality is predefined.
These get stored in the interpreter and come into action when they are called. These can be accessed from
any part of the program. The Python 3.6 version has 69 built-in functions and these are:
Table of built-in functions in Python:
abs( ) enumerate( ) iter( ) reversed( ) dict( ) int( )
all( ) eval( ) len( ) round( ) dir( ) isinstance( )
any( ) exec( ) list( ) set( ) dir( ) isinstance( )
ascii( ) filter( ) locals( ) setattr( ) divmod( ) issubclass( )
bin( ) float( ) map( ) slice( ) property( )
bool( ) format( ) max( ) sorted( ) range( )
breakpoint( ) frozenset( ) memoryview( ) staticmethod( ) repr( )
bytearray( ) getattr( ) min( ) str( )
bytes( ) globals( ) next( ) sum( )
callable( ) hasattr( ) object( ) super( )
chr( ) hash( ) oct( ) tuple( )
classmethod( ) help( ) open( ) type( )
compile( ) hex( ) ord( ) vars( )
complex( ) id( ) pow( ) zip( )
delattr( ) input( ) print( ) __import__( )

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

77
5.6

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

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

Example of a user-defined function

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

Default Parameter Values


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

79
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.
def foo(a=0, b=0, /, c=0, d=0):
print(a, b, c, d)
The parameters defined before the bare / are now considered to be positional-only and keyword
mapping will no longer work on them.
In the above function definition a and b are now positional-only parameters.
These function calls will still work:
>>> foo()
0000
>>> foo(1)
1000
>>> foo(1, 2, 3, 4)
1234
>>> foo(1, 2, d=4, c=3)
1234
>>> foo(1, d=4, c=3)
1034
>>> foo(c=3, d=4)
0034
However, attempting to pass keyword arguments for a or b will fail:
>>> foo(1, b=2, c=3, d=4)
TypeError: foo() got some positional-only arguments passed as keyword arguments: 'b'

Python return Statement


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

def add(x, y):


return x + y

80
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:
def calculate_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
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.

81
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:
def calculate_data(sales):
over_limit = 0
for s in sales:
if s > 500:
over_limit += 1
average_purchase = sum(sales) / len(sales)
return [over_limit, average_purchase]
We have just separated our values into a single list. Our list contains the number of purchases worth over
$500 and the value of an average purchase, respectively.
We could also return a tuple data structure. To do so, we would replace our square brackets with curly
brackets. The big factor to consider is that tuples cannot contain duplicate values. If there is a chance two
values you pass to your main program will be equal, avoid using a tuple.

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


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

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

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

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

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

Types Of Arguments In Python Functions

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

Types of Arguments in Pythons:


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

Positional Arguments in Python:


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

83
In demo16.py 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 demo17.py
Example: Positional arguments (Demo16.py)
def sub(x, y):
print(x-y)
# calling function
sub(10, 20)
Output: -10
Example: Positional arguments (Demo17.py)
def sub(x, y):
print(x-y)
# calling function
sub(10, 20,30)

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

Keyword Arguments in Python:


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

Example: Keyword arguments (Demo18.py)


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

Example: Keyword arguments (Demo19.py)


def details(id, name):
print("Emp id is: ",id)
print("Emp name is: ",name)

84
# 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
demo21.py
Example: Positional and keyword arguments in Python (Demo20.py)
def details(id, name):
print("Emp id is: ",id)
print("Emp name is: ",name)
# calling function
details(1, name="Anushka")
Output:

Example: Positional and keyword arguments in Python (Demo21.py)


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

Output: SyntaxError: non-keyword arg after keyword arg

Default Arguments in Python Function with Examples:


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

Example: Default Arguments in Python (Demo22.py)


def cart(item, price=20):
print(item, "cost is :" ,price)
cart(item="pen")

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

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

Example: Default arguments (Demo23.py)


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

Variable Length Arguments in Python Function:

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

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

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

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

Example: keyword variable length argument (**variable) in Python (Demo25.py)


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

Example: keyword variable-length argument (**variable) (Demo26.py)


def m1(**x):
for k, v in x.items():
print(k,"=",v)
m1(a=10, b=20, c=30)
m1(id=100, name="Subbalaxmi")
Output:

Function vs Module vs Library in Python:


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

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

Python Local Variables


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

#This function prints value of a global variable

def display_string(): #start of function scope


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

Outputelcome to CodeRepublics

Python Global Variables


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

Example: Create a Global Variable


x = "global variable"

def func_display():
print("x inside:", x)

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

Output
x inside: global variable
x out x 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
def Function(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

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

Example of filter() function:


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

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

Aliasing and Cloning Lists


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

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

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

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

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

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

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

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

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

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

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

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

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

91
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 = x.copy() #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:
def greeting():
print('Hi!')
print('How are you?')

92
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:
def greeting():
print('Hi!')
yield 1
print('How are you?')
yield 2
print('Are you there?')
yield 3

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:

1. Start

93
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):
if i == 1:
return 1
else:
return (i * factorial(i-1))
number = 9
print("The factorial of", number, "is", factorial(number))
Output
The factorial of 9 is 362880

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

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

EXPERIMENTATION

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

Step1: create a list using tuple


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

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

Step1: a list contain both even and odd numbers

94
Ex: seq=[1,2,3,4,5,6,7,…….]
Step2: Results contains only even numbers from the list
Step3: result = filter(lambda x: x % 2 == 0, seq)
print(list(result))
step4: output print the even numbers only.

95
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 the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator. For
example:
Program:
str ="WELCOME"
print str # Prints complete string
print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 5th print str[2:] # Prints string starting from 3rd
character print str * 2 # Prints string two times
print str + "CSE" # Prints concatenated string
Output:
WELCOME W
LCO LCOME
WELCOMEWELCOME WELCOMECSE

Built-in String methods for Strings:


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

How to create a string in Python?


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

96
my_string = 'Hello'
print(my_string)

my_string = "Hello"
print(my_string)

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

# triple quotes string can extend multiple lines


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

When you run the program, the output will be:

Hello
Hello
Hello
Hello, welcome to
the world of Python

How to access characters in a string?


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

Python allows negative indexing for its sequences.

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

#Accessing string characters in Python


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

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

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

#slicing 2nd to 5th character


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

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

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

# index must be in range


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

# index must be an integer


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

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

Element Slicing in Python

String Slicing in Python

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

>>> my_string = 'programiz'


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

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

>>> del my_string[1]


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

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

Concatenation of Two or More Strings


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

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

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

# Python String Operations


str1 = 'Hello'
str2 ='World!'

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

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

str1 + str2 = HelloWorld!


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

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

>>> # two string literals together


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

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

# Iterating through a string


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

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

>>> 'a' in 'program'


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

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

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

str = 'cold'

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

#character count
print('len(str) = ', len(str))
Run Code
When we run the above program, we get the following output:

100
list(enumerate(str) = [(0, 'c'), (1, 'o'), (2, 'l'), (3, 'd')]
len(str) = 4
Python String Formatting
Escape Sequence
If we want to print a text like He said, "What's there?", we can neither use single quotes nor double
quotes. This will result in a SyntaxError as the text itself contains both single and double quotes.

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


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

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

# using triple quotes


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

# escaping single quotes


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

# escaping double quotes


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

He said, "What's there?"


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

Escape Sequence Description


\newline Backslash and newline ignored
\\ Backslash
\' Single quote
\" Double quote
\a ASCII Bell
\b ASCII Backspace
\f ASCII Formfeed
\n ASCII Linefeed
\r ASCII Carriage Return

101
\t ASCII Horizontal Tab
\v ASCII Vertical Tab
\ooo Character with octal value ooo
\xHH Character with hexadecimal value HH
Here are some examples

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

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


This is printed
in two lines

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


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

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


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

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

# Python string format() method

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

# order using positional argument


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

# order using keyword argument


keyword_order = "{s}, {b} and {j}".format(j='John',b='Bill',s='Sean')
print('\n--- Keyword Order ---')

102
print(keyword_order)
Run Code
When we run the above program, we get the following output:

--- Default Order ---


John, Bill and Sean

--- Positional Order ---


Bill, John and Sean

--- Keyword Order ---


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

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

>>> # formatting integers


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

>>> # formatting floats


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

>>> # round off


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

>>> # string alignment


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

>>> x = 12.3456789
>>> print('The value of x is %3.2f' %x)
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

103
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")
i=0
while i<len(str):
print("|",str[i])
i=i+1

104
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
CMR TE"""

Step-3:# initializing substring


test_sub = "CMR"

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

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

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

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

Creating lists using range() function:

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

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

Looping on lists:

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

Output:
12345

Updating and deleting lists:


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

Example:

lst=[1,2,4,5,8,6]
print lst # [1,2,4,5,8,6] lst.append(9)
print lst # [1,2,4,5,8,6,9]

108
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]
print lst # [4,7,6,8,9,3]
lst[2]=5 # updates 2nd element in the list print lst # [4,7,5,8,9,3]
lst[2:5]=10,11,12 # update 2nd element to 4th element in the list print lst #
[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]
del lst[3] # delete 3rd element from the list i.e., 8 print lst # [5,7,1,9,6]

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

Concatenation of Two lists:


We can simply use „+‟ operator on two lists to join them. For example, „x‟ and „y‟ are two lists. If
we wrte x+y, the list „y‟ is joined at the end of the list „x‟.

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

Repetition of Lists:
We can repeat the elements of a list „n‟ number of times using „*‟ operator. x=[10,54,87,96,45]
print x*2 # [10,54,87,96,45,10,54,87,96,45]

Membership in Lists:
We can check if an element is a member of a list by using „in‟ and „not in‟ operator. Ifthe element
is a member of the list, then „in‟ operator returns True otherwise returns False. If the element is not in
the list, then „not in‟ operator returns True otherwise returns False.
Example:
x=[10,20,30,45,55,65] a=20
print a in x # True a=25
print a in x # False a=45
print a not in x # False a=40
print a not in x # True

Aliasing and Cloning Lists:


Giving a new name to an existing list is called ‘aliasing’. The new name is called

109
‘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 as y
print x # [10,20,30,40,50,60]
print y # [10,20,30,40,50,60]
x[1]=90 # modify 1st element in x print x # [10,90,30,40,50,60]
print y # [10,90,30,40,50,60]

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 also modify „y‟ and vice versa.
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 as y
print x # [10,20,30,40,50,60]
print y # [10,20,30,40,50,60]
x[1]=90 # modify 1st element in x print x # [10,90,30,40,50,60]
print y # [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.

110
Methods in Lists:

Method Description
lst.index(x) Returns the first occurrence of x in the list.
lst.append(x) Appends x at the end of the list.
lst.insert(i,x) Inserts x to the list in the position specified by i.
lst.copy() Copies all the list elements into a new list and returns it.
lst.extend(lst2) Appends lst2 to list.
lst.count(x) Returns number of occurrences of x in the list.
lst.remove(x) Removes x from the list.
lst.pop() Removes the ending element from the list.
lst.sort() Sorts the elements of list into ascending order.
lst.reverse() Reverses the sequence of elements in the list.
lst.clear() 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]
lst.insert(1,46)
print lst # [10,46,25,45,51,45,51,21,65]
print lst.count(45) #2

Finding Common Elements in Lists:


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

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

111
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]
print b # display [ 45, 65, [ 10, 20, 30 ] ] print b[1] # display 65
print b[2] # display [ 10, 20, 30 ] print b[2][0] # display 10
print b[2][1] # display 20
print b[2][2] # display 30
for x in b[2]:
print x, # display 10 20 30

Nested Lists as Matrices:


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

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

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.

112
Q) Write a program to perform multiplication of two matrices.
a=[[1,2,3],[4,5,6]]
b=[[4,5],[7,8],[1,2]]
c=[[0,0],[0,0]]
m1=len(a)
n1=len(a[0])
m2=len(b)
n2=len(b[0])
for i in range(0,m1):
for j in range(0,n2):
for k in range(0,n1):
c[i][j] += a[i][k]*b[k][j]
for i in range(0,m1):
for j in range(0,n2):
print "\t",c[i][j],
print ""

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):
squares.append(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 in range(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) if x%2==0 ] It will display the list even
squares as list.
[ 4, 16, 36, 64, 100 ]

113
Demonstration:

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

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

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

Step1: Python Program to Put Even and Odd Numbers in Separate List
Step2: create 3 empty list variable

114
Step3: create how many elements want to enter through key board
Step4: create loop to control the first list
for i in range(1, Number + 1):
value = int(input("Please enter the Value of %d Element :- " %i))
NumList.append(value)
Step5:
for j in range(Number):
if(NumList[j] % 2 == 0):
Even.append(NumList[j])
else:
Odd.append(NumList[j])
Step6: print even and odd numbers separately

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

Step1: create the empty list variable like a[]


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

115
Lab-8:

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

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

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

Accessing the tuple elements:


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

Updating and deleting elements:


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

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

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

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

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

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

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

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


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

Packing and unpacking tuples:


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

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

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

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

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

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

Real-life examples
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:

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

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

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

Finally, the tuple is unpacked into the variables:

Here is another example:

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

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

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

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

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

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

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

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

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

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

Tuple slices
You can uses slices with tuples:

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

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

Adding elements to a tuple


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

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

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

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


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

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

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

Looping
The list looping techniques work perfectly well with tuples:

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


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

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


k = list(t)
k.sort()
print(k)

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

Demonstration

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


Program to add a tuple to a list in Python
# Python program to add a tuple to list

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

Adding a list to a Tuple

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

120
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:

121
Experimentation

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

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

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

Output:
(5, 8, 24, 21)

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

# Python program to multiply adjacent


# elements of a tuple

Step-1:# Initializing and printing tuple value


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

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

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

# Python program to multiply adjacent


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

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

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

123
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 from it.
Creating a Set:
A set is created by placing all the elements inside curly brackets {}. Separated by comma or by using the
built-in function set( ).
Syntax:
Set_variable_name={var1, var2, var3, var4, …….}

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

We can also convert tuple or string into set.


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

Operations on set:

Sno Operation Result


1 len(s) number of elements in set s (cardinality)
2 x in s test x for membership in s
3 x not in s test x for non-membership in s
s.issubset(t) (or) test whether every element in s is in t
4 s <= t
s.issuperset(t) (or) test whether every element in t is in s

124
5 s >= t
6 s==t Returns True if two sets are equivalent and returns False.
7 s!=t Returns True if two sets are not equivalent and returns
False.
s.union(t) (or) new set with elements from both s and t
8 s|t
s.intersection(t) (or) new set with elements common to s and t
9 s&t
s.difference(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 s.copy() new set with a shallow copy of s
13 s.update(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_up return set s with elements from s or t but not both
date(t)
17 s.add(x) add element x to set s
18 s.remove(x) remove x from set s; raises KeyError if not present
19 s.discard(x) removes x from set s if present
20 s.pop() remove and return an arbitrary element from s; raises
KeyError if empty
21 s.clear() 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 the set.

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

Updating a set:
s=set( )
print type(s)
s={}
print type(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:

125
A dictionary represents a group of elements arranged in the form of key-value pairs. The first
element 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 adictionary are inserted in curly braces {
}.
d= { „Regd.No‟: 556, „Name‟:‟Mothi‟, „Branch‟: „CSE‟ }

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

Example:
}
print d[“Regd.No‟] # 556
# Mothi
# 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= { “Regd.No‟: 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={'Regd.No':556,'Name':'Mothi','Branch':'CSE'}
print d#{'Branch': 'CSE', 'Name': 'Mothi', 'Regd.No': 556}
d['Gender']="Male"
print (d) # {'Gender': 'Male', 'Branch': 'CSE', 'Name': 'Mothi', 'Regd.No': 556}

Suppose, we want to delete


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

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

To Test whether a „key‟ is available in a dictionary or not, we can use „in‟ and „not in‟ operators.
These operators return either True or False.
“Name‟ in d # check if „Name‟ is a key in d and returns 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 be available.
emp={'nag':10,'vishnu':20,'nag':20} print emp # {'nag': 20, 'vishnu': 20}

126
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‟.

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
d.clear() Removes all key-value pairs from dictionary„d‟.
d2=d.copy() Copies all elements from„d‟ into a new dictionary d2.
d.fromkeys(s [,v] ) Create a new dictionary with keys from the sequence„s‟ and
values all set to „v‟.
d.get(k [,v] ) Returns the value associated with key „k‟. If key is not
found, it returns „v‟.
d.items() Returns an object that contains key-value pairs of„d‟. The
pairs are stored as tuples in the object.
d.keys() Returns a sequence of keys from the dictionary„d‟.
d.values() Returns a sequence of values from the dictionary„d‟.
d.update(x) Adds all elements from dictionary „x‟ to„d‟.
Removes the key „k‟ and its value from„d‟ and returns thevalue. If key is
d.pop(k [,v] ) not found, then the value „v‟ is returned. If key is not found and „v‟ is
not mentioned then „KeyError‟
is raised.
d.setdefault(k [,v] ) If key „k‟ is found, its value is returned. If key is not
found, then the k, v pair is stored into the dictionary„d‟.

Using for loop with Dictionaries:


for loop is very convenient to retrieve the elements of a dictionary. Let‟s take a simple dictionary that
contains color code and its name as:
colors = { 'r':"RED", 'g':"GREEN", 'b':"BLUE", 'w':"WHITE" }
Here, “r‟, “g‟, “b‟ and “w” are represents keys and „RED‟, „GREEN‟, „BLUE‟ and „WHITE‟ indicate
values.

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


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

127
Converting Lists into Dictionary:
When we have two lists, it is possible to convert them into a dictionary. For example, we have
two lists containing names of countries and names of their capital cities.
There are two steps involved to convert the lists into a dictionary. The first step is to create a „zip‟ class
object by passing the two lists to zip( ) function. The zip( ) function is useful to convert the sequences
into a zip class object. The second step is to convert the zip object into a dictionary by using dict( )
function.
Example:
countries = [ 'USA', 'INDIA', 'GERMANY', 'FRANCE' ]
cities = [ 'Washington', 'New Delhi', 'Berlin', 'Paris' ]
z=zip(countries, cities)
d=dict(z)
print d

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

converting Strings into Dictionary:

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

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

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

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

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

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

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

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

130
Experiment-4:
Experiment-4:Write
Writea aprogram
programtotoeliminate duplicates
eliminate duplicatespresent
presentininthe
thelist
listusing
usingsetset?

Experiment-5: Write a Python program toto


enter name and percentage marks inin
a dictionary and
Experiment-5: Write a Python program enter name and percentage marks a dictionary and
display information onon
the console.
display information the console.?

Program:

131
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?

132
Experimentation:

Experiment-7:
Experiment-7: Write
Write a program
a program to find
to find the the number
number of occurrences
of occurrences of each
of each letterletter present
present in thein the
given string using a dictionary.
given string using 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 cmrcet is :
{'w': 1, 'e': 3, 'l': 2, ' ': 3, 'c': 3, 'o': 2, 'm': 2, 't': 2, 'r': 1}

Experiment-8: Write a program to accept student name and marks from the keyboard and
Experiment-8: Write a program to accept student name and marks from the keyboard and creates
creates a dictionary. Also display student marks by taking student name as input?
a dictionary. Also display student marks by taking student name as input?

Step1: as follow the experiment 5 and show the output

133
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
Packages.Python-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 file.py which contains a function func that contains a
code to print some message on the console.

Let's create the module named as file.py.


#displayMsg prints a message to the name being passed.
def displayMsg(name) :
print("Hi "+name);

Here, we need to include this module into our main module to call the method displayMsg() defined in
the module named file.

Loading the module in our python code:


We need to load the module in our python code to use its functionality. Python provides two types
of statements as defined below.
The import statement
The from-import statement

The import statement:

The import statement is used to import all the functionality of one module into another. Here, we
must notice that we can use the functionality of any python source file by importing that file as the module
into another python source file.

We can import multiple modules with a single import statement, but a module is loaded once regardless
of the number of times, it has been imported into our file.

The syntax to use the import statement is given below.

134
import module1, module2,........ module n

Hence, if we need to call the function displayMsg() defined in the file file.py, we have to import that file
as a module into our module as shown in the example below.

Example:
import file
name = input("Enter the name?")
file.displayMsg(name)

Output:
Enter the name?John
Hi John

The from-import statement:


Instead of importing the whole module into the namespace, python provides the flexibility to
import only the specific attributes of a module. This can be done by using from? import statement.

The syntax to use the from-import statement is given below.


from < module-name> import <name 1>, <name 2>..,<name n>

Consider the following module named as calculation which contains three functions as summation,
multiplication, and divide.
calculation.py:
#place the code in the calculation.py
def summation(a,b):
return a+b

def multiplication(a,b):
return a*b;

def divide(a,b):
return a/b;
Main.py:
from calculation import summation

#it will import only the summation() from calculation.py


a = int(input("Enter the first number"))
b = int(input("Enter the second number"))

print("Sum = ",summation(a,b)) #we do not need to specify the module name while accessing s
ummation()

Output:
Enter the first number10

135
Enter the second number20
Sum = 30

The from...import statement is always better to use if we know the attributes to be imported from the
module in advance. It doesn't let our code to be heavier. We can also import all the attributes from a
module by using *.

Consider the following syntax.


from <module> import *

Renaming a module:
Python provides us the flexibility to import some module with a specific name so that we can use
this name to use that module in our python source file.

The syntax to rename a module is given below.


import <module-name> as <specific-name>

Example
#the module calculation of previous example is imported in this example as cal.
import calculation as cal
a = int(input("Enter a?"))
b = int(input("Enter b?"))
print("Sum = ",cal.summation(a,b))

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

Using dir() function:

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

Example
import json
List = dir(json)
print(List)

Output:
['JSONDecoder', 'JSONEncoder', '__all__', '__author__',
'__builtins__', '__cached__', '__doc__',
'__file__', '__loader__', '__name__', '__package__', '__path__',
'__spec__', '__version__',

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

The reload() function:


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

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

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

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

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

Consider the following example.


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

Output:
Hi David

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

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

ITEmployees.py

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

3. Similarly, create one more python file with name BPOEmployees.py 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.

Test.py
import Employees
print(Employees.getNames())

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

Aliasing with ‘as’ keyword:


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

# Aliasing matplotlib.pyplot as plt


from matplotlib import pyplot as plt
plt.plot(x, y)

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

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

138
Consider a following example:

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

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

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

Value of first_variable: PYTHON


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

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

What is Math Module in Python?


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

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

139
Code

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

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

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

Constants in Math Module :


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

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

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

Syntax of this is:

math.e
Code

# importing the required library


import math

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


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

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

Syntax of this is:

math.tau
Code

# Importing the required library


import math

# Printing the value of tau using math module


print ( "The value of Tau is: ", math.tau )
Output:

The value of Tau is: 6.283185307179586


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

Syntax of this is:

math.inf
Code

# Importing the required library


import math

# Printing the value of positive infinity using the math module


print( math.inf )

# Printing the value of negative infinity using the math module


print( -math.inf )
Output:

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

Code

141
# Importing the required library
import math

# comparing the value of infinity


print( math.inf > 10e109 )
print( -math.inf < -10e109 )
Output:

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

Syntax of this is:

math.pi
Code

# Importing the required library


import math

# Printing the value of pi using the math module


print( "The value of pi is ", math.pi )
Output:

The value of pi is 3.141592653589793


Let us calculate the circumference of a circle.

Code

# Importing the required library


import math

# radius of the circle


r=4

# value of pi
pi_value = math.pi

# circumference of the circle


print(2 * pi_value * r)
Code

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

Code

# Importing the required library


import math

# Printing the value of nan using the math module


print( math.nan )
Output:

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

Calculating the Ceiling and the Floor Value


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

Code

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

# importing the math module


import math

x = 4.346

# returning the ceiling value of 4.346


print("The ceiling value of 4.346 is : ", end="")
print( math.ceil(x) )

# returning the floor value of 4.346


print("The floor value of 4.346 is : ", end="")
print( math.floor(x) )
Output:

The ceiling value of 4.346 is : 5


The floor value of 4.346 is : 4

143
Calculating the Factorial of the Number
We may determine the factorial of a given integer in a one-liner code by using the math.factorial()
function. The Python interpreter will send a message if the given number is not integral.

Code

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

# importing the math module


import math

x=6

# returning the factorial of 6


print( "The factorial of 6 is : ", math.factorial(x) )

# passing a non integral number


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

The factorial of 6 is : 720


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

Code

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

# importing the math module


import math

x = -45

# returning x's absolute value.


print( "The absolute value of -45 is: ", math.fabs(x) )
Output:

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.

144
Code

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

# importing the math module


import math

# declaring some value


num1 = 4
num2 = -3
num3 = 0.00

# passing above values to the exp() function


print( f"The exponenetial value of {num1} is: ", math.exp(num1) )
print( f"The exponenetial value of {num2} is: ", math.exp(num2) )
print( f"The exponenetial value of {num3} is: ", math.exp(num3) )
Output:

The exponenetial value of 4 is: 54.598150033144236


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

Code

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

# importing the math module


import math

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

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


Calculating Sine, Cosine, and Tangent
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

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

# importing the math module


import math

angle = math.pi / 4

# returning the sine of pi/4


print( "The sine of pi/4 is : ", math.sin( angle ) )

# returning the cosine of pi/4


print( "The cosine of pi/4 is : ", math.cos( angle ) )

# returning the tangent of pi/4


print("The tangent of pi/4 is : ", math.tan( angle ))
Output:

The sine of pi/4 is : 0.7071067811865475


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

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

Code

# Importing the math module


import math

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

['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan',
'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs',
'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt',
'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod',
'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc', 'ulp']

Description of all the Functions in Python Math Module

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

Function Description

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

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

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

factorial(x) provides the x factorial back.

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

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

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

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

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

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

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

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

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

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

exp(x) delivers e**x

expm1(x) yields e**x - 1

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

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

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

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

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

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

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

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

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

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

cos(x) returns the x's cosine.

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

sin(x) gives the sine of x back.

tan(x) gives the tangent of x back.

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

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

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

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

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

cosh(x) gives x's hyperbolic cosine.

sinh(x) gives x's hyperbolic cosine.

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

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

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

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

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

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


(3.14159...)

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

Python Random Module:


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

Example: Printing a random value from a list


# import random
import random

# prints a random value from the list


list1 = [1, 2, 3, 4, 5, 6]
print(random.choice(list1))

output:
2

Creating random integers:


# Python3 program explaining work
# of randint() function

# import random module


import random

# Generates a random number between


# a given positive range
r1 = random.randint(5, 15)
print("Random number between 5 and 15 is % s" % (r1))

# Generates a random number between

149
# two given negative range
r2 = random.randint(-10, -2)
print("Random number between -10 and -2 is % d" % (r2))

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

Python File Handling :

Till now, we were taking the input from the console and writing it back to the console to interact with the
user.
Sometimes, it is not enough to only display the data on the console. The data to be displayed may be very
large, and only a limited amount of data can be displayed on the console, and since the memory is volatile,
it is impossible to recover the programmatically generated data again and again.
However, if we need to do so, we may store it onto the local file system which is volatile and can be
accessed every time. Here, comes the need of file handling.
We will learn all about file handling in python including,
creating a file,
opening a file,
closing a file,
Reading, Writing and appending the file, etc.

Opening a file:
Python provides the open() function which accepts two arguments, file name and access mode in which
the file is accessed. The function returns a file object which can be used to perform various operations
like reading, writing, etc.
The syntax to use the open() function is given below.

file object = open(<file-name>, <access-mode>, <buffering>)

The files can be accessed using various modes like read, write, or append. The following are the details
about the access mode to open a file.
Access
SN Description
mode
It opens the file to read-only. The file pointer exists at the beginning. The file is by default
1 r
open in this mode if no access mode is passed.
It opens the file to read only in binary format. The file pointer exists at the beginning of
2 rb
the file.
3 r+ It opens the file to read and write both. The file pointer exists at the beginning of the file.
It opens the file to read and write both in binary format. The file pointer exists at the
4 rb+
beginning of the file.

150
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
12 ab+
end 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 "file.txt" (stored in the same directory) in read
mode and printing its content on the console.

Example
#opens the file file.txt in read mode
fileptr = open("file.txt","r")

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

Output:
<class '_io.TextIOWrapper'>
file is opened successfully

The close() method

Once all the operations are done on the file, we must close it through our python script using the close()
method. Any unwritten information gets destroyed once the close() method is called on a file object.

151
We can perform any operation on the file externally in the file system is the file is opened in python,
hence it is good practice to close the file once all the operations are done.

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

fileobject.close()

Consider the following example.

Example
# opens the file file.txt in read mode
fileptr = open("file.txt","r")

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

#closes the opened file


fileptr.close()

Reading the file

To read a file using the python script, the python provides us the read() method. The read() method reads
a string from the file. It can read the data in the text as well as binary format.

The syntax of the read() method is given below.

fileobj.read(<count>)

Here, the count is the number of bytes to be read from the file starting from the beginning of the file. If
the count is not specified, then it may read the content of the file until the end.
Consider the following example.

Example
#open the file.txt in read mode. Causes error if no such file exists.
fileptr = open("file.txt","r");

#stores all the data of the file into the variable content
content = fileptr.read(9);

# prints the type of the data stored in the file


print(type(content))

#prints the content of the file


print(content)

152
#closes the opened file
fileptr.close()

Output:
<class 'str'>
Hi, I am

Read Lines of the file :


Python facilitates us to read the file line by line by using a function readline(). The readline()
method reads the lines of the file from the beginning, i.e., if we use the readline() method two times, then
we can get the first two lines of the file.
Consider the following example which contains a function readline() that reads the first line of our file
"file.txt" containing three lines.

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

#stores all the data of the file into the variable content
content = fileptr.readline();

# prints the type of the data stored in the file


print(type(content))

#prints the content of the file


print(content)

#closes the opened file


fileptr.close()

Output:
<class 'str'>
Hi, I am the file and being used as

Looping through the file :

By looping through the lines of the file, we can read the whole file.

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

#running a for loop


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

153
Output:
Hi, I am the file and being used as
an example to read a
file in python.

Writing the file:


To write some text to a file, we need to open the file using the open method with one of the
following access modes.
a: It will append the existing file. The file pointer is at the end of the file. It creates a new file if no file
exists.

w: It will overwrite the file if any file exists. The file pointer is at the beginning of the file.
Consider the following example.

Example 1
#open the file.txt in append mode. Creates a new file if no such file exists.
fileptr = open("file.txt","a");

#appending the content to the file


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

File.txt:
Hi, I am the file and being used as
an example to read a
file in python.
Python is the modern day language. It makes things so simple.

Example 2
#open the file.txt in write mode.
fileptr = open("file.txt","w");

#overwriting the content of the file


fileptr.write("Python is the modern day language. It makes things so simple.")

#closing the opened file


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

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

154
Creating a new file:
The new file can be created by using one of the following access modes with the function open().
x: it creates a new file with the specified name. It causes an error a file exists with the same name.
a: It creates a new file with the specified name if no such file exists. It appends the content to the file
if the file already exists with the specified name.
w: It creates a new file with the specified name if no such file exists. It overwrites the existing file.
Consider the following example.

Example
#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file2.txt","x");

print(fileptr)
if fileptr:
print("File created successfully");

Output:
File created successfully

Using ‘with’ statement with files


The ‘with’ statement was introduced in python 2.5. It is useful in the case of manipulating the
files. It is used in the scenario where a pair of statements is to be executed with a block of code in between.

The syntax to open a file using with statement is given below.

with open(<file name>, <access mode>) as <file-pointer>:


#statement suite

The advantage of using with statement is that it provides the guarantee to close the file regardless of how
the nested block exits.
It is always suggestible to use the with statement in the case of file s because, if the break, return, or
exception occurs in the nested block of code then it automatically closes the file. It doesn't let the file to
be corrupted.
Consider the following example.

Example
with open("file.txt",'r') as f:
content = f.read();
print(content)

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

File Pointer positions

155
Python provides the tell() method which is used to print the byte number at which the file pointer exists.
Consider the following example.

Example
# open the file file2.txt in read mode
fileptr = open("file2.txt","r")

#initially the filepointer is at 0


print("The filepointer is at byte :",fileptr.tell())

#reading the content of the file


content = fileptr.read();

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

print("After reading, the filepointer is at:",fileptr.tell())

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

Modifying file pointer position


In the real world applications, sometimes we need to change the file pointer location externally
since we may need to read or write the content at various locations.
For this purpose, the python provides us the seek() method which enables us to modify the file pointer
position externally.

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

<file-ptr>.seek(offset[, from)

The seek() method accepts two parameters:

offset: It refers to the new position of the file pointer within the file.
from: It indicates the reference position from where the bytes are to be moved. If it is set to 0, the
beginning of the file is used as the reference position. If it is set to 1, the current position of the file
pointer is used as the reference position. If it is set to 2, the end of the file pointer is used as the reference
position.

Consider the following example.


Example
# open the file file2.txt in read mode
fileptr = open("file2.txt","r")

156
#initially the filepointer is at 0
print("The filepointer is at byte :",fileptr.tell())

#changing the file pointer location to 10.


fileptr.seek(10);

#tell() returns the location of the fileptr.


print("After reading, the filepointer is at:",fileptr.tell())

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

Python os module OR Built in Modules


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

Renaming the file

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

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

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

#rename file2.txt to file3.txt


os.rename("file2.txt","file3.txt")

Removing the file

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

Example
import os;
#deleting the file named file3.txt
os.remove("file3.txt")
Creating the new directory

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

Example
import os;

#creating a new directory with the name new


os.mkdir("new")

Changing the current working directory


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

#changing the current working directory to new

os.chdir("new")

The getcwd() method

This method returns the current working directory.


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

Example
import os;

#printing the current working directory


print(os.getcwd())

Deleting directory

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


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

Example
import os;

#removing the new directory


os.rmdir("new")

158
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 file1.py executes the script file.py and
writes its output to the text file output.txt
file.py:
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))

file1.py:
import subprocess

with open("output.txt", "wb") as f:


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

The file related methods

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

159
It reads one line from the file and places the file pointer to the beginning
7 File.readline([size])
of the new line.
It returns a list containing all the lines of the file. It reads the file until the
8 File.readlines([sizehint])
EOF occurs using readline() function.
It modifies the position of the file pointer to a specified offset with the
9 File.seek(offset[,from)
specified reference.
10 File.tell() It returns the current position of the file pointer within the file.
11 File.truncate([size]) It truncates the file to the optional specified size.
12 File.write(str) It writes the specified string to a file
13 File.writelines(seq) It writes a sequence of the strings to a file.

Demonstration

Experiment-1: Create a module fibo.py 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 fibo.py and __main__.py that
mentioned below

160
Output:

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 = os.listdir(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 os.path.isfile(file_path):
try:
# Printing the file pertaining to file_path
os.startfile(file_path, 'print')
print(f'Printing {file}')

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


# steady processing of the print operation.
time.sleep(5)

161
except:
# Catching if any error occurs and alerting the user
print(f'ALERT: {file} could not be printed! Please check\
the associated softwares, or the file type.')
else:
print(f'ALERT: {file} is not a file, so can not be printed!')

print('Task finished!')
Output:

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


Create following program structure and programs:

162
Program’s:

__main__.py:

Output:

163
Experiment-4:
Experiment-4:Write a python
Write program
a python to import
program module
to import from afrom
module package created created
a package in Experiment-3.
in Experiment-
3.
Program:

Output:

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

step-2:#stores all the data of the file into the variable content
content = fileptr.read(9);

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


print type(content)

step-4:#prints the content of the file


print content

step-5:#closes the opened file


fileptr close()

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

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

Step-2 # Function to count number


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

# variable to store total word count


num_words = 0

# variable to store total line count


num_lines = 0

# variable to store total character count


num_charc = 0

# variable to store total space count

165
num_spaces = 0

Step-3 # opening file using with() method


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

Step-4 # loop to iterate file


# line by line
for line in f:

Step-5 # incrementing value of


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

Step-6 # declaring a variable word


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

Step-8 # loop to iterate every


# line letter by letter
for letter in line:

Step-9 # condition to check


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

# incrementing the word


# count by 1
num_words += 1

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

Step-10 # condition to check


# that the encountered character

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

Step-11 # incrementing the space


# count by 1
num_spaces += 1

Step-12 # assigning value Y to


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

Step-13 # loop to iterate every


# letter character by
# character
for i in letter:

Step-14 # condition to check


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

# incrementing character
# count by 1
num_charc += 1

Step-15 # printing total word count


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

Step-16 # printing total line count


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

Step-17 # printing total character count


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

# printing total space count


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

Step -1# Driver Code:

167
if __name__ == '__main__':
fname = 'File1.txt'
try:
counter(fname)
except:
print('File not found')

Experiment-7:
Experiment-7:Program to read
Program image
to read file and
image filewrite to a new
and write to aimage file? file?
new image

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

step-2:# read an image with imread function


img = iio.imread("first.png")

step-3:# write it in a new format


iio.imwrite("firstjpg", img)

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

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

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

column 1 name,column 2 name, column 3 name


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

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

Example:

Consider the below CSV file –

Step-1:#Load import csv

Step-2:# opening the CSV file


with open('Giants.csv', mode ='r')as file:

Step-3:# reading the CSV file


csvFile = csv.reader(file)

Step-4 # displaying the contents of the CSV file


for lines in csvFile:
print(lines)
Output:

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


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

169

You might also like