Python Programming CLASS
Python Programming CLASS
Notes Prepared by: Ramesh Prasad Bhatta Assistant professor FWU CSIT department
2
to compile a program before executing it. You can simply run the program.
Basically python converts source program into intermediate form called byte
code.
Dynamic and strongly typed language: Python is strongly typed as the
interpreter keeps track of all variables types. It's also very dynamic as it rarely
uses what it knows to limit variable usage.
Extensible: Since Python is an open source software, anyone can add low-level
modules to the python interpreter. These modules enable programmers to add to
or customize their tools to work more efficiently.
Embeddable: Programmers can embed Python within their C, C++, COM,
ActiveX, CORBA and Java Programs to give „scripting „capability for users.
Extensive Libraries: Python has huge set of libraries that is easily portable
across different platforms with different operating systems.
Easy maintenance: Code Written in Python is easy to maintain.
Secure: This Programming language is secure for tampering. Modules can be
distributed to prevent altering of source code. Additionally, Security checks can
be easily added to implement additional security features.
Robust: Python Programmers cannot manipulate memory directly, errors are
raised as exceptions that can be catch and handled by the program code. For
every syntactical mistake, a simple and easy to interpret message is displayed. All
these make python robust.
Multi-threaded: Python supports executing more than one process of a program
simultaneously with the help of Multi Threading.
Garbage Collection: The Python run-time environment handles garbage
collection of all python objects. For this, a reference counter is maintained to
assure that no object that is currently in use is deleted.
Notes Prepared by: Ramesh Prasad Bhatta Assistant professor FWU CSIT department
3
It has been derived from many languages such as ABC, Modula-3, C, C++, Algol-
68, SmallTalk, UNIX shell and other scripting languages.
Since early 90‟s Python has been improved tremendously. Its version 1.0 was
released in 1991, which introduced several new functional programming tools.
Notes Prepared by: Ramesh Prasad Bhatta Assistant professor FWU CSIT department
4
imaging software such as Inkscape, GIMP, Paint Shop Pro and Scribus. It is also
used to make 3D animation packages, like Blender, 3ds Max, Cinema 4D,
Houdini, Light wave and Maya.
Scientific and Computational applications: Features like high speed,
productivity and availability of tools, such as Scientific Python and Numeric
Python, have made Python a preferred language to perform computation and
Notes Prepared by: Ramesh Prasad Bhatta Assistant professor FWU CSIT department
5
as elif if or yield
2. Literal Constants
In programming constants are referred to variables that cannot be changed.
Generally Literal constants are classified in to three types.
Literal Constants
Notes Prepared by: Ramesh Prasad Bhatta Assistant professor FWU CSIT department
6
The value of a literal constant can be used directly in programs. For example,
7, 3.9, 'A', and "Hello" are literal constants.
Numbers refers to a numeric value. You can use four types of numbers in
Python program- integers, long integers, floating point and complex
numbers.
Numbers like 5 or other whole numbers are referred to as integers. Bigger
whole numbers are called long integers. For example, 535633629843L is a
long integer.
Numbers like are 3.23 and 91.5E-2 are termed as floating point numbers.
Numbers of a + bj form (like -3 + 7j) are complex numbers.
Examples:
2.3 String Literals
A string is a group of characters.
Using Single Quotes ('): For example, a string can be written as 'HELLO'.
Notes Prepared by: Ramesh Prasad Bhatta Assistant professor FWU CSIT department
7
Using Double Quotes ("): Strings in double quotes are exactly same as those in
single quotes. Therefore, 'HELLO' is same as "HELLO".
Using Triple Quotes (''' '''): You can specify multi-line strings using triple quotes.
You can use as many single quotes and double quotes as you want in a string
within triple quotes.
Examples:
Unicode is a standard way of writing international text. That is,if you want to
write some text in your native language like hindi,then you need to have a
Unicode-enable text editor.
Python allows you to specify Unicode text by prefixing the string with a u or U.
For Example: u”Sample Unicode string”
Note :The „U‟ prefix specifies that the file contains text written in language
other than English
2.3.2Raw Strings
Notes Prepared by: Ramesh Prasad Bhatta Assistant professor FWU CSIT department
8
If you want to specify a string that should not handle any escape sequences
and want to display exactly as specified then you need to specify that string as
a raw string. A raw string is specified by prefixing r or R to the string.
Example:
3. Data types
The variables can hold values of different type called Data Type.
Data type is a set of values and the allowable operations on those values.
Python has a great set of useful data types. Python's data types are built in the
core of the language. They are easy to use and straightforward.
Example a person age is stored in a number ,his name is made only with
characters, and his address is made with mixture of numbers and characters.
Python ha various standard data types to define the operations possible on
them and storage method for each of them.
Python supports the following five standard data
types
1.Numbers
2.Strings 3.
Lists 4.Tuple
5.Dictionary
Note: Python is pure object oriented programming language.it refers to
everything as an object including numbers and strings.
Notes Prepared by: Ramesh Prasad Bhatta Assistant professor FWU CSIT department
9
Numbers
String
Boolean Lists Dictionaries Sets
Notes Prepared by: Ramesh Prasad Bhatta Assistant professor FWU CSIT department
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
In Python , you can reassign variables as many times as you want to change
the value stored in them. You may even store value of one data type in a
statement and other data type in subsequent statement. This is possible
because Python variables do not have specific types, i.e., we can assign integer
to the variable, later we assign string to the same variable.
Example:Program to reassign value to a variable
val = „Hello‟
print(val)
val = 100
print(val)
val=10.32
print(val)
10
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Output
Hello
100
10.32
3.1.2Multiple Assignments
Python allows programmers to assign single value to more than one variable
simultaneously.
For example
>>>sum = flag = a = b = 0
In the above statement, all four integer variables are assigned a value 0.You
can also assign different values to multiple variables simultaneously as shown
below
For example
>>>sum, a, b, mesg = 0, 3, 5, “Result”
Note: Removing a variable means that the reference from the name to the value has
been deleted.However, deleted variables can be used again in the code if and only if
you reassign them some value.
Similar to other variables, the Boolean variables are also created while we assign a
value to them or when we use a relational operator on them.
3.3 Tuples
The main difference between lists and tuples is that you can change the values
in a list but not in a tuple. This means that while tuple is a read only data type,
the list is not.
Examples:
3.4 Lists
Lists are the most versatile data type of Python language.
A list consist of items separated by commas and enclosed within square
brackets The values stored in a list are accessed using indexes.
The index of the first element being 0 and n-1 as that of the last element,
where n is the total number of elements in the list. Like strings, you can also
use the slice, concatenation and repetition operations on lists.
Example program to demonstrate operations on lists
list = ['a', 'bc', 78, 1.23]
print(list)
print(list[0])
print(list[1:3])
print(list[2:])
print(list * 2)
print(list + list1)
Output:
['bc', 78]
[78, 1.23]
12
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
3.5 Dictionary
Python‟s dictionaries stores data in key-value pairs.
The key values are usually strings and value can be of any data type. The key
value pairs are enclosed with curly braces ({ }).
Each key value pair separated from the other using a colon (:). To access any
value in the dictionary, you just need to specify its key in square braces
([]).Basically dictionaries are used for fast retrieval of data.
Example
4.1 Variables
Variable means its value can vary. You can store any piece of information in a
variable.
Variables are nothing but just parts of your computer‟s memory where
information is stored. To identify a variable easily, each variable is given an
appropriate name.
4.2 Identifiers
13
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
5. Operators
Operators are special symbols in Python that carry out arithmetic or logical
computation. The value that the operator operates on is called the operand.
For example:
>>> 2+3
Here, + is the operator that performs addition. 2 and 3 are the operands
and 5 is the output of the operation.
14
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
15
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
operator.
Unary minus operator is strikingly different from the arithmetic operator that
operates on two operands and subtracts the second operand from the first
operand.
When an operand is preceded by a minus sign, the unary operator negates its
value.
For example, if a number is positive, it becomes negative when preceded with a
unary minus operator. Similarly, if the number is negative, it becomes positive
after applying the unary minus operator. Consider the given example.
b = 10 a = -(b)
Bitwise Operators
As the name suggests, bitwise operators perform operations at the bit level.
These operators include bitwise AND, bitwise OR, bitwise XOR, and shift
operators.
Bitwise operators expect their operands to be of integers and treat them as a
sequence of bits.
The truth tables of these bitwise operators are given below.
Example: If a=60 and b=13 then look at the table below, to see the result of
Bitwise operations.
16
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
~ (~a ) = -61
It is unary and has the effect of (means 1100 0011
Binary Ones 'flipping' bits. in 2's complement
Complement form due to a
signed binary
number.
Python supports two bitwise shift operators. They are shift left (<<) and shift
right (>>).
These operations are used to shift bits to the left or to the right. The syntax for
a shift operation can be given as follows:
Examples:
17
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Logical NOT (not) operator takes a single expression and negates the value of
the expression. Logical NOT produces a zero if the expression evaluates to a
non-zero value and produces a 1 if the expression produces a zero. In other
words, it just reverses the value of the expression.
For example, a = 10; b = not a; Now, the value of b = 0.
Python supports two types of membership operators–in and not in. These
operators, test for membership in a sequence such as strings, lists, or tuples.
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
19
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
|= x |= 5 x=x|5
^= x ^= 5 x=x^5
Operators Meaning
() Parentheses
** Exponent
+, - Addition, Subtraction
20
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
^ Bitwise XOR
| Bitwise OR
or Logical OR
6. Input Operation
To take input from the users, Python makes use of the input( ) function. The
input( ) function prompts the user to provide some information on which the
program can work and give the result.
However, we must always remember that the input function takes user‟s input
as a string.
Example:
7. Comments
Comments are the non-executable statements in a program. They are just
added to describe the statements in the program code.
Comments make the program easily readable and understandable by the
programmer as well as other users who are seeing the code. The interpreter
simply ignores the comments.
21
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
In Python, a hash sign (#) that is not inside a string literal begins a comment.
All characters following the # and up to the end of the line are part of the
comment
Example:
Note: For writing Multi line comments. Make sure to indent the leading „ „
„ appropriately to avoid an Indentation Error
„„„
This is a multiline
comment.
„„„
8. Indentation
Whitespace at the beginning of the line is called indentation. These whitespaces
or the indentation are very important in Python.
In a Python program, the leading whitespace including spaces and tabs at the
beginning of the logical line determines the indentation level of that logical line.
Example:
9. Expressions
22
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Example Program:
Give the output for the following statements.( April 2018 Regular)
a = 20
b = 10
c = 15
d=5
e = (a + b) * c / d
e = ((a + b) * c) / d
e = (a + b) * (c / d)
e = a + (b * c) / d
Output:
Value of (a + b) * c / d is 90.0
Value of (a + b) * (c / d) is 90.0
Value of a + (b * c) / d is 50.0
3. String slicing.
Like numbers we can add two strings in Python. The process of combining two
strings is called concatenation.
Two strings whether created using single or double quote are concatenated in
the same way.Look at the codes given in the following example.
Example: Codes to demonstrate how easily two strings are concatenated.
>>>print(“hello” + “-world”)
24
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
output
hello-world
>>>print(“hello”+‟-world‟)
output
hello-world
>>print(„hello‟+‟-world‟)
output
hello-world.
>>print(“hello” * 5)
Output
>>print(5 * “hello”)
Output
Note:We cannot multiply two strings and cannot multiply string with floating
point number.
You can extract subsets of strings by using the slice operator ([ ] and [:]). You
25
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
print(str[3:9])
print(str[4:])
print(str[-1])
print(str[:5])
print(str * 2)
print(str + „Isn‟t
gec‟) Output
on is easy
Pytho
Type Conversion
Output Output
„2030‟ 5
print(x+y)
output
67
Example2:
x=int(input(“Enterthefirstnumber))
y=int(input(“Enterthesecondnumber))
print(x+y)
Output
Enterthefirstnumber6
Enerthesecondnumber7
Python provides various built-in functions to convert value from one data type to another
datatype.The following are the functions return new object representing the coverted value.
27
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
13 Limitations of Python:
Parallel processing can be done in Python but not as elegantly as done in some
other languages (like JavaScript and Go Lang).
Being an interpreted language, Python is slow as compared to C/C++. Python
is not a very good choice for those developing a high-graphic 3d game that
takes up a lot of CPU.
As compared to other languages, Python is evolving continuously and there is
little substantial documentation available for the language.
As of now, there are few users of Python as compared to those using C, C++ or
Java.
It lacks true multiprocessor support.
It has very limited commercial support point.
Python is slower than C or C++ when it comes to computation heavy tasks and
desktop applications.
It is difficult to pack up a big Python application into a single executable file.
This makes it difficult to distribute Python to non-technical.
Procedure for Executing your First Python Program
Step1: Type the program in notepad and save your python program with the
following extension
Filename.py
28
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Step4: For running your Python program click on run tab on the top of the
separate window in the previous step and select run module or simply press
F5.
1. simplemsg.py
print(“Hello World”)
Output
Hello World
2. sumoftwonumbers.py
res=num1+num2
print(str(num1)+"+"+str(num2)+"="+str(res))
Output:
10+20=30
3. distancebetweentwopoints.py
x1=(int(input("Enter x1")))
x2=(int(input("Enter y1")))
y1=(int(input("Enter x2")))
y2=(int(input("Enter y2")))
distance=((x2-x1)**2+(y2-y1)**2)**0.5
print("Distance Between two points")
print(distance)
Output:
Enter x1 8
Enter y1 9
Enter x2 10
Enter y2 12
2.2360679775
Control Statements:
Un-conditional Control:
if Statement
if-else Statement
30
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Nested if statement
if-elif-else statement.
1. 1 if Statement:
Syntax:
if test_expression:
statement 1
.....
statement n
statement x
if structure may include 1 or n statements enclosed within if block.
Flow chart:
Example:
31
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Syntax:
if (test expression):
statement_block 1
else:
statement_block 2
statement x
If the condition is true, then it will execute statement block 1 and if the
condition is false then it will execute statement block 2.
Flowchart:
To perform more complex checks, if statements can be nested, that is, can
be placed one inside the other.
In such a case, the inner if statement is the statement part of the outer one.
Nested if statements are used to check if more than one conditions are
satisfied.
32
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
var = 100
if var < 200:
Output:-
Expression value is less than 200
Which is 100
Good bye!
1.4 if-elif-else Statement :
A series of if and elif statements have a final else block, which is executed if
none of the if or elif expressions is True.
Syntax:
statement block1
33
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
statement block2
. . . . . . . . . . . . . . ..
statement block N
else:
statement block X
34
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Flowchart:
Program: To test whether a number entered by the user is negative, positive, or zero
Iterative statements are decision control statements that are used to repeat the
execution of a list of statements.
Syntax:
Statement x
while (condition):
Statement block
Statement y
35
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
36
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
In while loop, the condition is tested before any of the statements in the
statement block is executed.
Flowchart:
print(i, end=‖ ―)
i=i+1
Output: 0 1 2 3 4 5 6 7 8 9 10
Syntax:
37
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
38
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Flowchart:
Syntax:
Example: Program to print first n numbers using the range() in a for loop
o If range( ) is called with two arguments, it produces values from the first to
the second. For example, range(0, 10) gives 0-9.
39
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
40
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
o If range( ) has three arguments then the third argument specifies the
interval of the sequence produced. In this case, the third argument must be
an integer. For example, range(1, 20, 3) gives 1, 4, 7, 10, 13, 16, 19.
Example:
1. Program that accepts an integer (n) and computes the value of n+nn+nnn.
(Eg. If n=5, find 5+55+555).
for i in s:
str = i + str
Although this feature will work with any loop like while loop as well as for
loop.
A for loop can be used to control the number of times a particular set of
statements will be executed.
41
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
42
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Another outer loop could be used to control the number of times that a
whole loop is repeated.
Example:
The break statement is widely used with for loop and while loop.
Syntax:
43
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
44
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Break
Above code is meant to print first 10 numbers using a while loop, but it
will actually print only numbers from 0 to 4. As soon as i becomes equal to
5, the break statement is executed and the control jumps to the following
while loop.
Hence, the break statement is used to exit a loop from any point with in its
body, by passing its normal termination expression. Below, Figure shows
the transfer of control when the break statement is encountered.
Like the break statement, the continue statement can only appear in the
body of a loop.
When the compiler encounters a continue statement then the rest of the
statements in the loop are skipped and the control is unconditionally
transferred to the loop-continuation portion of the nearest enclosing loop.
Syntax:
Continue
45
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Note that the code is meant to print numbers from 0 to 10.But as soon as i
becomes equal to 5, the continue statement is encountered, so rest of the
statements in the loop are skipped. In the output, 5 is missing as continue
caused early increment of i and skipping of statement that printed the value
of i on screen.
The difference between a comment and pass statement is that while the
interpreter ignores a comment entirely, pass is not ignored.
46
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
47
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Example:
1. Program to demonstrate pass statement
The continue statement skips the rest of the statements in the loop transfer
the control un-conditionally to the loop-continuation portion of the nearest
enclosing loop.
48
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
49
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
3. Programs:
3. 1 Write a python program to Test whether a given number is even or odd.
num = int(input("Enter a number: "))
if (num % 2==0):
print(num, "is an even number.")
else:
Output:
Enter a number: 5
5 is an odd number.
3. 2 Write a python program to Print out the decimal equivalents of 1/1, 1/2, 1/3,
1/4.............1/10 using for loop.
i=1
for i in range(1,11):
value=1.0/i
Output:
1/ 1 = 1.0
1/ 2 = 0.5
1/ 3 = 0.333333333333
1/ 4 = 0.25
1/ 5 = 0.2
1/ 6 = 0.166666666667
1/ 7 = 0.142857142857
1/ 8 = 0.125
1/ 9 = 0.111111111111
1/ 10 = 0.1
50
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
51
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
3. 3. Write a python program to Print a count down from the given number to zero
using a while loop.
0
3.4. Write a python program to Find the sum of all the primes below hundred.
sum=0
for j in range(1,100):
for i in range(2,j):
if (j% i) == 0:
break
else:
utput:
53
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
while (num>0):
fact=fact*num
num=num-1
print("Factorial of", num, "is",fact)
Output:
Enter a number: 6
Factorial of 6 is 720
54
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
55
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Learning Material
Functions
A function is a block of organized and reusable program code that performs a
single, specific, and well-defined task.
Python enables its programmers to break up a program into functions, each of
which can be written more or less independently of the others. Therefore, the
code of one function is completely insulated from the codes of the other
functions.
called function. After called function is executed, the control is returned back
to the calling program.
It is not necessary that the func1() can call only one function, it can call as
many functions as it wants and as many times as it wants. For example, a
function call placed within for loop or while loop may call the same
function multiple times until the condition holds true.
to use functions.
Function Declaration and Definition:
• A function, f that uses another function g, is known as the calling function and g is
known as the called function.
58
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
60
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Figure 8: Arguments may be passed in the form of expressions to the called function.
61
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
62
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
63
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Figure 10: lists the differences between global and local variables.
64
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
66
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Resolution of names
Scope defines the visibility of a name within a block. If a local variable is defined in a
block, its scope is that particular block. If it is defined in a function, then its scope is
all blocks within that function.
When a variable name is used in a code block, it is resolved using the nearest
enclosing scope. If no variable of that name is found, then a NameError is raised. In
the code given below, str is a global string because it has been defined before calling
the function.
Figure 12: Program that demonstrates using a variable defined in global namespace.
The Return Statement
The syntax of return statement is,
return [expression]
The expression is written in brackets because it is optional. If the expression is
present, it is evaluated and the resultant value is returned to the calling function.
However, if no expression is specified then the function will return none.
The return statement is used for two things.
• Return a value to the caller
• To end and exit a function and go back to its caller
Figure 13: Program to write another function which returns an integer to the caller.
More on defining functions:
In this section we will discuss some more ways of defining a function.
67
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
1. Required arguments
68
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
Required Arguments
In the required arguments, the arguments are passed to a function in correct
positional order. Also, the number of arguments in the function call should exactly
match with the number of arguments specified in the function definition
Example:
Keyword Arguments
When we call a function with some values, the values are assigned to the arguments
based on their position. Python also allow functions to be called using keyword
arguments in which the order (or position) of the arguments can be changed. The
values are not assigned to arguments according to their position but based on their
name (or keyword).
Keyword arguments are beneficial in two cases.
• First, if you skip arguments.
• Second, if in the function call you change the order of parameters.
Example:
Default Arguments
Python allows users to specify function arguments that can have default values. This
means that a function can be called with fewer arguments than it is defined to have.
69
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
70
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
That is, if the function accepts three parameters, but function call provides only two
arguments, then the third parameter will be assigned the default (already specified)
value. The default value to an argument is provided by using the assignment operator
(=). Users can specify adefault value for one or more arguments.
Example:
Variable-length Arguments
In some situations, it is not known in advance how many arguments will be passed to
a function. In such cases, Python allows programmers to make function calls with
arbitrary (or any) number of arguments.
When we use arbitrary arguments or variable length arguments, then the function
definition use an asterisk (*) before the parameter name. The syntax for a
function using variable arguments can be given as,
Example:
72
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Lambda functions are throw-away functions, i.e. they are just needed where they
have been created and can be used anywhere a function is required. The lambda
feature was added to Python due to the demand from LISP programmers.
Lambda functions contain only a single line. Its syntax can be given as,
Example
Documentation Strings
Docstrings (documentation strings) serve the same purpose as that of comments, as
they are designed to explain code. However, they are more specific and have a proper
syntax.
Example:
Recursive Functions
A recursive function is defined as a function that calls itself to solve a smaller version
of its task until a final call is made which does not require a call to itself. Every
recursive solution has two major cases, which are as follows:
• base case, in which the problem is simple enough to be solved directly without
making any further calls to the same function.
• recursive case, in which first the problem at hand is divided into simpler sub parts.
Recursion utilized divide and conquer technique of problem solving.
73
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
74
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Example:
Recursion vs Iteration:
Recursion is more of a top-down approach to problem solving in while the original
problem is divided into smaller sub-problems.
Iteration follows a bottom-up approach that begins with what is known and then
constructing the solution step-by-step.
Pros The benefits of using a recursive program are:
Recursive solutions often tend to be shorter and simpler than non-recursive
ones.
Code is clearer and easier to use.
Recursion uses the original formula to solve a problem.
It follows a divide and conquer technique to solve problems.
In some instances, recursion may be more efficient.
Cons The limitations of using a recursive program are:
For some programmers and readers, recursion is difficult concept.
Recursion is implemented using system stack. If the stack space on the system
is limited, recursion to a deeper level will be difficult to implement.
Aborting a recursive process in midstream is slow and sometimes nasty.
Using a recursive function takes more memory and time to execute as
compared to its non-recursive counterpart.
It is difficult to find bugs, particularly when using global variables.
Conclusion: The advantages of recursion pays off for the extra overhead involved in
terms of time and space required.
75
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Modules
We have seen that functions help us to reuse a particular piece of code.
Module goes a step ahead. It allows you to reuse one or more functions in your
programs, even in the programs in which those functions have not been
defined.
Putting simply, module is a file with a.py extension that has definitions of all
functions and variables that you would like to use even in other programs. The
program in which you want to use functions or variables defined in the module
will simply import that particular module (or .py file).
Modules are pre-written pieces of code that are used to perform common
tasks like generating random numbers, performing mathematical operations,
etc.
The basic way to use a module is to add import module_name as the first line
of your program and then writing module_name.var to access functions and
values with the name var in the module.
The from…import Statement
A module may contain definition for many variables and functions. When you import
a module, you can use any variable or function defined in that module. But if you
want to use only selected variables or functions, then you can use the from...import
statement. For example, in the aforementioned program you are using only the path
variable in the sys module, so you could have better written from sys import path.
Example:
To import more than one item from a module, use a comma separated list. For
example, to import the value of pi and sqrt() from the math module you can write,
Every Python program is a module, that is, every file that you save as .py extension is
a module.
Modules should be placed in the same directory as that of the program in which
it is imported. It can also be stored in one of the directories listed in sys.path.
77
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
The main module may import any number of other modules which may in turn
import other modules. But the main module of a Python program cannot be
imported into other modules.
79
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
80
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
81
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
2. Write function to compute gcd, lcm of two numbers. Each function shouldn‟t
exceed one line.
Program:
from fractions import gcd
print gcd(5,25)
def lcm():
a=60
b=40
print (a * b) // gcd(a, b)
lcm()
output:
82
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
83
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
3. Find the sum of the even-valued terms in the Fibonacci sequence whose values do
not exceed ten thousand.
program:
i=0
j=1
sum=0
while(i<10000):
i=i+j
j=i-j
if(i%2==0):
sum+=i
print sum
output:
84
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
85
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Strings
86
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
87
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
88
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
89
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
90
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
91
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
92
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
93
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Programs:
1. Write a program that accepts a string from a user and re-displays the same after
removing vowels from it.
Program:
while True:
print('Enter x for exit.')
string = raw_input('Enter any string: ')
if string == 'x':
break
else:
newstr = string
94
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
95
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
96
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
97
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
output:
output:
98
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
99
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Tuples
Tuple Definition:
1. A tuple is a sequence of immutable objects. That is, you can change the value of
one or more items in a list; you cannot change the values in a tuple.
2. Tuples use parenthesis to define its elements. Whereas lists use square brackets.
Creating a Tuple:
Syntax: Tup1=(val1,val2,….)
Where val (or values) can be an integer, a floating number, a character, or a string.
Examples:
output:
Output:
100
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
characters print(Tup2)
101
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
print(Tup3)
numbers print(Tup4)
print(Tup5)
Output:
1,2,3,4,5
„a‟,‟b‟,‟c‟,‟d‟
„abc‟,‟def‟,‟ghi‟
1.2,2.3,3.4,4.5,5.6
1,‟abc‟,2.3,‟d‟
Output:
A bcd2 4.6
print(a,b)
Output:
10 20
102
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
103
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Example :
1) Tup1=(1,2,3,4,5,6,7,8,9,10)
print(“Tup[3:6]=”,Tup1[3:6])
print(“Tup[:8]=”,Tup1[:4])
print(“Tup[4:]=”,Tup1[4:])
print(“Tup[:]=”,Tup1[:])
Output:
Tup[3:6]=(4,5,6)
Tup[:8]=(1,2,3,4)
Tup[4:]=5,6,7,8,9,10)
Tup[:]=(1,2,3,4,5,6,7,8,9,10)
2) Tuple =(1,2,3,4,5.5,‟str‟)
Input:
1. print tuple
2. print tuple[5]
3. print tuple[1:5]
104
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
105
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Output:
1.1,2,3,4,5.5,‟str‟
2.‟str‟
3.2,3,4,5.5
Updating tuples:
As we all know tuples are immutable objects so we cannot update the values but we
can just extract the values from a tuple to form another tuple.
Example:
1) Tup1=(1,2,3,4,5)
Tup2=(6,7,8,9,10)
Tup3=Tup1+Tup2
print(Tup3)
Output:
(1,2,3,4,5,6,7,8,9,10)
2) Tup1=(1,2,3,4,5)
Tup2=(„sree‟,‟vidya‟,‟ram‟)
Tup3=Tup1+Tup2
print Tup3
Output:
(1,2,3,4,5,‟sree‟,‟vidya‟,‟ram‟)
106
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
107
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Hence there is another option to delete a single element of a tuple i.e..,you can create
a new tuple that has all elements in your tuple except the ones you don‟t want.
Example:
1) Tup1=(1,2,3,4,5)
del Tup1[3]
print Tup1
Output:
del Tup1[3]
2) however, you can always delete the entire tuple by using del statement.
Tup1=(1,2,3,4,5)
del Tup1
print Tup1
Output:
108
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
109
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Key Note: Note that exception is raised because you are now trying to print a tuple
that has already been deleted.
Like strings and lists,you can also perform operations like concatenation,
repetition,etc. on tuples. The only difference is that a new tuple should be created
when a change is required in an existing tuple.
Length len((1,2,3,4,5,6)) 6
print(i,end=‟ „)
Tup2=(1,2,3,4,5)
print(Tup1>Tup2)
Maximum max(1,0,3,8,2,9) 9
Minimum min(1,0,3,8,2,9) 0
111
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Ex:
Input:
Tup1= (1,2,3,4,5)
Output:
2) Concatenation:
Ex:
Input:
Tup1=(1,2,3,4)
Tup2=(5,6,7)
print tup1+tup2
Output:
(1,2,3,4,5,6,7)
3) Repetition:
Ex:
Input:
Tuple1=(„my‟)
112
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
113
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
print tuple1*3
Output:
(„my‟,‟my‟,‟my‟)
4) Membership:
Ex:
Input:
Tuple1=(1,2,3,4,6,7)
5) Iteration:
Ex:
Input:
For i in (1,2,3,4,5,6,7,8,9,10):
print (i,end=‟ „)
Output:
1,2,3,4,5,6,7,8,9,10
6) Comparison:
Ex:
Input:
Tup1 = (1,2,3,4,5)
Tup2 =(6,7,8,9,10)
print(Tup1<tup2)
Output:
114
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
True
7) Maximum:
Ex:
Input:
Max(1,2,6,5,4)
Output:
8) Minimum:
Ex:
Input:
Min(1,2,3,4,5)
Output:
9) Convert to tuple:
Ex:
Input:
Tuple(“vidya”)
Output:
(„v‟,‟i‟,‟d‟,‟y‟,‟a‟)
115
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
116
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
LISTS
The most basic data structure in Python is the sequence. Each element of a
sequence is assigned a number - its position or index. The first index is zero, the
second index is one, and so forth. There are certain things you can do with all
sequence types. These operations include indexing, slicing, adding, multiplying, and
checking for membership.
Creating a List:
Syntax:
List_variable = [val1,val2,…]
Example:
1) list_A =[1,2,3,4]
print(list_A)
Output
[1,2,3,4]
2) list_C=[„Good”,”Going”]
print(list_C)
Output
[‘Good’,’Going’]
117
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
118
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
syntax
s=list[start:stop:step]
For Example:
Example 1:
num_list=[1,2,3,4,5,6,7,8,9,10]
print(“num_list is:”,num_list)
print(“num_list[2:5]=”,num_list[2:5])
print(“num_list[::2]=”,num_list[::2])
print(“num_list[1::3]=”,num_list[1::3])
Output:
num_list[2:5]= [3,4,5]
num_list[::2]= [1,3,5,7,9]
num_list[1::3]= [2,5,8]
once created, one or more elements of a list can be easily updated by giving the
slice on the left-hand side of the assignment operator.
119
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
120
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
You can also append new values in the list and remove existing values from the
list using the append( ) method and del statement respectively.
Example:
1) num_list= [1,2,3,4,5,6,7,8,9,10]
print(“list is:”,num_list)
num_list[5]=100
num_list.append(200)
del num_list[3]
Output:
121
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
122
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
tion
print(max(num_list))
print(min(num_list))
print(“SUM=”,sum(nu
m_list))
123
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
124
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Mutability of lists:
Example:
print(fruit)
fruit[0] = "pear"
fruit[-1] = "orange"
print(fruit)
Output:
125
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
126
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Functional Programming:
1) map( ) Function:
The map() function applies a particular function to every element of a
list.
Syntax:
map(function,sequence)
After applying the specified function in the sequence, the map( ) function
returns the modified list.
def add_2(x):
x+=2
return x
num_list=[1,2,3,4,5,6,7]
new_list=list(map(add_2,num_list))
output:
2) reduce ( ):
127
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
128
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
The reduce( ) function with syntax as given below returns a single value
generated by calling the function on the first two items of the sequence,
then on the result and the next item and so on.
Syntax: reduce(function,sequence)
Ex: Program to calculate the sum of values in a list using the reduce( )
function.
def add(x,y):
return x+y
num_list=[1,2,3,4,5]
print(functools.reduce(add,num_list))
Output:
3) filter( ) function:
It constructs a list from those elements of the list for which a function
returns True.
Syntax:
filter(function,sequence)
As per the syntax filter( ) function returns a sequence that contains items from
the sequence for which the function is True. If sequence is a string, Unicode, or a
tuple, then the result will be the same type;
129
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
130
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
def check(x):
return 1
evens=list(filter(check,range(2,22))
print(evens)
Output:
[2,4,6,8,10,12,14,16,18,20]
programs:
Program: (val1,val2,val3)=(1,2,3)
(tup1,tup2,tup3)=(4,5,6)
(a,b,c)=(val1,val2,val3)
(val1,val2,val3)=(tup1,tup2,tup3)
(tup1,tup2,tup3)=(a,b,c)
print (val1,val2,val3)
print (tup1,tup2,tup3)
Output:
(4, 5, 6)
(1, 2, 3)
131
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
132
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Program: tup=[5,1,40,8,6,2,1]
print(sorted(tup))
Output:
[1, 1, 2, 5, 6, 8, 40]
3. Write program that scans an email address and forms a tuple of user name and
domain name.
Program:
Output:
4. Write a program to print sum and average of the elements present in the list.
Program:
lst = [ ]
for n in range(num):
133
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
134
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
lst.append(numbers)
avg=sum(lst)/num
print(avg)
Output:
Enter number 1
Enter number 2
Enter number 3
Enter number 4
Enter number 5
Enter number 6
Enter number 7
Sum of elements in given list is : 28
5. Write a program that forms a list of first character of every word present in
another list.
Program:
b= [ ]
l= ["gudlavalleru","engineering","college"]
for item in l:
b.append(item[0])
print(b)
Output: [„g‟,‟e‟,‟c‟]
135
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
136
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Dictionary:
o It is a data structure in which we store values as a pair of key and value.
o Each key is separated from its value by a colon (:), and consecutive items
are separated by commas.
o The entire items in a dictionary are enclosed in curly brackets ({}).
Syntax:
dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3}
If there are many keys and values in dictionaries, then we can also write just one
key-value pair on a line to make the code easier to read and understand. This is
shown below.
dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3 , ….}
o Keys in the dictionary must be unique and be of any immutable data type (like
Strings, numbers, or tuples), there is no strict requirement for uniqueness and
type of values.
o Values of a key can be of any type.
o Dictionaries are not Sequences, rather they are mappings.
o Mappings are collections of objects that are store objects by key instead of by
relative position.
Creating a Dictionary:
o The Syntax to create an empty dictionary can be given as:
Dictionary_variable= { }
o The Syntax to create a dictionary with key-value pair is:
Dictionary_variable= {key1:val1, key2:val2……}
o A dictionary can be also created by specifying key-value pairs separated
by a colon in curly brackets as shown below.
o Note that one key value pair is separated from the other using a comma.
Example:
d= {'roll_no':'18/001','Name:':'Arav','Course':'B.tech'}
print(d)
Output: {'Name:': 'Arav', 'Course': 'B.tech', 'roll_no': '18/001'}
137
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Accessing Values:
In Dictionary, through key accessing values,
Example:
d={'Name': 'Arav', 'Course': 'B.tech', 'roll_no': '18/001'}
print('d[Name]:',d['Name'])
print('d[course]:',d['Course'])
print('d[roll_no]:',d['roll_no'])
output:
d[Name]: Arav
d[course]: B.tech
d[roll_no]: 18/001
Adding and Modifying an Item in a Dictionary:
To add a new entry or a key-value pair in a dictionary, just specify the key-
value pair as you had done for the existing pairs.
Syntax: dictionary_ variable[key ]= val
Example:
1. Program to add a new item in the dictionary
d={'Name': 'Arav', 'Course': 'B.tech', 'roll_no': '18/001'}
d['marks']=99 #new entry
print('d[Name]:',d['Name'])
print('d[course]:',d['Course'])
print('d[roll_no]:',d['roll_no'])
print('d[marks]:',d['marks'])
Output:
d[Name]: Arav
d[course]: B.tech
d[roll_no]: 18/001
d[marks]: 99
138
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
139
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Modifying an Entry:
To modify an entry, just overwrite the existing value as shown in the following
example:
1. program to modify an item in the dictionary
d={'Name': 'Arav', 'Course': 'B.tech', 'roll_no': '18/001'}
d['marks']=99 #new entry
print('d[Name]:',d['Name'])
print('d[course]:',d['Course'])
print('d[roll_no]:',d['roll_no'])
print('d[marks]:',d['marks'])
d[‘Course’]=’BCA’ #Updated entry
print('d[course]:',d['Course'])
Output:
d[Name]: Arav
d[course]: B.tech
d[roll_no]: 18/001
d[marks]: 99
d[course]: BCA
Deleting Items :
You can delete one or more items using the del keyword.
To delete or remove all the items in just one statement, use the clear ()
function.
Finally, to remove an entire dictionary from the memory, we can gain use
the del statement as del Dict_name.
The syntax to use the del statement can be given as,
del dictionary_variable[key]
Example:
1. Program to demonstrate the use of del statement and clear() function
140
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
141
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
142
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
143
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
144
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
145
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Nested Dictionaries :
Dictionary with in another dictionary is called Nested dictionary.
146
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
147
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Example:
students={'cse1':{'c':90,'ds':89,'python':98},
'cse2':{'c':90,'ds':99,'python':98},
'cse3':{'c':99,'ds':99,'python':98}}
for key,value in students.items():
print(key,value)
Output:
cse3 {'python': 98, 'c': 99, 'ds': 99}
cse2 {'python': 98, 'c': 90, 'ds': 99}
cse1 {'python': 98, 'c': 90, 'ds': 89}
Difference between a List and a Dictionary:
First, a list is an ordered set of items. But, a dictionary is a data structure that
is used for matching one item (key) with another (value).
Second, in lists, you can use indexing to access a particular item. But, these
indexes should be a number. In dictionaries, you can use any type (immutable)
of value as an index. For example, when we write Dict['Name'], Name acts as
an index but it is not a number but a string.
Third, lists are used to look up a value whereas a dictionary is used to take
one value and look up another value. For this reason, dictionary is also known
as a lookup table.
148
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
149
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Fourth, the key-value pair may not be displayed in the order in which it was
specified while defining the dictionary. This is because Python uses complex
algorithms (called hashing) to provide fast access to the items stored in the
dictionary. This also makes dictionary preferable to use over a list of tuples.
String Formatting with Dictionaries:
Python also allows you to use string formatting feature with dictionaries. So you can
use %s, %d, %f, etc. to represent string, integer, floating point number, or any other
data.
Example:
Program that uses string formatting feature to print the key-value pairs stored in the
dictionary.
d={"cse":98,"ece":99,"eee":90}
for key,value in d.items():
print("%s branch:%d"%(key,value))
output:
ece branch:99
cse branch:98
eee branch:90
Lab Programs:
5a.Write a program to count the number of characters in the string and store
them in dictionary
n=int(input("Enter the number"))
i=0;
dict1={}
while(i<n):
str1=input("Enter the string")
length=len(str1)
dict1[str1]=length
i=i+1;
print('Entered dictionary elements are')
print(dict1)
150
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
151
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Output
Enter the number2
Enter the stringhari
Enter the stringchennai
Entered dictionary elements are
{'hari': 4, 'chennai': 7}
5b.Write a program to sort keys in a Dictionary
Dict1={'Course':'B.Tech','Rollno':'565','Address':'GDV'}
for key in sorted(Dict1):
print("%s%s"%(key,Dict1[key]))
Output
AddressGDV
CourseB.Tech
Rollno565
5c.Write a Program that prints maximum and minimum value in a dictionary
Dict1={'Course':'B.Tech','Rollno':'565','Address':'GDV'}
print('Minimum value is ',min(Dict1.values()))
print('Maximum value is',max(Dict1.values()))
Output
>>>
Minimum value is 565
Maximum value is GDV
152
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Files
1. Introduction to Files:
When a program is being executed, its data is stored in RAM. Though RAM can
be accessed faster by the CPU,it is also volatile, which means when the
program ends, or the computer shuts down, all the data is lost. If you want to
use the data in future,then you need to store this data on a permanent or non-
volatile storage media such as hard disk, USB drive and DVD e.t.c.,
A file is a collection of data stored on a secondary storage device like hard
disk.
A file is basically used because real-life applications involve large amounts of
data and in such situations the console oriented I/O operations pose two major
problems:
First, it becomes cumbersome and time consuming to handle huge amount of
data through terminals.
Second, when doing I/O using terminal, the entire data is lost when either the
program is terminated or computer is turned off. Therefore, it becomes
necessary to store data on a permanent storage (the disks) and read whenever
necessary, without destroying the data.
2. File Types
Like C and C++,Python also supports two types of files
1. ASCII Text Files
2. Binary Files
2.1 ASCII Text Files
A text file is a stream of characters that can be sequentially processed by a
computer in forward direction. For this reason a text file is usually opened for
only one kind of operation (reading, writing, or appending) at any given time.
Because text files can process characters, they can only read or write data one
character at a time. In Python, a text stream is treated as a special kind of file.
Depending on the requirements of the operating system and on the operation
that has to be performed (read/write operation) on the file, the newline
characters may be converted to or from carriage-return/linefeed combinations.
153
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Besides this, other character conversions may also be done to satisfy the
storage requirements of the operating system. However, these conversions
occur transparently to process a text file. In a text file, each line contains zero
or more characters and ends with one or more characters.
Another important thing is that when a text file is used, there are actually two
representations of data- internal or external. For example, an integer value will
be represented as a number that occupies 2 or 4 bytes of memory internally
but externally the integer value will be represented as a string of characters
representing its decimal or hexadecimal value.
Note: In a text file, each line of data ends with a newline character. Each file ends with
a special character called end-of-file (EOF) Marker.
2.2 Binary Files
A binary file is a file which may contain any type of data, encoded in binary
form for computer storage and processing purposes. It includes files such as
word processing documents, PDFs, images, spreadsheets, videos, zip files and
other executable programs.
Like a text file, a binary file is a collection of bytes. A binary file is also referred
to as a character stream with following two essential differences.
A binary file does not require any special processing of the data and each byte
of data is transferred to or from the disk unprocessed.
Python places no constructs on the file, and it may be read from, or written to,
in any manner the programmer wants.
While text files can be processed sequentially, binary files, on the other
hand, can be either processed sequentially or randomly depending on the
needs of the application.
Note:Binary files store data in the internal representation format.Therefore, an
integer value will be stored in binary form as 2 byte value.The same format is used to
store data in memory as well as in files.Like Text files,Binary files also ends with an
EOF Marker
154
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
155
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
3. File Path:
Files that we use are stored on a storage medium like the hard disk in such a
way that they can be easily retrieved as and when required.
Every file is identified by its path that begins from the root node or the root
folder. In Windows, C:\ (also known as C drive) is the root folder but you can
also have a path that starts from other drives like D:\, E:\, etc. The file path is
also known as pathname.
In order to access a file on a particular disk we have two paths.
1. Absolute Path
2. Relative Path
While an absolute path always contains the root and the complete directory
list to specify the exact location the file.
Example:To access BTech_CS.docx,The absolute path is C:\
Students\Under Graduate\BTech_CS.docx
Relative path needs to be combined with another path in order to access a
file. It starts with respect to the current working directory and therefore lacks
the leading slashes.
Example: Suppose you are working on current directory Under Graduate in order to
access BTech_CS.docx,The Relative path is
Under Graduate\BTech_CS.docx
156
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
157
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
4. File Operations
When we want to read from or write to a file we need to open it first. When we
are done, it needs to be closed, so that resources that are tied with the file are
freed.
Python has many in-built functions and methods to manipulate files.These
Hence, in Python, a file operation takes place in the following order.
1. Open a file
2. Read or write (perform operation)
3. Close the file
4.1 Opening A File
Before reading from or writing to a file, you must first open it using Python‟s
built-in open() function. This function creates a file object, which will be used
to invoke methods associated with it.
The Syntax of open() is:
fileObj = open(file_name [, access_mode])
Where file_name is a string value that specifies name of the file that you want to
access. access_mode indicates the mode in which the file has to be opened, i.e., read,
write, append, etc.
Example:Write a Program to print the details of file object
Note:Access mode is an optional parameter and the default file access mode is
read(r).
158
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
159
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
160
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
161
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
162
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
print(file.read())
Output:
Name of the file : File1.txt
File is closed: False
File is now being closed
File is closed True
Traceback (most recent call last):
File "D:/Python/sample.py", line 7, in <module>
print(file.read())
io.UnsupportedOperation: read
4.3 Writing A File
The write() method is used to write a string to an already opened file. Of
course this string may include numbers, special characters or other symbols.
While writing data to a file, you must remember that the write() method does
not add a newline character ('\n') to the end of the string.
The syntax of write() method is:
fileObj.write(string)
Example:Program that writes a message in the file,data.txt
file=open('data.txt','w')
file.write('hello cse we are learning python programming')
file.close() data.txt
print('file writing successful')
hello cse we are learning python programming
Output:
file writing successful
4.3.1 writeline() method:
The writelines() method is used to write a list of strings.
Example:Program to write to afile using the writelines() method
file=open('data.txt','w')
lines=['hello','cse','hope to enjoy','learning','python programming']
file.writelines(lines) data.txt
163
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
164
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
165
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
166
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
167
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
168
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
169
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
170
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
Note: When you open a file for reading, or writing, the file is searched in the current
directory. If the file exists somewhere else then you need to specify the path of the
file.
4.4.5 Splitting Words:
Python allows you to read line(s) from a file and splits the line (treated as a
string) based on a character. By default, this character is space but you can
even specify any other character to split words in the string.
Example: Program to split the line into series of words and use space to perform the
split operation
with open('data.txt','r') as file:
data.txt
line=file.readline()
hellocsehope to enjoylearningpython programming
words=line.split()
print(words)
Output:
['hellocsehope', 'to', 'enjoylearningpython', 'programming']
4.5 Some Other Useful File Methods:
The following are some of additional methods which will work on files
171
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
172
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
173
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
174
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
For example, the tell() method tells the current position within the file at which
the next read or write operation will occur. It is specified as number of bytes
from the beginning of the file.
When you just open a file for reading, the file pointer is positioned at location
0, which is the beginning of the file.
The syntax for seek() function is
seek(offset[, from])
The offset argument indicates the number of bytes to be moved and the from
argument specifies the reference position from where the bytes are to be
moved.
Example: Program that tells and sets the position of file pointer
File1.txt
Hello All,
Hope you are enjoying learning python
175
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
176
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
The rename() Method: The rename() method takes two arguments, the current
filename and the new filename.
Its syntax is: os.rename(old_file_name, new_file_name)
The remove() Method: This method can be used to delete file(s). The method
takes a filename (name of the file to be deleted) as an argument and deletes
that file.
Its syntax is: os.remove(file_name)
Example: Program to rename file ‘File1.txt’ to ‘student.txt’
5. Types of Arguments
5.1 Command line Arguments:
The Python sys module provides access to any command-line arguments via
the sys.argv. This serves two purposes −
sys.argv is the list of command-line arguments.
len(sys.argv) is the number of command-line arguments.
Here sys.argv[0] is the program ie. script name.
Example1:Write a Python program to demonstrate the usage of Command Line
Arguments
177
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
178
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
sample11.py
#!/usr/bin/python
import sys
print ('Number of arguments:', len(sys.argv), 'arguments.')
print ('Argument List:', str(sys.argv))
Output:
Example2: Write a Python program to copy the content of one file to another
using command line arguments.
sample12.py input.txt
Hello hi
#!/usr/bin/python How are you
import sys
print ('Number of arguments:', len(sys.argv), 'arguments.')
with open(str(sys.argv[1])) as f:
with open((sys.argv[2]), "w") as f1: output.txt
Hello hi
for line in f:
How are you
f1.write(line)
print('File Copied Success')
print (line[::-1])
Output:
ih olleH
179
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
180
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
data.txt
181
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
182
Prepared by: Ramesh Prasad Bhatta FWU CSIT Department, Mahendranagar
out.txt
183