Python Book R-22
Python Book R-22
PYTHON PROGRAMMING
A Comprehensive Smart Approach for Beginners to Learn
Python Language Using Best Practices
AUTHORS
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.
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
4
LAB OBJECTIVES
COURSE (LAB)OUTCOMES
5
SYLLABUS
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.
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
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?
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:
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.
➢ 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.
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.
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
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.
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
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.
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:
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are assigned to the
same memory location. You can also assign multiple objects to multiple variables.
For example –
a, b, c = 1, 2.5, ”mothi”
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and
one string object with the value "john" is assigned to the variable c.
The data stored in memory can be of many types. For example, a person's age is stored as a numeric value
and his or her address is stored as alphanumeric characters. Python has various standard data types that
are used to define the operations possible on them and the storage method for each of them.
Python has five standard data types:
• Numbers
• String
• Boolean
• List
• Tuple
• Set
• Dictionary
Python Numbers:
Number data types store numeric values. Number objects are created when you assign a value
to them.
Python supports four different numerical types:
• int (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.
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.
25
Float Floating point number Immutable
Demonstration:
26
Click here on the next 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.
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
32
To run the python IDE
33
Experimentation:
Experiment 3: Explore various IDEs for python program development.
Experiment 3: Explore various IDEs for python program development.
4.
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
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
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)
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
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
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:
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.
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.
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.
50
x = 5 print(x)
OUTPUT: 5
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.
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')
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.
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
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:
Demonastration:
Experiment-2: Write a program to read Employee data from the keyboard and print that data.
Program:
Name=input(“enter your name”)
Eid=input(“enter your empid”)
DOJ=input(“enter your Date of joining”)
address=input(“enter your address”)
print(Name)
print(Eid)
print(DOJ)
print(address)
output:
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
58
Lab 4:
Flow control describe the order in which statements will be executed at runtime.
These are of 3 types :
Conditional Statements/selection statements
Iterative Statements
Transfer Statements
Conditional Statements :
If we have to write a program in which we want to execute a code on behalf of conditions then we
come for Conditional Statements.
if:
if-else:
Nested if:
elif:
Decision making is the most important aspect of almost all the programming languages. As the name
implies, decision making allows us to run a particular block of code for a particular decision. Here, the
decisions are made on the validity of the particular conditions. Condition checking is the backbone of
decision making.
In python, decision making is performed by the following statements.
Statement Description
The if statement is used to test a specific condition. If the condition is true, a block of
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.
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
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 enables us to check multiple conditions and execute the specific block of statements
depending upon the true condition among them. We can have any number of elif statements in our
program depending upon our need. However, using elif is optional.
The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if
statement.
if expression 1:
# block of statements
elif expression 2:
# block of statements
elif expression 3:
# block of statements
else:
# block of statements
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.
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.
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
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)
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.
break
continue
pass
The break is a keyword in python which is used to bring the program control out of the loop. The break
statement breaks the loops one by one, i.e., in the case of nested loops, it breaks the inner loop first and
then proceeds to outer loops. In other words, we can say that break is used to abort the current
execution of the program and the control goes to the next line after the loop.
The break is commonly used in the cases where we need to break the loop for a given condition.
Example 1
list =[1,2,3,4]
count = 1
for i in list:
if i == 4:
print("item matched")
count = count + 1;
break
print("found at",count,"location")
Output:
item matched
found at 2 location
Example 2
str = "python"
for i in str:
if i == 'o':
70
break
print(i);
Output:
p
y
t
h
Output:
0 1 2 3 4 5 6 7 8 9 came out of while loop
The continue statement in python is used to bring the program control to the beginning of the loop. The
continue statement skips the remaining lines of code inside the loop and start with the next iteration. It
is mainly used for a particular condition inside the loop so that we can skip some specific code for a
particular condition.
Output:
infinite loop
Example 2
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.
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
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:
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.
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
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
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.
#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
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'
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.
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.
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
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)
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:
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.
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.
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.
Outputelcome to CodeRepublics
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.
Reduce functions:
The reduce() function in python is a part of the functools module and doesn't return multiple
values; it just returns a single value.
Steps of how to reduce function works in python:
The function passed as an argument is applied to the first two elements of the iterable.
After this, the function is applied to the previously generated result and the next element in the iterable.
This process continues until the whole iterable is processed.
The single value is returned as a result of applying the reduce function on the iterable.
Examples of Reduce Function in Python
Example using lambda function (Summing Numeric Values)
In this example, we have defined a lambda function that calculates the sum of two numbers on the passed
list as an iterable using the reduce function.
Code:
from functools import reduce
nums = [1, 2, 3, 4]
ans = reduce(lambda x, y: x + y, nums)
print(ans)
Output:
10
To provide a new name to this list, we can simply use assignment operator as:
In this case, we are having only one list of elements but with two different names 'x' and 'y'. Here, 'x' is
the original name and 'y' is the alias name for the same list. Hence, any modifications done to 'x' will 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
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?')
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-4: Program to filter only even numbers from the list by using filter() function?
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
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
96
my_string = 'Hello'
print(my_string)
my_string = "Hello"
print(my_string)
my_string = '''Hello'''
print(my_string)
Hello
Hello
Hello
Hello, welcome to
the world of Python
The index of -1 refers to the last item, -2 to the second last item and so on. We can access a range of
items in a string by using the slicing operator :(colon).
#first character
print('str[0] = ', str[0])
#last character
print('str[-1] = ', str[-1])
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.
If we want to access a range, we need the index that will slice the portion from the string.
Strings are immutable. This means that elements of a string cannot be changed once they have been
assigned. We can simply reassign different strings to the same name.
98
We cannot delete or remove characters from a string. But deleting the string entirely is possible using the
del keyword.
To learn more about the data types available in Python visit: Python Data Types
The + operator does this in Python. Simply writing two string literals together also concatenates them.
The * operator can be used to repeat the string for a given number of times.
# using +
print('str1 + str2 = ', str1 + str2)
# using *
print('str1 * 3 =', str1 * 3)
Run Code
When we run the above program, we get the following output:
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.
3 letters found
String Membership Test
We can test if a substring exists within a string or not, using the keyword in.
Some of the commonly used ones are enumerate() and len(). The enumerate() function returns an
enumerate object. It contains the index and value of all the items in the string as pairs. This can be useful
for iteration.
str = 'cold'
# enumerate()
list_enumerate = list(enumerate(str))
print('list(enumerate(str) = ', list_enumerate)
#character count
print('len(str) = ', len(str))
Run Code
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.
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.
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
# default(implicit) order
default_order = "{}, {} and {}".format('John','Bill','Sean')
print('\n--- Default Order ---')
print(default_order)
102
print(keyword_order)
Run Code
When we run the above program, we get the following output:
We can also format integers as binary, hexadecimal, etc. and floats can be rounded or displayed in the
exponent format. There are tons of formatting you can use. Visit here for all the string formatting
available with the format() method.
>>> x = 12.3456789
>>> print('The value of x is %3.2f' %x)
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"""
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”]
We can use range() function to generate a sequence of integers which can be stored in a list. To store
numbers from 0 to 10 in a list as follows.
numbers = list( range(0,11) )
print numbers # [0,1,2,3,4,5,6,7,8,9,10]
To store even numbers from 0 to 10in a list as follows. numbers = list( range(0,11,2) )
print numbers # [0,2,4,6,8,10]
Looping on lists:
We can also display list by using for loop (or) while loop. The len( ) function useful to know the numbers
of elements in the list. while loop retrieves starting from 0th to the last element i.e. n-1
Ex-1:
numbers = [1,2,3,4,5] for i in numbers:
print i,
Output:
12345
Example:
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.
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
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
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
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.
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.
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.
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.
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:
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.
You can add two tuples, because that just creates a new tuple (it doesn't change a or b):
a = (1, 2, 3)
b = (10, 20, 30)
c=a+b
print c #(1, 2, 3, 10, 20, 30)
You can do something a bit like the insert() function using slices:
Finding elements
You can use the count() and index() functions to find elements in a tuple. You can use the in and not in operators to check
for membership. The len() function also works with tuples.
Removing elements
You cannot use remove(), del or clear() on a tuple, for the obvious reason, again, that you cannot change a tuple. You can
create a new tuple, with some of the elements removed.
Looping
The list looping techniques work perfectly well with tuples:
Even in this case, you are not actually changing the tuple, only the list copy of it.
Demonstration
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:
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
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.
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.
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” ] )
Operations on set:
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}
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‟.
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'}
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'}
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?
130
Experiment-4:
Experiment-4:Write
Writea aprogram
programtotoeliminate duplicates
eliminate duplicatespresent
presentininthe
thelist
listusing
usingsetset?
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.
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?
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.
Here, we need to include this module into our main module to call the method displayMsg() defined in
the module named file.
The import statement is used to import all the functionality of one module into another. Here, we
must notice that we can use the functionality of any python source file by importing that file as the module
into another python source file.
We can import multiple modules with a single import statement, but a module is loaded once regardless
of the number of times, it has been imported into our file.
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
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
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 *.
Renaming a module:
Python provides us the flexibility to import some module with a specific name so that we can use
this name to use that module in our python source file.
Example
#the module calculation of previous example is imported in this example as cal.
import calculation as cal
a = int(input("Enter a?"))
b = int(input("Enter b?"))
print("Sum = ",cal.summation(a,b))
Output:
Enter a?10
Enter b?20
Sum = 30
The dir() function returns a sorted list of names defined in the passed module. This list contains all the
sub-modules, variables and functions defined in this module.
Consider the following example.
Example
import json
List = dir(json)
print(List)
Output:
['JSONDecoder', 'JSONEncoder', '__all__', '__author__',
'__builtins__', '__cached__', '__doc__',
'__file__', '__loader__', '__name__', '__package__', '__path__',
'__spec__', '__version__',
136
'_default_decoder', '_default_encoder', 'decoder', 'dump', 'dumps',
'encoder', 'load', 'loads', 'scanner']
for example, to reload the module calculation defined in the previous example, we must use the following
line of code.
reload(calculation)
Scope of variables:
In Python, variables are associated with two types of scopes. All the variables defined in a module
contain the global scope unless or until it is defined within a function.
All the variables defined inside a function contain a local scope that is limited to this function itself. We
can not access a local variable globally.
If two variables are defined with the same name with the two different scopes, i.e., local and global, then
the priority will always be given to the local variable.
Output:
Hi David
Python packages :
The packages in python facilitate the developer with the application development environment
by providing a hierarchical directory structure where a package contains sub-packages, modules, and
sub-modules. The packages are used to categorize the application level code efficiently.
Let's create a package named Employees in your home directory. Consider the following steps.
1. Create a directory with name Employees on path /home.
2. Create a python source file with name 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 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.
This tutorial teaches us about applying the math module from fundamentals to more advanced concepts
with the support of easy examples to understand the concepts fully. We have included the list of all built-
in functions defined in this module for better understanding.
Since the source code of this module is in the C language, it provides access to the functionalities of the
underlying C library. For instance,
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.
Euler's Number
Tau
Infinity
Pi
Not a Number (NaN)
Let's go over each of them one by one.
Euler's Number
The value 2.71828182845 of Euler's number is returned by the math.e constant.
math.e
Code
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.
math.tau
Code
math.inf
Code
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
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.
math.pi
Code
Code
# value of pi
pi_value = math.pi
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
nan
Mathematical Operations with Math Module
The functions that are required in representation theory and number theory, such as calculating the
factorial of an integer, will be covered in this part.
Code
x = 4.346
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
x=6
Code
x = -45
144
Code
Code
x=4
y=5
# returning x to the power of y.
print( f"The value of {x} to the power of {y} is: ", math.pow(x,y) )
Output:
Code
145
# Python program to show how to use the sin(), cos(), tan() function.
angle = math.pi / 4
The list includes the names of modules, each specified constants, functions, and methods. Here is a
straightforward illustration:
Code
functions = dir(math)
print( functions )
Output:
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan',
'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs',
'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', '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']
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
floor(x) gives back the biggest integer that is less than or equal to x.
fsum(iterable) returns the iterable's correct floating point sum of all values.
147
log2(x) gives x's base-2 logarithm back.
148
erfc(x) a function that gives the complementary error at x
lgamma(x) gives the natural logarithm of the gamma function's absolute value at x.
output:
2
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
Till now, we were taking the input from the console and writing it back to the console to interact with the
user.
Sometimes, it is not enough to only display the data on the console. The data to be displayed may be very
large, and only a limited amount of data can be displayed on the console, and since the memory is volatile,
it is impossible to recover the programmatically generated data again and again.
However, if we need to do so, we may store it onto the local file system which is volatile and can be
accessed every time. Here, comes the need of file handling.
We will learn all about file handling in python including,
creating a file,
opening a file,
closing a file,
Reading, Writing and appending the file, etc.
Opening a file:
Python provides the open() function which accepts two arguments, file name and access mode in which
the file is accessed. The function returns a file object which can be used to perform various operations
like reading, writing, etc.
The syntax to use the open() function is given below.
The files can be accessed using various modes like read, write, or append. The following are the details
about the access mode to open a file.
Access
SN Description
mode
It opens the file to read-only. The file pointer exists at the beginning. The file is by default
1 r
open in this mode if no access mode is passed.
It opens the file to read only in binary format. The file pointer exists at the beginning of
2 rb
the file.
3 r+ It opens the file to read and write both. The file pointer exists at the beginning of the file.
It opens the file to read and write both in binary format. The file pointer exists at the
4 rb+
beginning of the file.
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
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.
fileobject.close()
Example
# opens the file file.txt in read mode
fileptr = open("file.txt","r")
if fileptr:
print("file is opened successfully")
To read a file using the python script, the python provides us the read() method. The read() method reads
a string from the file. It can read the data in the text as well as binary format.
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);
152
#closes the opened file
fileptr.close()
Output:
<class 'str'>
Hi, I am
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();
Output:
<class 'str'>
Hi, I am the file and being used as
By looping through the lines of the file, we can read the whole file.
Example
#open the file.txt in read mode. causes an error if no such file exists.
fileptr = open("file.txt","r");
153
Output:
Hi, I am the file and being used as
an example to read a
file in python.
w: It will overwrite the file if any file exists. The file pointer is at the beginning of the file.
Consider the following example.
Example 1
#open the file.txt in append mode. Creates a new file if no such file exists.
fileptr = open("file.txt","a");
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");
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
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.
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")
#after the read operation file pointer modifies. tell() returns the location of the fileptr.
Output:
The filepointer is at byte : 0
After reading, the filepointer is at 26
<file-ptr>.seek(offset[, from)
offset: It refers to the new position of the file pointer within the file.
from: It indicates the reference position from where the bytes are to be moved. If it is set to 0, the
beginning of the file is used as the reference position. If it is set to 1, the current position of the file
pointer is used as the reference position. If it is set to 2, the end of the file pointer is used as the reference
position.
156
#initially the filepointer is at 0
print("The filepointer is at byte :",fileptr.tell())
Output:
The filepointer is at byte : 0
After reading, the filepointer is at 10
The os module provides us the rename() method which is used to rename the specified file to a new name.
rename(?current-name?, ?new-name?)
Example
import os;
The os module provides us the remove() method which is used to remove the specified file. The syntax
to use the remove() method is given below.
remove(?file-name?)
Example
import os;
#deleting the file named 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;
os.chdir("new")
Example
import os;
Deleting directory
Example
import os;
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
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}')
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:
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);
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
165
num_spaces = 0
# assigning value N to
# variable word because until
# space will not encounter
# a word can not be completed
word = 'N'
166
# is a white space
elif (letter == ' '):
# incrementing character
# count by 1
num_charc += 1
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
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:
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:
169