Python Notes
Python Notes
P
Write an algorithm to find the factorial of a number entered by user.
Step 1: Start
AP
Step 2: Declare variables n,factorial and i.
Step 3: Initialize variables
factorial←1
i←1
Step 4: Read value of n
Step 5: Repeat the steps till i=n
5.1: factorial←factorial*i
R
5.2: i←i+1
Step 6: Display factorial
CO
Step 7: Stop
Step 1: Start
U
i←2
Step 4: Read n from user.
Step 5: Repeat the steps till i<(n/2)
5.1 If remainder of n÷i equals 0
flag←0
Go to step 6
5.2 i←i+1
Step 6: If flag=0
.
Step 1: Start
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
Pseudo code:
Pseudo code is a detailed yet readable description of what a computer program or algorithm must do, expressed
in a formally-styled natural language rather than in a programming language. Pseudo code is sometimes used as
a detailed step in the process of developing a program
P
Compute the area of a rectangle:
AP
GET THE length, l, and width, w
COMPUTE area = l*w
DISPLAY area
Compute the perimeter of a rectangle:
READ length, l
READ width, w
R
COMPUTE Perimeter = 2*l + 2*w
DISPLAY Perimeter of a rectangle
CO
Iteration:
Iteration is the act of repeating a process, either to generate an unbounded sequence of outcomes, or with the
aim of approaching a desired goal, target or result. Each repetition of the process is also called an "iteration",
U
and the results of one iteration are used as the starting point for the next iteration.
ST
a = 0
for i from 1 to 3 // loop three times
{
a = a + i // add the current value of i to a
}
print a // the number 6 is printed (0 + 1; 1 + 2; 3 + 3)
.
Recursion
The process in which a function calls itself directly or indirectly is called recursion and the corresponding
function is called as recursive function. Using recursive algorithm, certain problems can be solved quite easily.
Examples of such problems are Towers of Hanoi (TOH), In order/Preorder/Post order Tree Traversals, DFS of
Graph, etc.
int fact(int n)
{
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
In the above example, base case for n < = 1 is defined and larger value of number can be solved by converting
to smaller one till base case is reached.
Disadvantages of Recursion over iteration
Note that both recursive and iterative programs have same problem solving powers, i.e., every recursive
P
program can be written iteratively and vice versa is also true. Recursive program has greater space requirements
than iterative program as all functions will remain in stack until base case is reached. It also has greater time
requirements because of function calls and return overhead.
AP
Advantages of Recursion over iteration
Recursion provides a clean and simple way to write code. Some problems are inherently recursive like tree
traversals, Tower of Hanoi, etc. For such problems it is preferred to write recursive code. We can write such
codes also iteratively with the help of stack data structure. For example refer Inorder Tree Traversal without
Recursion, Iterative Tower of Hanoi.
R
Flow Charts
CO
A Flowchart is a diagram that graphically represents the structure of the system, the flow of steps in a
process, algorithm, or the sequence of steps and decisions for execution a process or solution a problem.
Flow charts are easy-to-understand diagrams that show how the steps of a process fit together. American
engineer Frank Gilbert is widely believed to be the first person to document a process flow, having introduced
U
the concept of a “Process Chart” to the American Society of Mechanical Engineers in 1921.
Flow charts tend to consist of four main symbols, linked with arrows that show the direction of flow:
ST
4. Parallelograms, which show input and output. This can include materials, services or people.
.
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
P
AP
R
CO
U
ST
.
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
Flow Chart Examples:
Sequence to find the sum of two number Area of triangle
P
AP
Flowchart to find the number is odd or Even
R
CO
U
ST
.
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
P
Factorial of the given Number
AP
R
CO
U
ST
.
P
AP
R
CO
U
ST
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
P
AP
Flow chart for finding Prime number
R
CO
U
ST
.
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
P
AP
R
CO
U
ST
.
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
P
AP
R
CO
U
ST
Illustrative problems: find minimum in a list, insert a card in a list of sorted cards, guess an integer number in a
range, Towers of Hanoi.
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
P
AP
R
CO
U
ST
.
To find the minimum from the list the same flowchart but change the sign
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
Insertion Sort
P
AP
R
CO
U
ST
Sorting is ordering a list of objects. We can distinguish two types of sorting. If the number of objects is small
enough to fits into the main memory, sorting is calledinternal sorting. If the number of objects is so large that
some of them reside on external storage during the sort, it is called external sorting. In this chapter we consider
the following internal sorting algorithms
Bucket sort
Bubble sort
.
Insertion sort
Selection sort
Heapsort
Mergesort
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
x = [Link](1, 201)
print(x)
if guess == x:
print("Hit!")
else:
P
print ("Your guess is too high")
OUTPUT
AP
>>> runfile('C:/Users/admin/.anaconda/navigator/[Link]', wdir='C:/Users/admin/.anaconda/navigator')
158
59
Flow Chart
ST
.
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
P
AP
R
CO
U
ST
.
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
Range function in python
the range() function has two sets of parameters, as follows:
range(stop)
stop: Number of integers (whole numbers) to generate, starting from zero. eg. range(3) ==
[0, 1, 2].
P
Note that:
AP
All parameters can be positive or negative.
range() (and Python in general) is 0-index based, meaning list indexes start at 0, not 1. eg.
The syntax to access the first element of a list is mylist[0]. Therefore the last integer
generated by range() is up to, but not including, stop. For example range(0, 5) generates
integers from 0 up to, but not including, 5.
Python's range() Function Examples
R
>>> # One parameter
>>> for i in range(5):
CO
... print(i)
...
0
1
2
U
3
4
>>> # Three parameters
>>> for i in range(4, 10, 2):
ST
... print(i)
...
4
6
8
>>> # Going backwards
>>> for i in range(0, -10, -2):
.
... print(i)
...
0
-2
-4
-6
-8
Tower of the Hanoi
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
P
AP
R
CO
U
ST
.
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
P
AP
R
CO
U
ST
.
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
The Tower of Hanoi puzzle was invented by the French mathematician Edouard Lucas in 1883. He was
inspired by a legend that tells of a Hindu temple where the puzzle was presented to young priests. At the
beginning of time, the priests were given three poles and a stack of 64 gold disks, each disk a little smaller than
the one beneath it. Their assignment was to transfer all 64 disks from one of the three poles to another, with two
important constraints. They could only move one disk at a time, and they could never place a larger disk on top
of a smaller one. The priests worked very efficiently, day and night, moving one disk every second. When they
finished their work, the legend said, the temple would crumble into dust and the world would vanish.
Although the legend is interesting, you need not worry about the world ending any time soon. The number of
moves required to correctly move a tower of 64 disks is 264−1=18,446, 744, 073, 709, 551,
615264−1=18,446,744,073,709,551,615. At a rate of one move per second, that
is 584,942,417,355584,942,417,355 years! Clearly there is more to this puzzle than meets the eye.
Figure 1 shows an example of a configuration of disks in the middle of a move from the first peg to the third.
Notice that, as the rules specify, the disks on each peg are stacked so that smaller disks are always on top of the
larger disks. If you have not tried to solve this puzzle before, you should try it now. You do not need fancy
disks and poles–a pile of books or pieces of paper will work.
P
AP
R
CO
How do we go about solving this problem recursively? How would you go about solving this problem at all?
What is our base case? Let’s think about this problem from the bottom up. Suppose you have a tower of five
disks, originally on peg one. If you already knew how to move a tower of four disks to peg two, you could then
easily move the bottom disk to peg three, and then move the tower of four from peg two to peg three. But what
U
if you do not know how to move a tower of height four? Suppose that you knew how to move a tower of height
three to peg three; then it would be easy to move the fourth disk to peg two and move the three from peg three
on top of it. But what if you do not know how to move a tower of three? How about moving a tower of two
ST
disks to peg two and then moving the third disk to peg three, and then moving the tower of height two on top of
it? But what if you still do not know how to do this? Surely you would agree that moving a single disk to peg
three is easy enough, trivial you might even say. This sounds like a base case in the making.
Here is a high-level outline of how to move a tower from the starting pole, to the goal pole, using an
intermediate pole:
As long as we always obey the rule that the larger disks remain on the bottom of the stack, we can use the three
steps above recursively, treating any larger disks as though they were not even there. The only thing missing
from the outline above is the identification of a base case. The simplest Tower of Hanoi problem is a tower of
one disk. In this case, we need move only a single disk to its final destination. A tower of one disk will be our
base case. In addition, the steps outlined above move us toward the base case by reducing the height of the
tower in steps 1 and 3. Listing 1 shows the Python code to solve the Tower of Hanoi puzzle.
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
moveTower(height-1,fromPole,withPole,toPole)
moveDisk(fromPole,toPole)
moveTower(height-1,withPole,toPole,fromPole)
def moveDisk(fp,tp):
print("moving disk from",fp,"to",tp)
P
moveTower(3,"A","B","C")
AP
OUTPUT
runfile('C:/Users/admin/.anaconda/navigator/[Link]',wdir='C:/Users/admin/.anaconda/navigator')
R
moving disk from A to B
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
Two Marks
A value is one of the basic things ina programs like a letter or a number. The values are
belonging to different types. For example
P
>>> type(‘Hello’)
AP
<type ‘str’>
>>> type(17)
<type ‘float’>
2. Define variables.
R
A variable is a name that refers to a value. They can contain both letters and numbers but
they do not begin with a letter. The underscore ‘_’ can appear in a name.
CO
Example:
>>> n=176
A Boolean expression is an expression that is either true (or) false. The Operator == which
compares two operands and produces True if they are equal otherwise it is false.
>>> 5==5
True
>>> 5==6
.
False
4. Define String
>>> fruit=’banana’
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
Output:
[Link] List.
A List is a sequence of values. The values are characters in a list they can be of any type. The
values in a list are called elements.
P
Examples
AP
[‘a’,’b’,’c’,’d’]-> Character List
>>> n=[17,35]
>>> n[0]=5
U
7. Define Expression
ST
8. Define Tuples
A Tuple is a sequence of values. The values can be of any type, They are indexed by integers.
>>> t=(‘a’,’b’,’c’)
>>> t[1:3]
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
>>(‘a’,’b’)
a=5
b=6
a,b=b,a
print (a,b)
In – Evaluates to true, if it finds a variable in the specified sequence and false otherwise.
P
Not in- Evaluates to true, if it does not finds a variable in the specified sequence and false
otherwise.
AP
[Link] Functions
def print_1():
CO
print (“welcome”)
[Link] Module
[Link] arguments
[Link] arguments
.
[Link] arguments
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
1. Define Operators. What are the different types of Operators in python? Explain in
detail.
Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.
Types of Operator
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
P
Logical Operators
Bitwise Operators
AP
Membership Operators
Identity Operators
operator.
Subtracts right hand operand from left
- Subtraction a – b = -10
hand operand.
* Multiplies values on either side of the
a * b = 200
Multiplication operator
U
These operators compare the values on either sides of them and decide the relation among
them. They are also called Relational operators.
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
P
If the value of left operand is greater
>= than or equal to the value of right (a >= b) is not true.
operand, then condition becomes true.
AP
If the value of left operand is less than
<= or equal to the value of right operand, (a <= b) is true.
then condition becomes true.
Modulus c %= a is equivalent to c = c % a
and assign the result to left operand
AND
**= Performs exponential (power)
Exponent calculation on operators and assign c **= a is equivalent to c = c ** a
AND value to the left operand
//= Floor It performs floor division on operators
c //= a is equivalent to c = c // a
Division and assign value to the left operand
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b =
13; Now in binary format they will be as follows −
a = 0011 1100
b = 0000 1101
-----------------
P
a^b = 0011 0001
AP
~a = 1100 0011
operand.
^ Binary It copies the bit if it is set in one
(a ^ b) = 49 (means 0011 0001)
XOR operand but not both.
~ Binary (~a ) = -61 (means 1100 0011 in 2's
It is unary and has the effect of
Ones complement form due to a signed
'flipping' bits.
U
right operand.
The left operands value is moved right
>> Binary
by the number of bits specified by the a >> = 15 (means 0000 1111)
Right Shift
right operand.
There are following logical operators supported by Python language. Assume variable a holds
10 and variable b holds 20 then
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
Python’s membership operators test for membership in a sequence, such as strings, lists, or
tuples. There are two membership operators as explained below
P
Python Identity Operators
Identity operators compare the memory locations of two objects. There are two Identity
AP
operators explained below:
The following table lists all operators from highest precedence to lowest.
U
Operator Description
** Exponentiation (raise to the power)
ST
Complement, unary plus and minus (method names for the last two
~+-
are +@ and -@)
* / % // Multiply, divide, modulo and floor division
+- Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
^| Bitwise exclusive `OR' and regular `OR'
.
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
A function is a block of organized, reusable code that is used to perform a single, related
action. Functions provide better modularity for application and a high degree of code reusing.
Defining a Function
Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).
Any input parameters or arguments should be placed within these parentheses. You
can also define parameters inside these parentheses.
P
The first statement of a function can be an optional statement - the documentation
string of the function or docstring.
AP
The code block within every function starts with a colon (:) and is indented.
The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as return
None.
Syntax
R
def functionname( parameters ):
"function_docstring"
function_suite
CO
return [expression]
By default, parameters have a positional behavior and you need to inform them in the same
order that they were defined.
U
Example
The following function takes a string as input parameter and prints it on standard screen.
ST
Calling a Function
.
Defining a function only gives it a name, specifies the parameters that are to be included in
the function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it from
another function or directly from the Python prompt. Following is the example to call
printme() function −
#!/usr/bin/python
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
P
All parameters (arguments) in the Python language are passed by reference. It means if you
change what a parameter refers to within a function, the change also reflects back in the
calling function. For example −
mylist = [10,20,30];
CO
changeme( mylist );
print "Values outside the function: ", mylist
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
Function Arguments
U
You can call a function by using the following types of formal arguments:
ST
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
Required arguments
.
Required arguments are the arguments passed to a function in correct positional order. Here,
the number of arguments in the function call should match exactly with the function
definition.
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
print str
return;
printme()
Keyword arguments
Keyword arguments are related to the function calls. When you use keyword arguments in a
P
function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python interpreter
AP
is able to use the keywords provided to match the values with parameters. You can also make
keyword calls to the printme() function in the following ways −
#!/usr/bin/python
return;
Default arguments
A default argument is an argument that assumes a default value if a value is not provided in
ST
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
Variable-length arguments
You may need to process a function for more arguments than you specified while defining
the function. These arguments are called variable-length arguments and are not named in the
function definition, unlike required and default arguments.
An asterisk (*) is placed before the variable name that holds the values of all nonkeyword
P
variable arguments. This tuple remains empty if no additional arguments are specified during
the function call. Following is a simple example −
AP
# Function definition is here
def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print "Output is: "
print arg1
R
for var in vartuple:
print var
return;
CO
Output is:
70
60
ST
50
[Link] Calculator Program
def sum(a,b):
return a+b
def sub(a,b):
.
return a-b
def mul(a,b):
return a*b
def div(a,b):
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
return(a//b)
print ("Subtraction",sub(8,4))
print ("Multiplication",mul(8,4))
print ("Division",div(8,2))
Output:
Addition 11
Subtraction 4
P
Multiplication 32
AP
Division 4
def rotate(l,y=1):
if(len(l)==0):
R
return 1
CO
y=y%len(l)
return l[y:]+l[:y]
print(rotate([1,2,3,4]))
U
print(rotate([2,3,4,1]))
print(rotate([3,4,1,2]))
ST
print(rotate([3,2,1,4]))
Output:
[2, 3, 4, 1]
[3, 4, 1, 2]
.
[4, 1, 2, 3]
[2, 1, 4, 3]
def swap(a,b):
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
a,b=b,a
swap(4,5)
Output:
P
import math
AP
p1 = [4, 0]
p2 = [6, 6]
print(distance)
R
Output:
CO
6.324555320336759
[Link] of n numbers
U
def sum(n):
s=0
ST
for i in range(1,n):
s=s+i
return s
n=int(n)
Output:
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
Sum of n numbers 45
def sumofevenodd(n):
se=0
so=0
for i in range(1,n):
if i%2==0:
se=se+i
P
else:
AP
so=so+i
return se,so
n=int(n)
R
print("Sum of n numbers", sumofevenodd(n))
CO
Output:
def sum(farg,*args):
ST
s=0
for i in args:
s=s+i
sum(1,4,5,6)
Output:
def someFunction(**kwargs):
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
if 'text' in kwargs:
print (kwargs['text'])
someFunction(text='welcome')
Output:
Welcome
9. Keyword arguments
def print_info(name,age=25):
print ("Name:",name)
P
print("Age",age)
AP
print_info(name='Uma',age=35)
print_info(name='Reka')
Output:
Name: Uma
R
Age 35
CO
Name: Reka
Age 25
U
ST .
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
Conditionals:
Boolean values:
P
Boolean values are the two constant objects False and True. They are used to represent truth
values (although other values can also be considered false or true). In numeric contexts (for
AP
example when used as the argument to an arithmetic operator), they behave like the
integers 0 and 1, respectively.
str="Hello World"
CO
print [Link]() #False #check if all char in the string are alphabetic
The if statement
Conditional statements give us this ability to check the conditions. The simplest form is
the if statement, which has the general form:
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
if BOOLEAN EXPRESSION:
STATEMENTS
The colon (:) is significant and required. It separates the header of the compound statement from
the body.
The line after the colon must be indented. It is standard in Python to use four spaces for
indenting.
All lines indented the same amount after the colon will be executed whenever the
P
BOOLEAN_EXPRESSION is true.
AP
Here is an example:
If a>0:
Flow Chart:
R
CO
U
ST
.
The header line of the if statement begins with the keyword if followed by a boolean
expression and ends with a colon (:).
The indented statements that follow are called a block. The first unintended statement marks the
end of the block. Each statement inside the block must have the same indentation.
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
if else statement
when a condition is true the statement under if part is executed and when it is false the statement
under else part is executed
if a>0:
print(“ a is positive”)
else:
P
print(“ a is negative”)
AP
Flow Chart
R
CO
U
ST
if BOOLEAN EXPRESSION:
.
else:
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
Each statement inside the if block of an if else statement is executed in order if the boolean
expression evaluates to True. The entire block of statements is skipped if the boolean expression
evaluates to False, and instead all the statements under the else clause are executed.
else:
pass
Chained Conditionals
P
Sometimes there are more than two possibilities and we need more than two branches. One way
AP
to express a computation like that is a chained conditional:
if x < y:
STATEMENTS_A
elif x > y:
R
STATEMENTS_B
CO
else:
STATEMENTS_C
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
P
AP
R
elif is an abbreviation of else if. Again, exactly one branch will be executed. There is no limit of
the number of elif statements but only a single (and optional) final else statement is allowed and
it must be the last branch in the statement:
CO
if choice == '1':
print("Monday.")
print(“Tuesday")
ST
print("Wednesday")
else:
print("Invalid choice.")
.
Another Example
def letterGrade(score):
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
letter = 'A'
letter = 'B'
letter = 'C'
P
else: # grade must D or F
AP
if score >= 60:
letter = 'D'
else:
letter = 'F'
R
return letter
CO
Program1:
if x1>x2:
ST
print("x1 is big")
else:
print("x2 is big")
Program2:
.
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
largest = num1
largest = num2
else:
largest = num3
P
print("The largest number between",num1,",",num2,"and",num3,"is",largest)
AP
Program 3: Roots of a quadratic equation
import math
a=int(input("Enter a"))
b=int(input("enter b"))
R
c=int(input("enter c"))
CO
d = b**2-4*a*c
d=int(d)
if d < 0:
U
elif d == 0:
ST
x = (-b+[Link](b**2-4*a*c))//2*a
else:
x1 = (-b+[Link](b**2-4*a*c))//2*a
.
x2 = (-[Link](b**2-4*a*c))//2*a
print ("This equation has two solutions: ", x1, " and", x2)
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
x=int(input("enter a number"))
if x%2==0:
else:
print("it is Odd")
x=int(input("enter a number"))
P
if x>0:
AP
print("it is positive")
else:
print("it is negative") R
Each condition is checked in order. If the first is false, the next is checked, and so on. If one of
CO
them is true, the corresponding branch executes, and the statement ends. Even if more than one
condition is true, only the first true branch executes.
Nested Conditionals
Flowchart
U
ST
.
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
P
if x < y:
AP
R
STATEMENTS_A
CO
else:
if x > y:
STATEMENTS_B
U
else:
STATEMENTS_C
ST
The outer conditional contains two branches. The second branch contains another if statement,
which has two, branches of its own. Those two branches could contain conditional statements as
well.
Logical operators often provide a way to simplify nested conditional statements. For example,
we can rewrite the following code using a single conditional:
.
if x < 10:
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
Iteration
Computers are often used to automate repetitive tasks. Repeating identical or similar tasks
without making errors is something that computers do well and people do poorly.
While loop
While statement
The general syntax for the while statement looks like this:
While BOOLEAN_EXPRESSION:
P
STATEMENTS
Like the branching statements and the for loop, the while statement is a compound statement
AP
consisting of a header and a body. A while loop executes an unknown number of times, as long
at the BOOLEAN EXPRESSION is true.
n=int(input("enter n"))
U
s=0
ST
while(n>0):
r=n%10
s=s+r
n=n/10
.
print("sum of digits",int(s))
OUTPUT
enter n 122
sum of digits 5
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
n=int(input("enter n"))
a=n
a=int(a)
s=0
while(n>0):
r=n%10
P
s=s+r*r*r
AP
n=n//10
print(s)
if(s==a):
n=int(input("enter n"))
U
a=n
a=int(a)
ST
s=0
while(n>0):
r=n%10
s=s*10+r
.
n=n//10
print(s)
if(s==a):
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
print("It is a Palindrome")
else:
for loop
The for loop processes each item in a sequence, so it is used with Python’s sequence data types -
strings, lists, and tuples.
P
Each item in turn is (re-)assigned to the loop variable, and the body of the loop is executed.
AP
for LOOP_VARIABLE in SEQUENCE:
STATEMENTS
i is now 1
i is now 2
i is now 3
U
i is now 4
ST
>>>
Example 2:
Using the tab character ('\t') makes the output align nicely.
0 1
1 2
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
2 4
3 8
4 16
5 32
6 64
7 128
8 256
P
9 512
AP
10 1024
11 2048
12 4096
Equals = ==
Not equal ≠ !=
ST
def convert(n):
if n > 1:
convert(n//2)
.
dec=int(input("enter n"))
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
convert(dec)
OUPUT
enter n 25
11001
P
print(bin(dec),"in binary.")
AP
print(oct(dec),"in octal.")
print(hex(dec),"in hexadecimal.")
OUTPUT
enter n 25
R
The decimal value of 25 is:
CO
0b11001 in binary.
0o31 in octal.
0x19 in hexadecimal.
U
n= int(input("enter a number"))
ST
f=1
for i in range(1,n+1):
f = f*i
OUTPUT
enter a number 7
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
if num > 1:
P
for i in range(2,num):
AP
if (num % i) == 0:
break
else:
print(num)
R
OUTPUT
CO
enter start value 0
3
ST
11
13
.
17
19
23
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
a = int(input("enter a"))
b=int(input("enter b"))
temp = a
a=b
b = temp
P
print("\nafter swapping\na=", a, " b=", b)
AP
Program for swapping two numbers without using temporary variable
a = int(input("enter a"))
b=int(input("enter b"))
if ch == '+':
res = n1+n2
elif ch == '-':
res = n1-n2
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
elif ch == '*':
res = n1 * n2
elif ch == '/':
res = n1 / n2
else:
P
print("enter a valid operator")
AP
Fruitful function
Fruitful function is a special function in which function is defined in the return statement,
It is a function with return type as [Link] first example is area, which returns the area of
a circle with the given radius:
def cal(r1):
R
return 3.14*r1*r1
CO
r=int(input("enter r"))
print("ans=",cal(r))
We have seen the return statement before, but in a fruitful function the return statement includes
U
a return value. This statement means: "Return immediately from this function and use the
following expression as a return value." The expression provided can be arbitrarily complicated,
so we could have written this function more concisely:
ST
Sometimes it is useful to have multiple return statements, one in each branch of a conditional:
def absoluteValue(x):
if x<0:
return -x
else:
.
return x
Since these return statements are in an alternative conditional, only one will be executed. As
soon as one is executed, the function terminates without executing any subsequent statements.
Code that appears after a return statement, or any other place the flow of execution can never
reach, is called dead code.
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
To deal with increasingly complex programs, you might want to try a process called
incremental development. The goal of incremental development is to avoid long
debugging sessions by adding and testing only a small amount of code at a time.
As an example, suppose you want to find the distance between two points, given by
the coordinates (x1, y1) and (x2, y2). By the Pythagorean theorem, the distance is:
distance =
√ (x2 − x1)2 + (y2 − y1)2
P
def distance(x1, y1, x2, y2):
dx=x2-x1
AP
dy=y2-y1
return ([Link](dx**2)+(dy**2))
x1=int(input("enter x1"))
y1=int(input("enter y1"))
x2=int(input("enter x2"))
R
y2=int(input("enetr y2"))
print(distance(x1,y1,x2,y2))
CO
def recur_fibo(n):
if n <= 1:
U
return n
ST
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
if nterms <= 0:
.
else:
print("Fibonacci sequence:")
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
for i in range(nterms):
print(recur_fibo(i))
Function composition is a way of combining functions such that the result of each function is
passed as the argument of the next function. For example, the composition of two
functions fand g is denoted f(g(x)). x is the argument of g, the result of g is passed as the
argument of fand the result of the composition is the result of f.
P
Let’s define compose2, a function that takes two functions as arguments (f and g) and returns a
function representing their composition:
AP
def compose2(f, g):
Example:
R
>>> def double(x):
CO
... return x * 2
...
... return x + 1
...
ST
>>> inc_and_double(10)
Syntax
.
pass
Example
#!/usr/bin/python3
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
if letter == 'h':
pass
P
Output
When the above code is executed, it produces the following result −
AP
Current Letter : P
Current Letter : y
Current Letter : t
R
This is pass block
Current Letter : h
CO
Current Letter : o
Current Letter : n
Good bye!
U
Local Variables
Define the variables inside the function definition, they are local to this function by default. This
means that anything will do to such a variable in the body of the function will have no effect on
other variables outside of the function, even if they have the same name. This means that the
.
function body is the scope of such a variable, i.e. the enclosing context where this name with its
values is associated.
def f():
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
print(s)
f()
Output:
P
The variable s is defined as the string "I love Paris in the summer!", before calling the function
AP
f(). The body of f() consists solely of the "print(s)" statement. As there is no local variable s, i.e.
no assignment to s, the value from the global variable s will be used. So the output will be the
string "I love Paris in the summer!". what will happen, if we change the value of s inside of the
function f()?
R
def f():
CO
print(s)
f()
ST
print(s)
Output:
I love London!
.
I love Paris!
Even though the name of both global and local variables are same. The value of the local
variables does not affect the global variables. If we are directly calling the global variable,
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
without assigning any values to the variable, if both local and global variables are same. It
produces an Unbound Local Error.
For Example,
def f():
print(s)
P
print(s)
AP
s = "I love Paris!"
f()
Unbound Local Error: local variable's' referenced before assignment. Because Local variable s
R
referenced before assignment.
CO
We want use global variable in python. We should give keyword global in python
U
def f():
global s
ST
print(s)
s = "Only in spring, but London is great as well!"
print(s)
.
Output:
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
Recursive Functions:
A recursive function is a function that calls itself. To prevent a function from repeating itself
indefinitely, it must contain at least one selection statement. This statement examines a condition
P
called a base case to determine whether to stop or to continue with another recursive step.
1. Program for finding the factorial of a given no
AP
def fact(n):
if n==0:
return 1
else:
return n*fact(n-1)
R
CO
print("The factorial of a given no is",fact(5))
Output:
The factorial of a given no is:120
U
def fib(n):
if n<3:
return 1
else:
return fib(n-1)+fib(n-2)
.
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
P
Len is a inbuilt function. It returns number of characters in a string.
len(fruit)
AP
Out[4]: 6
String Slices:
A segment of a string is called string slices.
Fruit=’banana’
Fruit[1:4]
R
It returns the output as ‘ana’. It includes the first character and excludes the last character in a
CO
string.
Fruit[:3]
It includes from the first character. It produces the output as ‘ban’.
Fruit[3:]
U
If first index is greater than or equal to the second index. Then it returns empty string as output’
‘.
Fruit[:]
It returns the entire string. Out put is ‘banana’.
Fruit[-1]
.
String Immutable
We cant change the value of the strings.
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
fruit[0]='w'
Traceback (most recent call last):
File "<ipython-input-10-839a456c8838>", line 1, in <module>
fruit[0]='w'
TypeError: 'str' object does not support item assignment
Strings are immutable.
String Methods
P
Built-in String Methods
A method is similar to a function. It takes an argument and returns the values. A method call is called invocation.
AP
Python includes the following built-in methods to manipulate strings −
2 center(width, fillchar)
Returns a space-padded string with the original string centered to a total of width columns.
Counts how many times str occurs in string or in a substring of string if starting index beg
and ending index end are given.
ST
4 decode(encoding='UTF-8',errors='strict')
Decodes the string using the codec registered for encoding. encoding defaults to the default
string encoding.
5 encode(encoding='UTF-8',errors='strict')
.
Returns encoded string version of string; on error, default is to raise a ValueError unless
errors is given with 'ignore' or 'replace'.
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
7 expandtabs(tabsize=8)
Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not
provided.
P
Determine if str occurs in string or in a substring of string if starting index beg and ending
index end are given returns index if found and -1 otherwise.
AP
9 index(str, beg=0, end=len(string))
Returns true if string has at least 1 character and all characters are alphanumeric and false
CO
otherwise.
11 isalpha()
Returns true if string has at least 1 character and all characters are alphabetic and false
U
otherwise.
ST
12 isdigit()
13 islower()
Returns true if string has at least 1 cased character and all cased characters are in lowercase
.
14 isnumeric()
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
Returns true if a unicode string contains only numeric characters and false otherwise.
15 isspace()
Returns true if string contains only whitespace characters and false otherwise.
16 istitle()
P
17 isupper()
Returns true if string has at least one cased character and all cased characters are in
AP
uppercase and false otherwise.
18 join(seq)
Merges (concatenates) the string representations of elements in sequence seq into a string,
with separator string.
R
19 len(string)
Returns the length of the string
CO
20 ljust(width[, fillchar])
Returns a space-padded string with the original string left-justified to a total of width
U
columns.
21 lower()
ST
22 lstrip()
23 maketrans()
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
24 max(str)
25 min(str)
Replaces all occurrences of old in string with new or at most max occurrences if max given.
P
27 rfind(str, beg=0,end=len(string))
AP
Same as find(), but search backwards in string.
29 rjust(width,[, fillchar])
CO
Returns a space-padded string with the original string right-justified to a total of width
columns.
30 rstrip()
U
31 split(str="", num=[Link](str))
Splits string according to delimiter str (space if not provided) and returns list of substrings;
split into at most num substrings if given.
32 splitlines( num=[Link]('\n'))
.
Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs
removed.
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
33 startswith(str, beg=0,end=len(string))
Determines if string or a substring of string (if starting index beg and ending index end are
given) starts with substring str; returns true if so and false otherwise.
34 strip([chars])
35 swapcase()
P
Inverts case for all letters in string.
AP
36 title()
Returns "titlecased" version of string, that is, all words begin with uppercase and the rest
are lowercase. R
37 translate(table, deletechars="")
Translates string according to translation table str(256 chars), removing those in the del
CO
string.
38 upper()
39 zfill (width)
ST
Returns original string leftpadded with zeros to a total of width characters; intended for
numbers, zfill() retains any sign given (less one zero).
40 isdecimal()
Returns true if a unicode string contains only decimal characters and false otherwise.
.
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
This module contains a number of functions to process standard Python strings. In recent
versions, most functions are available as string methods as well (more on this below).
# File: [Link]
import string
text = "Monty Python's Flying Circus"
print "upper", "=>", [Link](text)
P
print "lower", "=>", [Link](text)
print "split", "=>", [Link](text)
AP
print "join", "=>", [Link]([Link](text), "+")
print "replace", "=>", [Link](text, "Python", "Java")
print "find", "=>", [Link](text, "Python"), [Link](text, "Java")
print "count", "=>", [Link](text, "n")
R
upper => MONTY PYTHON'S FLYING CIRCUS
CO
lower => monty python's flying circus
split => ['Monty', "Python's", 'Flying', 'Circus']
join => Monty+Python's+Flying+Circus
replace => Monty Java's Flying Circus
U
find => 6 -1
count => 3
ST
# File: [Link]
text = "Monty Python's Flying Circus"
print "upper", "=>", [Link]()
print "lower", "=>", [Link]()
.
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
P
count => 3
In addition to the string manipulation stuff, the string module also contains a number of
AP
functions which convert strings to other types:
# File: [Link]
import string
R
CO
print int("4711"),
print [Link]("4711"),
print [Link]("11147", 8), # octal
print [Link]("1267", 16), # hexadecimal
U
print float("4711"),
.
print [Link]("1"),
print [Link]("1.23e5")
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
P
revword('string')
Output:
AP
g
n
i
r
t
R
s
CO
def find(word,letter):
U
index=0
while index<len(word):
ST
if word[index]==letter:
return index
index=index+1
return -1
print("the letter present", find('malayalm','l'))
.
Output:
The letter present 2
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
def find(word,ch):
count=0
for letter in word:
if letter==ch:
count=count+1
return count
print("The total count for the given letter", find('malayalm','l'))
P
Output:
The total count for the given letter 2
AP
3. String Palindrome
def palin(word):
y=word[::-1]
if word==y:
print("Palindrome")
R
else:
CO
print("Not Palindrome")
palin('good')
Output:
Not Palindrome.
U
while y:
x,y=y,x%y
return x
print("GCD of two numbers", ComputeGCD(24,12))
Output:
.
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
print(exp)
expo(5,2)
Output
25
P
AP
R
CO
U
ST
.
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP UNIT – 4
UNIT IV LISTS, TUPLES, DICTIONARIES 9
Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list
parameters; Tuples: tuple assignment, tuple as return value; Dictionaries: operations and
methods; advanced list processing - list comprehension; Illustrative programs: selection sort,
insertion sort, merge sort, histogram.
A list is a sequence of values. In a string, the values are characters but in a list, list values
can be any type.
Elements or Items:
The values in a list are called elements or items. list must be enclosed in square brackets
([and]).
Examples:
P
>>>[10,20,30]
>>>[‘hi’,’hello’,’welcome’]
Nested List:
AP
A list within another list is called nested list.
Example:
[‘good’,10,[100,99]]
Empty List:
A list that contains no elements is called empty list. It can be created with empty
brackets, [].
R
Assigning List Values to Variables:
Example:
>>>numbers=[40,121]
CO
>>>characters=[‘x’,’y’]
>>>print(numbers,characters)
Output:
[40,12][‘x’,’y’]
4.1.1 LIST OPERATIONS:
U
>>>c
Output: [1,2,3,4,5,6]
Example 2:
The * operator repeats a list given number of times:
>>>[0]*4
Output:
[0,0,0,0]
.
>>>[1,2,3]*3
Output:
[1,2,3,1,2,3,1,2,3]
The first example repeats [0] four [Link] second example repeats [1,2,3] three
times.
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
4.1.2 LIST SLICES:
List slicing is a computationally fast way to methodically access parts of given data.
Syntax:
Listname[start:end:step]where :end represents the first value that is not in the
selected slice. The differencebetween end and start is the numbe of elements selected (if step is
1, the default).The start and end may be a negative number. For negative numbers, the count
starts from the end of the array instead of the beginning.
Example:
>>>t=[‘a’,’b’,’c’,’d’,’e’,’f’]
Lists are mutable, so it is useful to make a copy before performing operations that
modify this. A slice operator on the left side of an assignment can update multiple
elements.
Example:
>>>t[1:3]=[‘x’,’y’]
>>>t
P
Output:
[‘a’,’x’,’y’,’d’,’e’,’f’]
AP
4.1.3 LIST METHODS:
Python provides methods that operate on lists.
Example:
1. append adds a new element to the end of a list.
>>>t=[‘a’,’b’,’c’,’d’]
>>>[Link](‘e’)
>>>t
R
Output:
[‘a’,’b’,’c’,’d’,’e’]
CO
2. extend takes a list as an argument and appends all the elements.
>>>t1=[‘a’,’b’]
>>>t2=[‘c’,’d’]
>>>[Link](t2)
>>>t1
U
Output:
[‘a’,’b’,’c’,’d’]
t2 will be unmodified.
4.1.4 LIST LOOP:
ST
[1,2]
[4,5]
Example 2:
>>>for i in range(len(numbers)):
Numbers[i]=numbers[i]*2
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
Above example is used for updating values in numbers [Link] loop traverses
the list and updates each element. Len returns number of elements in the list. Range returns a list
of indices from 0 to n-1, where n is the length of the [Link] time through the loop i gets the
index of next element. A for loop over an empty list never runs the body:
Example:
for x in []:
print(‘This won’t work’)
A list inside another list counts as a single element. The length of the below list is four:
[‘spam’,1,[‘x’,’y’],[1,2,3]]
Example 3:
colors=[“red”,”green”,”blue”,”purple”]
for i in range(len(colors)):
print(colors[i])
Output:
red
green
P
blue
purple
4.1.5 MUTABILITY:
AP
Lists are mutable. Mutable means, we can change the content without changing the
identity. Mutability is the ability for certain types of data to be changed without entirely
recreating [Link] mutable data types can allow programs to operate quickly and efficiently.
Figure 4.1 shows the state diagram for cheeses, numbers and empty:
Lists are represented by boxes with the word “list” outside and the elements of the list
inside. cheeses refers to a list with three elements indexed 0, 1 and 2.
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
numbers contains two elements; the diagram shows that the value of the second element
has been reassigned from 123 to 5. empty refers to a list with no elements.
The in operator also works on lists.
>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> 'Edam' in cheeses
True
>>> 'Brie' in cheeses
False
4.1.6 ALIASING
If a refers to an object and we assign b = a, then both variables refer to the same object:
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
P
The state diagram looks like Figure 4.2.
AP
Figure 4.2 State Diagram
The association of a variable with an object is called a reference. In this example, there
are two references to the same [Link] object with more than one reference has more than one
R
name, so we say that the object is [Link] the aliased object is mutable, changes made with one
alias affect the other:
4.1.7 CLONING LISTS Copy list v Clone list
CO
veggies=["potatoes","carrots","pepper","parsnips","swedes","onion","minehead"]
veggies[1]="beetroot"
# Copying a list gives it another name
daniel=veggies
# Copying a complete slice CLONES a list
U
david=veggies[:]
daniel[6]="emu"
# Daniel is a SECOND NAME for veggies so that changing Daniel also changes veggies.
ST
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
Example:
def delete_head(t):
del t[0]
Here’s how it is used:
>>> letters = ['a', 'b', 'c']
>>> delete_head(letters)
>>> letters
Output:
['b', 'c']
The parameter t and the variable letters are aliases for the same object. The stack diagram
looks like Figure [Link] the list is shared by two frames, I drew it between them. It is
important to distinguish between operations that modify lists and operations that create new lists.
For example, the append method modifies a list, but the + operator creates a new list.
Example 1:
>>> t1 = [1, 2]
>>> t2 = [Link](3)
P
>>> t1
Output:
[1, 2, 3]
AP
Example 2:
>>> t2
Output:
None
R
CO
4.2. TUPLES
U
<class 'tuple'>
A value in parentheses is not a tuple:
>>> t2 = ('a')
>>> type(t2)
Output:
<class 'str'>
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
Another way to create a tuple is the built-in function tuple. With no argument, it creates
an empty tuple.
Example:
>>> t = tuple()
>>> t
Output: ()
If the argument is a sequence (string, list or tuple), the result is a tuple with the elements
of the sequence:
Example:
>>> t = tuple('lupins')
>>> t
Output: ('l', 'u', 'p', 'i', 'n', 's')
Because tuple is the name of a built-in function, we should avoid using it as a variable
name. Most list operators also work on tuples. The bracket operator indexes an element:
Example:
>>> t = ('a', 'b', 'c', 'd', 'e')
P
>>> t[0]
Output: 'a' And the slice operator selects a range of elements.
Example:
AP
>>> t[1:3] Output:('b', 'c')But if we try to modify one of the elements of the
tuple, we get an error:
>>> t[0] = 'A'
TypeError: object doesn't support item assignmentBecause tuples are immutable, we
can’t modify the elements. But we can replace one
tuple with another: Example:
R
>>> t = ('A',) + t[1:]
>>> t
Output:
CO
('A', 'b', 'c', 'd', 'e')This statement makes a new tuple and then makes t refer to it.
The relational operators work with tuples and other sequences; Python starts by
comparing the first element from each sequence. If they are equal, it goes on to the next
elements, and so on, until it finds elements that differ. Subsequent elements are not considered
(even if they are really big).
U
Example 1:
>>> (0, 1, 2) < (0, 3, 4)
Output:
True
ST
Example 2:
>>> (0, 1, 2000000) < (0, 3, 4)
Output:
True
4.2.1 TUPLE ASSIGNMENT
It is often useful to swap the values of two variables. With conventional assignments, we
have to use a temporary variable. For example, to swap a and b:
.
Example:
>>> temp = a
>>> a = b
>>> b = temp
This solution is cumbersome; tuple assignment is more elegant:
>>> a, b = b, a
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
The left side is a tuple of variables; the right side is a tuple of expressions. Each value is
assigned to its respective variable. All the expressions on the right side are evaluated before any
of the [Link] number of variables on the left and the number of values on the right
have to be the same:
>>> a, b = 1, 2, 3
ValueError: too many values to unpack
More generally, the right side can be any kind of sequence (string, list or tuple). For
example, to split an email address into a user name and a domain, we could write:
>>> addr = 'monty@[Link]'
>>> uname, domain = [Link]('@')
The return value from split is a list with two elements; the first element is assigned to
uname, the second to domain.
>>> uname
'monty'
>>> domain
'[Link]'
P
4.2.2 TUPLE AS RETURN VALUES
A function can only return one value, but if the value is a tuple, the effect is the same as
returning multiple values. For example, if we want to divide two integers and compute the
AP
quotient and remainder, it is inefficient to compute x/y and then x%y. It is better to compute
them both at the same time. The built-in function divmod takes two arguments and returns a
tuple of two values, the quotient and remainder. We can store the result as a tuple:
Example:
>>> t = divmod(7, 3)
>>> t
Ouput:
R
(2, 1)
Or use tuple assignment to store the elements separately:
CO
Example:
>>> quot, rem = divmod(7, 3)
>>> quot
Output:
2
U
Example:
>>> rem
Output:
1
ST
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
Output:
dict_items([('c', 2), ('a', 0), ('b', 1)])
The result is a dict_items object, which is an iterator that iterates the key-value pairs. We
can use it in a for loop like this:
Example:
>>> for key, value in [Link]():
... print(key, value)
Output:
c2
a0
b1
As we should expect from a dictionary, the items are in no particular order.
Going in the other direction, we can use a list of tuples to initialize a new dictionary:
Example:
>>> t = [('a', 0), ('c', 2), ('b', 1)]
>>> d = dict(t)
P
>>> d
Output:
{'a': 0, 'c': 2, 'b': 1}
AP
Combining dict with zip yields a concise way to create a dictionary:
Example:
>>> d = dict(zip('abc', range(3)))
>>> d
Output:
{'a': 0, 'c': 2, 'b': 1}
R
The dictionary method update also takes a list of tuples and adds them, as key-value
pairs, to an existing dictionary. It is common to use tuples as keys in dictionaries (primarily
because we can’t use lists). For example, a telephone directory might map from last-name, first-
CO
name pairs to telephone numbers. Assuming that we have defined last, first and number, we
could write: directory [last, first] = number
The expression in brackets is a tuple. We could use tuple assignment to traverse this
dictionary. For last, first in directory:
print(first, last, directory[last,first])
U
This loop traverses the keys in directory, which are tuples. It assigns the elements of each
tuple to last and first, then prints the name and corresponding telephone number.
There are two ways to represent tuples in a state diagram. The more detailed version
ST
shows the indices and elements just as they appear in a list. For example, the tuple('Cleese',
'John') would appear as in Figure 4.4. But in a larger diagram we might want to leave out the
details. For example, a diagram of the telephone directory might appear as in Figure 4.5.
Here the tuples are shown using Python syntax as a graphical shorthand. The telephone
number in the diagram is the complaints line for the BBC, so please don’t call it.
.
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
P
def capitalize_all(t):
res = []
AP
for s in t:
[Link]([Link]())
return res
We can write this more concisely using a list comprehension:
def capitalize_all(t):
return [[Link]() for s in t]
R
The bracket operators indicate that we are constructing a new list. The expression inside
the brackets specifies the elements of the list, and the ‘for’ clause indicates what sequence we are
[Link] syntax of a list comprehension is a little awkward because the loop variable, s in
CO
this example, appears in the expression before we get to the definition.
List comprehensions can also be used for filtering. For example, this function selects only
the elements of t that are upper case, and returns a new list:
def only_upper(t):
res = []
for s in t:
U
if [Link]():
[Link](s)
return res
ST
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
the second position of the list. We continue repeating this process until the list gets sorted.
ALGORITHM:
1. Start from the first element in the list and search for the smallest element in the list.
2. Swap the first element with the smallest element of the list.
3. Take a sub list (excluding the first element of the list as it is at its place) and
search for the smallest number in the sub list (second smallest number of the entire list)
and swap it with the first element of the list (second element of the entire list).
4. Repeat the steps 2 and 3 with new subsets until the list gets sorted.
PROGRAM:
a = [16, 19, 11, 15, 10, 12, 14]
i=0
while i<len(a):
#smallest element in the sublist
smallest = min(a[i:])
#index of smallest element
index_of_smallest = [Link](smallest)
P
#swapping
a[i],a[index_of_smallest] = a[index_of_smallest],a[i]
i=i+1
AP
print (a)
Output
>>>
[10, 11, 12, 14, 15, 16, 19]
4.5.2 INSERTION SORT
Insertion sort is similar to arranging the documents of a bunch of students in order of
R
their ascending roll number. Starting from the second element, we compare it with the first
element and swap it if it is not in order. Similarly, we take the third element in the next iteration
and place it at the right place in the sub list of the first and second elements (as the sub list
CO
containing the first and second elements is already sorted). We repeat this step with the fourth
element of the list in the next iteration and place it at the right position in the sub list containing
the first, second and the third elements. We repeat this process until our list gets sorted.
ALGORITHM:
U
1. Compare the current element in the iteration (say A) with the previous adjacent element
to it. If it is in order then continue the iteration else, go to step 2.
2. Swap the two elements (the current element in the iteration (A) and the previous adjacent
element to it).
ST
3. Compare A with its new previous adjacent element. If they are not in order, then proceed
to step 4.
4. Swap if they are not in order and repeat steps 3 and 4.
5. Continue the iteration.
PROGRAM:
a = [16, 19, 11, 15, 10, 12, 14]
#iterating over a
.
for i in a:
j = [Link](i)
#i is not the first element
while j>0:
#not in order
if a[j-1] > a[j]:
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
#swap
a[j-1],a[j] = a[j],a[j-1]
else:
#in order
break
j = j-1
print (a)
Output
>>>
[10, 11, 12, 14, 15, 16, 19]
4.5.3 MERGE SORT
Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls
itself for the two halves and then merges the two sorted halves. The merge() function is used for
merging two halves. The merge(arr, l, m, r) is key process that assumes that arr[l..m] and
arr[m+1..r] are sorted and merges the two sorted sub-arrays into one. See following C
implementation for details.
P
The following diagram shows the complete merge sort process for an example array {38,
27, 43, 3, 9, 82, 10}. If we take a closer look at the diagram, we can see that the array is
recursively divided in two halves till the size becomes 1. Once the size becomes 1, the merge
AP
processes comes into action and starts merging arrays back till the complete array is merged.
R
CO
U
ST
ALGORITHM:
MergeSort(arr[], l, r)
.
If r > l
1. Find the middle point to divide the array into two halves:
middle m = (l+r)/2
2. Call mergeSort for first half:
Call mergeSort(arr, l, m)
3. Call mergeSort for second half:
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
Call mergeSort(arr, m+1, r)
4. Merge the two halves sorted in step 2 and 3:
Call merge(arr, l, m, r)
PROGRAM:
def mergeSort(alist):
print("Splitting ",alist)
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf):
P
if lefthalf[i] < righthalf[j]:
alist[k]=lefthalf[i]
i=i+1
AP
else:
alist[k]=righthalf[j]
j=j+1
k=k+1
while i < len(lefthalf):
alist[k]=lefthalf[i]
i=i+1
R
k=k+1
while j < len(righthalf):
CO
alist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging ",alist)
n = input("Enter the size of the list: ")
U
n=int(n);
alist = []
for i in range(n):
[Link](input("Enter %dth element: "%i))
ST
mergeSort(alist)
print(alist)
Input:
a = [16, 19, 11, 15, 10, 12, 14]
Output:
>>>
[10, 11, 12, 14, 15, 16, 19]
.
4.5.5 HISTOGRAM
A histogram is a visual representation of the Distribution of a Quantitative variable.
Appearance is similar to a vertical bar graph, but used mainly for continuous
distribution
It approximates the distribution of variable being studied
A visual representation that gives a discretized display of value counts.
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
Example:
P
def histogram(s):
d = dict()
for c in s:
AP
if c not in d:
d[c] = 1
else:
d[c] += 1
return d
R
The name of the function is histogram, which is a statistical term for a collection of
counters (or frequencies).
The first line of the function creates an empty dictionary. The for loop traverses the
CO
[Link] time through the loop, if the character c is not in the dictionary, we create a new item
with key c and the initial value 1 (since we have seen this letter once). If c is already in the
dictionary we increment d[c]. Here’s how it works:
Example:
>>> h = histogram('brontosaurus')
U
>>> h
Output:
{'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 2, 't': 1}
The histogram indicates that the letters 'a' and 'b' appear once; 'o' appears twice, and so
ST
on. Dictionaries have a method called get that takes a key and a default value. If the key appears
in the dictionary, get returns the corresponding value; otherwise it returns the default value. For
example:
>>> h = histogram('a')
>>> h
{'a': 1}
>>> [Link]('a', 0)
.
1
>>> [Link]('b', 0)
0
As an exercise, use get to write histogram more concisely. We should be able to eliminate
the if statement.
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
If we use a dictionary in a for statement, it traverses the keys of the dictionary. For
example, print_hist prints each key and the corresponding value:
def print_hist(h):
for c in h:
print(c, h[c])
Here’s what the output looks like:
>>> h = histogram('parrot')
>>> print_hist(h)
a1
p1
r2
t1
o1
Again, the keys are in no particular order. To traverse the keys in sorted order, we can use
the built-in function sorted:
>>> for key in sorted(h):
P
... print(key, h[key])
a1
o1
AP
p1
r2
t1
Write a function named choose_from_hist that takes a histogram as defined in Histogram
given above and returns a random value from the histogram, chosen with probability in
proportion to frequency. For example, for this histogram:
R
>>> t = ['a', 'a', 'b']
>>> hist = histogram(t)
>>> hist
CO
{'a': 2, 'b': 1}
The function should return 'a' with probability 2/3 and 'b' with probability 1/3.
TWO MARKS
1. What are elements in a list? Give example.
The values in a list are called elements or items.
U
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
Mutability is the ability for certain types of data to be changed without entirely
recreating it. Using mutable data types can allow programs to operate quickly and
efficiently.
6. List any three mutable data types. Give example for mutability.
Example for mutable data types are:
List, Set and Dictionary
Example 1:
>>>numbers=[42,123]
>>>numbers[1]=5
>>>numbers
Output: [42,5]
7. What is aliasing? Give example.
An object with more than one reference has more than one name, so we say that
the object is aliased.
If the aliased object is mutable, changes made with one alias affect the other.
Example:
P
If a refers to an object and we assign b = a, then both variables refer to the same object:
>>> a = [1, 2, 3]
>>> b = a
AP
>>> b is a True
8. What is the difference between copying and cloning lists?
Copying a list gives it another name but copying a complete slice clones a list.
9. Give example for copying and cloning lists.
Example:
veggies=["potatoes","carrots","pepper","parsnips","swedes","onion","min
ehead"]
R
veggies[1]="beetroot"
Copying a list
CO
daniel=veggies
CLONES a list
david=veggies[:]
daniel[6]="emu"
10. Define Dictionaries. Give example.
U
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
UNIT V FILES, MODULES, PACKAGES 9
Files and exception: text files, reading and writing files, format operator; command line
arguments, errors and exceptions, handling exceptions, modules, packages; Illustrative programs:
word count copy file.
PERSISTENCE
Most of the programs we have seen are transient in the sense that they run for a short
time and produce some output, but when they end, their data disappears. If you run the
program again, it starts with a clean slate.
Other programs are persistent: they run for a long time (or all the time); they keep at
least some of their data in permanent storage (a hard drive, for example); and if they shut down
and restart, they pick up where they left off.
Examples of persistent programs are operating systems, which run pretty much
P
whenever a computer is on, and web servers, which run all the time, waiting for requests to come
in on the network.
AP
One of the simplest ways for programs to maintain their data is by reading and writing
text files. We have already seen programs that read text files; in this chapter we will see
programs that write them. An alternative is to store the state of the program in a database.
5.1 FILES:TEXTFILE
R
A textfile is a sequence of characters stored on a permanent medium like a hard drive,
flash memory, or CD-ROM.
CO
beginning of the next screen line. Thus, text files can be directly viewed and created using a text
editor.
ST
In contrast, binary files can contain various types of data, such as numerical values,
and are therefore not structured as lines of text. Such files can only be read and written via a
computer program.
Using Text Files
Fundamental operations of all types of files include opening a file, reading from a file,
.
writing to a file, and closing a file. Next we discuss each of these operations when using text files
in Python.
OPENING TEXT FILES
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
All files must first be opened before they can be read from or written to. In Python, when
a file is (successfully) opened, a file object is created that provides methods for accessing the
file.
All files must first be opened before they can be used. In Python, when a file is opened, a file
object is created that provides methods for accessing the file.
file_object = open(“filename”, “mode”) where file_object is the variable to add the file object.
To open a file for reading, the built-in open function is used as shown,
P
input_file=open('[Link]','r')
AP
The modes are:
‘r’ – Read mode which is used when the file is only being read
‘w’ – Write mode which is used to edit and write new information to the file (any existing
R
files with the same name will be erased when this mode is activated)
‘a’ – Appending mode, which is used to add new data to the end of the file; that is new
CO
information is automatically amended to the end
‘r+’ – Special read and write mode, which is used to handle both actions when working
with a file
U
The first argument is the file name to be opened, '[Link]'. The second argument, 'r',
indicates that the file is to be opened for reading. (The second argument is optional when
ST
opening a file for reading.) If the file is successfully opened, a file object is created and assigned
to the provided identifier, in this case identifier input_fi le.
When opening a file for reading, there are a few reasons why an I/O error may occur.
First, if the file name does not exist, then the program will terminate with a “no such file or
directory” error.
.
... open('[Link]','r')
Traceback (most recent call last):
File " , pyshell#1 . ", line 1, in , module .
open('[Link]','r')
IOError: [Errno 2] No such file or directory:
'[Link]'
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
This error can also occur if the file name is not found in the location looked for
(uppercase and lowercase letters are treated the same for file names). When a file is opened,
it is first searched for in the same folder/directory that the program resides in.
However, an alternate location can be specified in the call to open by providing a path to
the file.
input_file=open('data/[Link]','r')
the file is searched for in a subdirectory called data of the directory in which the program
is contained. Thus, its location is relative to the program location. (Although some operating
P
systems use forward slashes, and other backward slashes in path names, directory paths in
AP
Python are always written with forward slashes and are automatically converted to backward
slashes when required by the operating system executing on.) Absolute paths can also be
provided giving the location of a file anywhere in the file system.
input_file= open('C:/mypythonfiles/data/[Link]','r')
R
When the program has finished reading the file, it should be closed by calling the close method
CO
on the file object,
input_file=open('C:/mypythonfiles/data/[Link]','r')
output_file=open('[Link]','w')
.
output_file.close()
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
P
writelines() #writelines can write a list of strings.
AP
Appending to a file example
fh = open("[Link]", "r")
To read a text file:
fh = open("[Link]","r")
print [Link]()
To read one line at a time:
fh = open("hello".txt", "r")
.
print [Link]()
To read a list of lines:
fh = open("[Link].", "r")
print [Link]()
To write to a file:
fh = open("[Link]","w")
write("Hello World")
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
P
AP
5.1.4 FORMAT OPERATOR
The argument of write has to be a string, so if we want to put other values in a file, we
have to convert them to strings. The easiest way to do that is with str:
R
>>> x = 52
CO
>>> [Link](str(x))
The first operand is the format string, which contains one or more format sequences,
which specify how the second operand is formatted. The result is a string.
ST
For example, the format sequence '%d' means that the second operand should be formatted
as a decimal integer:
>>> camels = 42
>>> '%d' % camels
.
'42'
The result is the string '42', which is not to be confused with the integer value 42.
A format sequence can appear anywhere in the string, so you can embed a value
in a
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
sentence:
If there is more than one format sequence in the string, the second argument has to be a
tuple. Each format sequence is matched with an element of the tuple, in order.
The following example uses '%d' to format an integer, '%g' to format a floating-point
number, and '%s' to format a string:
P
The number of elements in the tuple has to match the number of format sequences in the
string. Also, the types of the elements have to match the format sequences:
AP
>>> '%d %d %d' % (1, 2)
TypeError: not enough arguments for format string
>>> '%d' % 'dollars'
TypeError: %d format: a number is required, not str
R
5.2 COMMAND LINE ARGUMENTS
CO
Command-line arguments in Python show up in [Link] as a list of strings (so you'll
need to import the sys module).
For example, if you want to print all passed command-line arguments:
import sys
U
[Link] is a list in Python, which contains the command-line arguments passed to the
script.
With the len([Link]) function you can count the number of arguments.
If you are gonna work with command line arguments, you probably want to
use [Link].
.
To use [Link], you will first have to import the sys module.
Example
import sys
print "This is the name of the script: ", [Link][0]
print "Number of arguments: ", len([Link])
print "The arguments are: " , str([Link])
Output
ame o f the script: [Link] STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
P
Various error messages can occur when executing Python programs. Such errors are
AP
called exceptions. So far we have let Python handle these errors by reporting them on the screen.
Exceptions can
be “caught” and “handled” by a program, however, to either correct the error and continue
execution,
R
or terminate the program gracefully.
5.3.1 WHAT IS AN EXCEPTION?
CO
An exception is a value (object) that is raised (“thrown”) signaling that an unexpected, or
“exceptional,”situation has occurred. Python contains a predefined set of exceptions referred to
as standard exceptions .
Base class for all errors that occur for
ArithmeticError
U
numeric calculation.
Raised when a calculation exceeds
OverflowError
maximum limit for a numeric type.
ST
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
Raised when an input/ output operation fails,
such as the print statement or the open()
IOError
function when trying to open a file that does
not exist.
OSError Raised for operating system-related errors.
Raised when there is an error in Python
SyntaxError
syntax.
Raised when indentation is not specified
IndentationError
properly.
Raised when an operation or function is
TypeError attempted that is invalid for the specified
data type.
Raised when the built-in function for a data
ValueError type has the valid type of arguments, but the
arguments have invalid values specified.
P
Raised when a generated error does not fall
RuntimeError
into any category.
AP
5.3.2 PYTHON EXCEPTION HANDLING - TRY, EXCEPT AND FINALLY
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
If an exception occurs during execution of the try clause, the rest of the clause is skipped.
Then if its type matches the exception named after the except keyword, the except clause
is executed, and then execution continues after the try statement.
If an exception occurs which does not match the exception named in the except clause, it
is passed on to outer try statements; if no handler is found, it is an unhandled exception
and execution stops with a message
Example
import math
num=int(input('Enter the number'))
print('the factorial is',[Link](num))
P
Output
Enter the number-5
AP
ValueError:Recovery
Example:Program factorial() via
not defined for negative
Exception Handlingvalues
import math
num=int(input('Enter the number'))
valid_input=False;
while not valid_input:
R
try:
result=[Link](num);
CO
print('the factorial is',result)
valid_input=True
except ValueError:
print('Cannot recompute reenter again')
U
num=int(input('Please reenter'))
Output
Enter the number-5 Cannot recompute reenter again
ST
Please reenter5
the factorial is 120
A Python module is a file containing Python definitions and statements. The module that
.
is directly executed to start a Python program is called the main module. Python provides
standard (built-in) modules in the Python Standard Library.
Each module in Python has its own namespace: a named context for its set of identifiers.
The fully
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
qualified name of each identifier in a module is of the form [Link].
Python has a math module that provides most of the familiar mathematical functions. A
module is a file that contains a collection of related functions.
Before we can use the module, we have to import it:
This statement creates a module object named math. If you print the module object, you
get some information about it:
P
>>> print math
<module 'math' (built-in)>
AP
The module object contains the functions and variables defined in the module. To access
one of the functions, you have to specify the name of the module and the name of the
function, separated by a dot (also known as a period). This format is called dot notation.
R
>>> ratio = signal_power / noise_power
>>> decibels = 10 * math.log10(ratio)
CO
>>> radians = 0.7
>>> height = [Link](radians)
U
The first example uses log10 to compute a signal-to-noise ratio in decibels (assuming that
signal_power and noise_power are defined). The math module also provides log, which
ST
>>> [Link](radians)
0.707106781187
The expression [Link] gets the variable pi from the math module. The value of this
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
variable is an approximation of p, accurate to about 15 digits.
If you know your trigonometry, you can check the previous result by comparing it to the
square root of two divided by two:
One of the most useful features of programming languages is their ability to take small
building blocks and compose them. For example, the argument of a function can be any
kind of expression, including arithmetic operators:
P
x = [Link]([Link](x+1))
AP
Almost anywhere you can put a value, you can put an arbitrary expression, with one
exception: the left side of an assignment statement has to be a variable name.
R
>>> minutes = hours * 60 # right
>>> hours * 60 = minutes # wrong!
CO
SyntaxError: can't assign to operator
1. ceil() :- This function returns the smallest integral value greater than the number. If
number is already integer, same number is returned.
ST
2. floor() :- This function returns the greatest integral value smaller than the number. If
number is already integer, same number is returned.
a = 2.3
# returning the ceil of 2.3
print ("The ceil of 2.3 is : ", end="")
print ([Link](a))
# returning the floor of 2.3
print ("The floor of 2.3 is : ", end="")
print ([Link](a))
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
P
# fabs() and factorial()
# importing "math" for mathematical operations
AP
import math
a = -10
b= 5
# returning the absolute value.
print ("The absolute value of -10 is : ", end="")
R
print ([Link](a))
# returning the factorial of 5
CO
5. copysign(a, b) :- This function returns the number with the value of ‘a’ but with the sign of
‘b’. The returned value is float type.
6. gcd() :- This function is used to compute the greatest common divisor of 2
numbers mentioned in its arguments.
.
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
P
print ("The copysigned value of -10 and 5.5 is : ", end="")
print ([Link](5.5, -10))
AP
# returning the gcd of 15 and 5
print ("The gcd of 5 and 15 is : ", end="")
print ([Link](5,15))
Output:
R
The copysigned value of -10 and 5.5 is : -5.5
The gcd of 5 and 15 is : 5
CO
U
ST
.
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
MATH MODULE
This module contains a set of commonly-used mathematical functions, including number-theoretic
functions (such as factorial); logarithmic and power functions; trigonometric (and hyperbolic)
functions; angular conversion functions (degree/radians); and some special functions and constants
(including pi and e). A selected set of function from the math module are presented here.
[Link] returns the ceiling of x (smallest integer greater than or equal to x).
[Link](x) returns the absolute value of x
[Link](x) returns the factorial of x
[Link]() returns the floor of x (largest integer less than x).
P
[Link](s) returns an accurate floating-point sum of values in s (or other iterable).
[Link]() returns the fractional and integer parts of x.
AP
[Link](X) returns the truncated value of s.
[Link](x) returns e**x, for natural log base e.
[Link](x,base) returns log x for base. If base omitted, returns log x base e.
[Link](x) returns the square root of x.
R
[Link](x) returns cosine of x radians.
[Link](x) returns sine of x radians.
CO
[Link](x) returns tangent of x radians.
[Link](x) returns arc cosine of x radians.
[Link](x) returns arc sine of x radians.
[Link](x) returns arc cosine of x radians.
[Link](x) returns x radians to degrees.
U
IMPORTING MODULES
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
A Python module is a file containing Python definitions and statements. When a Python
file is directly executed, it is considered the main module of a program. Main modules are given
the special name __main__. Main modules provide the basis for a complete Python program.
They may import (include) any number of other modules (and each of those modules import
other modules, etc.).
Main modules are not meant to be imported into other modules.
As with the main module, imported modules may contain a set of statements. The
statements of imported modules are executed only once, the first time that the module is
imported. The purpose of these statements is to perform any initialization needed for the
members of the imported module. The Python Standard Library contains a set of predefined
Standard (built-in) modules.
P
AP
1. import modulename
Makes the namespace of modulename available, but not part of, the importing
module. All imported identifiers used in the importing module must be fully
qualified:
R
import math
print('factorial of 16 = ', [Link](16))
CO
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
Packages are namespaces which contain multiple packages and modules themselves.
They are simply directories, but with a change.
Each package in Python is a directory which MUST contain a special file called
__init__.py. This file can be empty, and it indicates that the directory it contains is a Python
package, so it can be imported the same way a module can be imported
P
The __init__.py file is necessary because with this file, Python will know that this
AP
directory is a Python package directory other than an ordinary directory (or folder – whatever
you want to call it).
In this tutorial, we will create an Animals package – which simply contains two module
R
files named Mammals and Birds, containing the Mammals and Birds classes, respectively.
CO
Now, we create the two classes for our package. First, create a file
named [Link] inside the Animals directory and put the following code in it:
ST
1
.
3
class Mammals:
4 def __init__(self):
''' Constructor for this class. '''
# Create some member animals
[Link] = ['Tiger', 'Elephant', 'Wild Cat']
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
5
The class has a property named members – which is a list of some mammals we might be
P
interested in. It also has a method named printMembers which simply prints the list of mammals
AP
of this class!.When you create a Python package, all classes must be capable of being imported,
and won't be executed directly.
Next we create another class named Birds. Create a file named [Link] inside
the Animals directory and put the following code in it:
R
class Birds:
CO
def __init__(self):
''' Constructor for this class. '''
# Create some member animals
[Link] = ['Sparrow', 'Robin', 'Duck']
U
def printMembers(self):
print('Printing members of the Birds class')
for member in [Link]:
ST
This code is similar to the code we presented for the Mammals class.
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
Finally, we create a file named __init__.py inside the Animals directory and put the
following code in it:
That's it! That's all there is to it when you create a Python package. For testing, we create
a simple file named [Link] in the same directory where the Animals directory is located.
We place the following code in the [Link] file:
P
from Animals import Mammals
AP
from Animals import Birds
myMammal = Mammals()
R
[Link]()
CO
# Create an object of Birds class & call a method of it
myBird = Birds()
[Link]()
U
ST
STUCOR APP
DOWNLOADED FROM STUCOR APP
DOWNLOADED
STUCOR APP FROM STUCOR APP
for line in f:
words = [Link]()
num_words += len(words)
print("Number of words:")
print(num_words)
Case 1:
Contents of file:
Hello world
OUTPUT:
Enter file name: [Link]
P
Number of words:
AP
2
Case 2:
Contents of file:
This programming language is
Python
R
Output:
CO
Enter file name: [Link]
Number of words:
5
COPY FILE IN PYTHON
U
with open("[Link]") as f:
with open("[Link]", "w") as f1:
ST
for line in f:
[Link](line)
OUTPUT:
Case 1:
Contents of file([Link]):
.
Hello world
Output([Link]):
Hello world
STUCOR APP
DOWNLOADED FROM STUCOR APP