pspp ch3,4,5
pspp ch3,4,5
Conditionals: Boolean values and operators, conditional (if), alternative (if-else), chained
conditional (if-elif-else); Iteration: state, while, for, break, continue, pass; Fruitful
functions: return values, parameters, local and global scope, function composition,
recursion; Strings: string slices,immutability, string functions and methods, string
module; Lists as arrays. Illustrative programs: square root, gcd, exponentiation, sum an
array of numbers, linear search, binary search.
Boolean values:
Boolean values are the two constant objects False and True. They are used to
represent truth values (other values can also be considered false or true).
Remember that the built-in type Boolean can hold only one of two possible objects: True
or False
The built-in function bool() can be used to cast any value to a Boolean, If the value can
be interpreted as a truth value.
Bool ([value])
Example
>>>x=2
>>>1<x
True
>>>10<x
False
>>>3>x
True
>>>2==x
True
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.
1
Python language supports the following types of operators.
Arithmetic Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Arithmetic Operators
Example: For arithmetic operators we will take simple example of addition where we
will add two-digit 4+5=9
x= 4
y= 5
print x + y
Similarly, you can use other arithmetic operators like for multiplication(*), division (/),
substraction (-), etc.
Comparison(Relational) Operators
These operators compare the values on either side of the operand and determine the
relation between them. It is also referred as relational operators. Various comparison
operators are ( ==, != , <>, >,<=, etc)
2
Operator Meaning Example
> Greater than - True if left operand is
x>y
greater than the right
< Less than - True if left operand is less
x<y
than the right
== Equal to - True if both operands are
x == y
equal
!= Not equal to - True if operands are
x != y
not equal
>= Greater than or equal to - True if left
operand is greater than or equal to x >= y
the right
<= Less than or equal to - True if left
operand is less than or equal to the x <= y
right
Example: For comparison operators we will compare the value of x to the value of y and
print the result in true or false. Here in example, our value of x = 4 which is smaller than
y = 5, so when we print the value as x>y, it actually compares the value of x to y and
since it is not correct, it returns false.
x=4
y=5
print('x > y is',x>y)
Likewise, you can try other comparison operators (x < y, x==y, x!=y, etc.)
Assignment Operators
Python assignment operators are used for assigning the value of the right operand to the
left operand. Various assignment operators used in Python are (+=, - = , *=, /= , etc.)
Example: Python assignment operators is simply to assign the value, for example
a = 21
b = 10
c=0
c=a+b
print "Line 1 - Value of c is ", c
c += a
print "Line 2 - Value of c is ", c
c *= a
print "Line 3 - Value of c is ", c
c /= a
print "Line 4 - Value of c is ", c
c=2
c %= a
print "Line 5 - Value of c is ", c
c **= a
print "Line 6 - Value of c is ", c
c //= a
print "Line 7 - Value of c is ", c
When you execute the above program, it produces the following result:
Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864
Logical Operators
Logical operators in Python are used for conditional statements are true or false. Logical
operators in Python are AND, OR and NOT. For logical operators following condition are
applied.
For AND operator – It returns TRUE if both the operands (right side and left side)
are true
4
For OR operator- It returns TRUE if either of the operand (right side or left side)
is true
For NOT operator- returns TRUE if operand is false
Example
a = True
b = False
print(('a and b is',a and b))
print(('a or b is',a or b))
print(('not a is',not a))
Output
a and b is False
a and b is True
not a is False
Bitwise Operators
Bitwise operators are used to perform bit operations. All the decimal values will be
converted into binary values (sequence of bits i.e 0100, 1100, 1000, 1001 etc) and
bitwise operators will work on these bits such as shifting them left to right or converting
bit value from 0 to 1 etc. Below table shows the different Python Bitwise operators and
their meaning.
Binary AND(&)
Binary OR(|)
Binary XOR(^)
Binary Left-Shift(<<)
Binary Right-Shift(>>)
5
For example, Consider x = 6 and y = 8 and their values in binary form are
x = 0110
y = 1000
Membership Operators
inand not in are the membership operators in Python. They are used to test
whether avalue or variable is found in a sequence (string, list, tuple, set and dictionary).
In a dictionary we can only test for presence of key, not the value.
x = 'Hello world'
print('H' in x)
print('a' in x)
output
True
False
Identity Operators
Identity operators compare the memory locations of two objects. There are two
6
side of the operator point to the
same object and true otherwise.
The decision control statements are the decision making statements that decides
the order of execution of statements based on the conditions. In
thedecision making statements the programmer specify which conditions are to be
executed or tested with the statements to be executed if the condition is true or false.
1. Conditional (if)
2. Alternative execution (if… else)
3. Chained conditionals (if-elif-else)
4. Nested if Statements
1. While Loop
2. For Loop
3. Nested Loop
Conditional (if)
Conditional statements give us the ability to check conditions and change the
behaviourof the program accordingly.
if <test_expression>:
<body>
Flowchart:
7
Example:
x=10
if x> 0 :
print('x is positive')
if
<test_expression>:
<body_1>
else:
<body_2>
Flowchart:
Example:
x=11
if x%2 == 0 :
print('x is even')
else :
print('x is odd')
8
Chained conditionals (if-elif-else)
Chained conditionals (if-elif-else) allows more than two possibilities and need
more than two branches.
if <test_expression_1>:
<body1>
elif<test_expression_2>:
<body2>
elif<test_expression_3>:
<body3>
….
…..
else:
<bodyN>
Flowchart:
Example:
a=10
b=20
if a < b:
elif a > b:
else:
Nested conditionals
9
The conditional statement is written within another conditional statement. This is called
nested conditionals. Any number of conditional statements can be nested inside one
another
if test expression:
Body of if
else:
if test expression:
Body of if
else:
if test expression:
Body of if
:
else:
Body of else
Flowchart
Example
a=20
b=10
if a == b:
print('a and b are equal')
else:
if a < b:
print('a is less than b')
else:
print('a is greater than b')
10
LOOPING STRUCTURES OR ITERATIVE CONTROL STATEMENTS
State of a variable
It is possible to have more than one assignment for the same variable. The value which
is assigned at the last is given to the variable. The new assignment makes an existing
variable assigned with new value by replacing the old value. For example, consider the
following Example.
Example 1:
x=5
y=3
x=4
print x
print y
The result is
The variable x is first assigned with 5 then it is assigned with 4. The last assignment
Example 2:
x=5
Print y
The result is
The result is
3
5
Here the variable x is assigned with the value 5. The variable y is assigned with the
value of x. Finally, the value of x is updated to 3. So, the value 3 is assigned to x. This is
called state of the variable.
The whileLoop
11
Syntax of while Loop
While test_expression:
Body of while
Example:
count=0
while(count <9):
count= count +1
print"Good bye!"
The For loop in Python is used to iterate over a sequence (list, tuple, string) or other
iterable objects. Iterating over a sequence is called traversal.
forval in sequence:
Body of for
Example 1:
primes = [2, 3, 5, 7]
forprime in primes:
print(prime)
The range of a function is the complete set of all possible resulting values of the
dependent variable
The body of the loop is apparent through indentation used. The loop body starts with
indentation and the first unintended statement denotes the end. To generate the
sequence of numbers range () function is used
print(list(range(5)))
print(list(range(2, 5)))
Result:
range (0, 5)
[0, 1, 2, 3, 4]
[2, 3, 4]
for x in range(5):
print(x)
print(x)
print(x)
5
13
7
Nested Loop
Python programming language allows to use one loop inside another loop. Following
section shows few examples to illustrate the concept.
foriterating_var in sequence:
foriterating_var in sequence:
statements(s)
statements(s)
while expression:
while expression:
statement(s)
statement(s)
Example
i =2
while(i <20):
j =2
while(j <=(i/j)):
ifnot(i%j):break
j = j +1
i = i +1
print"Good bye!"
Output
2 is prime
3 is prime
5 is prime
14
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
Good bye!
CONTROL STATEMENTS:
It Controls the flow of program Execution to get desire result. The Control Statements
are
1. Break
2. Continue
3. Pass
Break Statement
The break statement in Python terminates the current loop and resumes execution at
the next statement,
The most common use for break is when some external condition is triggered requiring a
hasty exit from a loop. The break statement can be used in both while and for loops.
If condition:
Break
Example:
Output:
Continue Statement
15
The continue statement in Python returns the control to the beginning of the while
loop. The continue statement rejects all the remaining statements in the current
iteration of the loop and moves the control back to the top of the loop.
The continuestatement can be used in both while and for loops.
If condition:
Continue
Example 1 :
if letter =='h':
continue
Output :
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Example 2 :
var=10
whilevar>0:
var=var-1
ifvar==5:
continue
print"Good bye!"
Output:
16
Current variable value : 1
Current variable value : 0
Good bye!
Pass Statement:
The pass statement in Python is used when a statement is required syntactically but
you do not want any command or code to execute. The pass statement is a null
operation; nothing happens when it executes.
If condition:
Pass
Example:
if letter =='h':
pass
print"Good bye!"
Output:
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!
FRUITFUL FUNCTIONS
Fruitful functions are functions that return value. While using fruitful function, the return
value must be handled properly by assigning it to a variable or use it as part of
expression.
Return values
The built-in functions we have used, such as abs, pow, int, max, and range, have
produced results. Calling each of these functions generates a value, which we usually
assign to a variable or use as part of an expression.
Example:
17
biggest=max(3,7,2,5)
x=abs(3-11)+10
we are going to write more functions that return values, which we will call fruitful
functions, for want of a better name. The first example is area, which returns the area of
a circle with the given radius:
defarea(radius):
b=3.14159*radius**2
returnb
We have seen the return statement before, but in a fruitful function the return statement
includes a return value. This statement means: evaluate the return expression, and
then return it immediately as the result (the fruit) of this function. The expression
provided can be arbitrarily complicated, so we could have written this function like this:
defarea(radius):
return3.14159*radius*radius
Parameters:
Parameter
Formal parameter
Example
x in:
def cube(x):
return x*x*x
Actual Parameter -- The actual data sent to a function. It's found in the function call,
Example
7 in
result = cube(7)
or
y in:
y=5
res = cube(y)
Global Variables :
In Python, a variable declared outside of the function or in global scope is known as
global variable. This means, global variable can be accessed inside or outside of the
function.
18
Example
x = "global"
def foo():
foo()
print("x outside:", x)
output:
x inside : global
x outside: global
In above code, we created x as a global variable and defined a foo() to print the global
variable x. Finally, we call the foo() which will print the value of x.
Local Variables
A variable declared inside the function's body or in the local scope is known as local
variable.
Example 1:
def foo():
y = "local"
foo()
print(y)
output:
The output shows an error, because we are trying to access a local variable y in a global
scope whereas the local variable only works inside foo() or local scope.
Example 2:
def foo():
y = "local"
print(y)
foo()
output
local
Let's take a look to the earlier problem where x was a global variable and we wanted to
modify x inside foo().
19
Function Composition:
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 f and g is denoted f(g(x)). x is the argument of g, the result of g is passed
as the argument of f and the result of the composition is the result of f.
As an example, we’ll write a function that takes two points, the center of the
circle and a point on the perimeter, and computes the area of the circle.
Assume that the center point is stored in the variables xc and yc, and the
perimeter point is in xp and yp. The first step is to find the radius of the circle, which is
the distance between the two points. Fortunately, we’ve just written a function, distance,
that does just that, so now all we have to do is use it:
The second step is to find the area of a circle with that radius and return it. Again
we will use one of our earlier functions:
result = area(radius)
We called this function area2 to distinguish it from the area function defined
earlier. There can only be one function with a given name within a given module. The
temporary variables radius and result are useful for development and debugging, but
once the program is working, we can make it more concise by composing the function
calls:
Recursion
Recursion is a process in which a function calls itself as a subroutine. This allows the
function to be repeated several times, since it calls itself during its execution. Functions
that incorporate recursion are called recursive functions.
Recursion is often seen as an efficient method of programming since it requires the least
amount of code to perform the necessary functions. However, recursion must be
incorporated carefully, since it can lead to an infinite loop if no condition is met that will
terminate the function.
Example:
def factorial(n):
if n ==1:
20
return1
else:
return n * factorial(n-1)
print factorial(3)
When calling the factorial function n = 3. Thus it returns n * factorial(n-1). This process
will continue until n = 1. If n==1 is reached, it will return the result.
Limitations of Recursions
Everytime a function calls itself and stores some memory. Thus, a recursive function
could hold much more memory than a traditional function. Python stops the function
calls after a depth of 1000 calls. If you run this example:
def factorial(n):
if n ==1:
return1
else:
return n * factorial(n-1)
print factorial(3000)
STRINGS:
A Python string is a sequence of characters. There is a built-in class ‘str’ for handling
Python string.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator.
21
declare a string using either single quotes or double quotes.
print(a)
print(a)
output
You just need to know the index of a character to retrieve it from the String.
However, the range of characters can be accessed with the slicing feature.
Like the most programming languages, Python allows to index from the zeroth position
in Strings. But it also supports negative indexes. Index of ‘-1’ represents the last
character of the String. Similarly using ‘-2’ we can access the penultimate element of the
string and so on.
P Y T H O N – S T R I N G
0 1 2 3 4 5 6 7 8 9 10 11 12
Exampe:
sample_str='Python String'
print(sample_str[0])# return 1st character
# output: P
print(sample_str[-1])# return last character
# output: g
print(sample_str[-2])# return last second character
# output: n
Python String Operators
1. Concatenation:
Operator :+
Example:
var1 = ‘Python’
var2 = ‘String’
print (var1+var2)
Output
22
PythonString
2. Appending
Operator:+=
Example:
Str = “Hello”
Name=input(“\n Enter your name:”)
Str += name
Str += “Welcome to Python Programming.”
Print(str)
Output
Enter your name :Arnav
HelloArnav Welcome to Python Programming.
3. Repetition
It is used to Creates new String by repeating the String given number of times.
Operator :*
Example:
var1 = ‘Python’
print (var1*3)
Output
PythonPythonPython
4. Slicing
Example:
var1 = ‘Python’
print (var1[2])
Output
t
5. Range Slicing
Operator :[ : ]
Example:
23
var1=‘Python’
print(var1[2:5])
Output
tho
6. Membership in
Operator: in
Example:
var1=‘Python’
print(‘n’invar1)
Output
True
7. Membership not in
It is used to Returns ‘True’ value if character is not present in given String.
Operator: not in
Example:
var1 = ‘Python’
print (‘N’ not in var1)
Output
True
8. Iterating
Operator: for
Example:
var1 ='Python'
forvarin var1:
print(var)
Output
#P
#y
#t
#h
#o
#n
9. Raw String
24
It is used to ignore the actual meaning of Escape characters inside a string. For
this we add ‘r’ or ‘R’ in front of the String.
Operator : r\R
Example:
print (r’\n’)
print (R’\n’)
Output
\n
\n
STRING SLICES:
A substring of a string is called a slice. The slice operation is used to refer to sub-parts
of sequences and strings.
The "slice" syntax is a handy way to refer to sub-parts of sequences -- typically strings
and lists. The slice s[start:end] is the elements beginning at start and extending up to
but not including end. Suppose we have s = "Hello"
s[1:4] is 'ell' -- chars starting at index 1 and extending up to but not including index 4
s[1:] is 'ello' -- omitting either index defaults to the start or end of the string
s[:] is 'Hello' -- omitting both always gives us a copy of the whole thing (this is the
pythonic way to copy a sequence like a string or list)
s[1:100] is 'ello' -- an index that is too big is truncated down to the string length
The standard zero-based index numbers give easy access to chars near the start of the
string. As an alternative, Python uses negative numbers to give easy access to the chars
at the end of the string: s[-1] is the last char 'o', s[-2] is 'l' the next-to-last char, and so
on. Negative index numbers count back from the end of the string:
s[-3:] is 'llo' -- starting with the 3rd char from the end and extending to the end of the
string.
25
It is a neat truism of slices that for any index n, s[:n] + s[n:] == s. This works even for
n negative or out of bounds. Or put another way s[:n] and s[n:] always partition the
string into two string parts, conserving all the characters. As we'll see in the list section
later, slices work with lists too.
Immutability:
Python defines variety of data types of objects. These objects are stored in memory.
Contents of some objects can be changed after they are created while others can't be
changed. Numeric objects such as integer, float and complex number objects occupy the
memory and memory contents can not be changed. Such objects are called immutable.
String and dictionary objects are also immutable. Tuple is also immutable. List object
however is mutable because items in a list object can be modified, deleted or added in a
list.
int
float
decimal
complex
bool
string
tuple
range
frozenset
bytes
A method is like a function, but it runs "on" an object. If the variable s is a string, then
the code s.lower() runs the lower() method on that string object and returns the result
(this idea of a method running on an object is one of the basic ideas that make up
Object Oriented Programming, OOP). Here are some of the most common string
methods:
Function
Name Description Example Code
islower() Returns ‘True’ if all the characters in the String are var=’Python’
in lowercase. If any one character is in uppercase it print (var.islower())
will return ‘False’. # False
var=’python’
print (var.islower())
# True
isupper() Returns ‘True’ if all the characters in the String are var=’Python’
in uppercase. If any one character is in lowercase it print (var.isupper())
will return ‘False’. # False
var=’PYTHON’
print (var.isupper())
27
# True
isdigit() Returns ‘True’ for any character for which print (‘2’.isdigit())
isdecimal() would return ‘True and some characters # True
in ‘No’ category. print (‘²’.isdigit())
If there are any characters other than these, it will # True
return ‘False’.
Precisely, digits are the characters for which
Unicode property includes:
Numeric_Type=Digit or Numeric_Type=Decimal.
For example, superscripts are digits but fractions
not.
28
ljust(width[,fillchar]) Returns a padded version of String with var=’Python’
the original String left-justified to a total print (var.ljust(10))
of width columns. # Python
By default, Padding is done by using print (var.ljust(10,’-‘))
space. Otherwise ‘fillchar’ specifies the # Python—-
filler character.
find(str [,i [,j]]) Searches for ‘str’ in complete String (if i and j var=”Tech Beamers”
not defined) or in a sub-string of String (if i str=”Beam”
and j are defined).This function returns the print (var.find(str))
index if ‘str’ is found else returns ‘-1’. #5
where, var=”Tech Beamers”
i=search starts from this index str=”Beam”
j=search ends at this index. print (var.find(str,4))
#5
var=”Tech Beamers”
str=”Beam”
print (var.find(str,7))
# -1
index(str[,i [,j]]) This is same as ‘find’ method. The only var=’Tech Beamers’
difference is that it raises ‘ValueError’ str=’Beam’
exception if ‘str’ is not found. print (var.index(str))
#5
var=’Tech Beamers’
str=’Beam’
print (var.index(str,4))
#5
var=’Tech Beamers’
str=’Beam’
print (var.index(str,7))
# ValueError:
substring not found
rfind(str[,i [,j]]) This is same as find() just that this function var=’This is a good
returns the last index where ‘str’ is found. If example’
29
‘str’ is not found it returns ‘-1’. str=’is’
print
(var.rfind(str,0,10))
#5
print (var.rfind(str,10))
# -1
rindex(str[,i [,j]]) Searches for ‘str’ in complete String (if i and j var=’This is a good
not defined) or in a sub-string of String (if i example’
and j are defined).This function returns the str=’is’
last index where ‘str’ is found. print
If ‘str’ is not found it raises ‘ValueError’ (var.rindex(str,0,10))
exception.where, #5
i=search starts from this index print
j=search ends at this index. (var.rindex(str,10))
# ValueError:
substring not found
Hello World!
31
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
String Module:
This module contains a number of functions to process standard Python strings. Most
functions are available as string methods as well
import string
List as Arrays:
Array:
Syntax :
import array
Array_name = module_name.function_name(‘datatype’,[elements])
example:
a=array.array(‘i’,[1,2,3,4])
a- array name
32
array- module name
i- integerdatatype
import array
sum=0
a=array.array(‘i’,[1,2,3,4,5])
for i in a:
sum=sum+i
print(sum)
Output:
15
fromlist() function is used to append list to array. Here the list is act like a array.
Syntax:
arrayname.fromlist(list_name)
import array
sum=0
l=[6,7,8,9,5]
a=array.array('i',[])
a.fromlist(l)
for i in a:
sum=sum+i
print(sum)
The programmer can easily perform certain operations by using these methods.
Syntax:
Objectname.method()
Methods in Array:
a=[2,4,6,8]
33
S.No Syntax Example Description
1 append() >>>a.append(10) This method is used to add the
[2,4,6,8,10] at the end of the array.
2 insert(index,element) >>>a.insert(2,5) This method is used to add the
[2,4,5,6,8,10] value at the position specified in
its argument.
3 pop(index) >>>a.pop(1) This function removes the
[2,5,6,8,10]
mentioned in its argument, and
elementat the position returns it.
4 index(element) >>>a.index(2) This function returns the index of
0 value
5 reverse() >>>a.reverse() This function reverses the array.
[10,8,6,5,2]
6 count() >>>a.count() This is used to count number of
5 elements in an array.
Illustrative Problems
deflistsum(numList):
iflen(numList) == 1:
returnnumList[0]
else:
returnnumList[0] + listsum(numList[1:])
print(listsum([1,3,5,7,9,11]))
Output :
36
2.Linear Search:
defsequentialSearch(alist, item):
pos = 0
found = False
ifalist[pos] == item:
found = True
else:
pos=pos+1
return found
print(sequentialSearch(testlist, 3))
print(sequentialSearch(testlist, 13))
Output:
False
34
True
3.Binary Search:
defbinarySearch(alist, item):
first = 0
last = len(alist)-1
found = False
ifalist[midpoint] == item:
found = True
else:
if item <alist[midpoint]:
last = midpoint-1
else:
first = midpoint+1
return found
print(binarySearch(testlist, 3))
print(binarySearch(testlist, 13))
Output:
False
True
Important Questions:
Part A:
36