0% found this document useful (0 votes)
12 views36 pages

pspp ch3,4,5

Unit III covers control flow and functions in Python, including conditionals, iteration, and fruitful functions. It explains Boolean values, various operators (arithmetic, comparison, assignment, logical, bitwise, membership, and identity), and decision control statements like if, if-else, and loops. Illustrative programs demonstrate practical applications such as calculating square roots and performing searches.

Uploaded by

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

pspp ch3,4,5

Unit III covers control flow and functions in Python, including conditionals, iteration, and fruitful functions. It explains Boolean values, various operators (arithmetic, comparison, assignment, logical, bitwise, membership, and identity), and decision control statements like if, if-else, and loops. Illustrative programs demonstrate practical applications such as calculating square roots and performing searches.

Uploaded by

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

UNIT III CONTROL FLOW, FUNCTIONS

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.

The Bool() function return the value as False and True,respectively

The syntax of bool is :

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

 Comparison (Relational) Operators

 Assignment Operators

 Logical Operators

 Bitwise Operators

 Membership Operators

 Identity Operators

Arithmetic Operators

Arithmetic Operators perform various arithmetic calculations like addition, subtraction,


multiplication, division, %modulus, exponent, etc. There are various methods for
arithmetic calculation in Python like you can use the eval function, declare variable &
calculate, or call functions.

Arithmetic operators in Python

Operator Meaning Example


+ Add two operands or unary plus X+Y
_ Subtract right operand from the left
X-Y
or unary minus
* Multiply two operands X*Y
/ Divide left operand by the right one
X/Y
(always results into float)
% Modulus - remainder of the division of
X%Y
left operand by the right

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

The output of this code is "9."

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)

Comparison operators in Python

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)

The output of this code will be ('x > y is', False)

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

Assignment Operators in python

Operator Meaning Example


= Assigns values from right side c = a + b assigns
operands to value of a + b
left side operand into c
+= It adds right operand to the left c += a is
operandand assign the result to left equivalent
operand
to c = c + a
-= It subtracts right operand from the c -= a is
leftoperand and assign the result to equivalent
left
operand to c = c - a
*= It multiplies right operand with the c *= a is
left equivalent
operand and assign the result to left
operand to c = c * a
3
/= It divides left operand with the right c /= a is
operand and assign the result to left equivalent
operand to c = c / a
%= c %= a is
It takes modulus using two operands equivalent to c =
and c
assign the result to left operand %a
**= Performs exponential (power)
c **= a is
calculation
equivalent to c =
on operators and assign value to the
c
left
** a
operand
//= c //= a is
It performs floor division on operators equivalent to c =
and c
assign value to the left operand // a

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

Logical Operators in python


Operator Meaning Example
Logical AND If both the operands are true then (a and b) is true.
condition becomes true.
Logical OR If any of the two operands are non- (a or b) is true.
zero then condition becomes true.
Logical NOT Used to reverse the logical state of its Not(a and b) is false.
operand.

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.

List of Bitwise Operators

Binary AND(&)

Binary OR(|)

Binary XOR(^)

Binary One’s Complement(~)

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

Operator Meaning Example


& Bitwise AND X & Y =0000
Bitwise OR X Y = 1110

^ Bitwise exclusive OR X^Y=1110


~ Bitwise complement ~X=00001001
(convert all 0 to
1)
<< Shift Left X<<1=00001100
(Bits will move 1
step left)
>> Shift Right Y>>1=00000100

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.

Operato Meaning Example


r
in True if value/variable is found in the sequence 5 in x
Not in True if value/variable is not found in the 5 not in x
sequence

Example: Membership operators in Python

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

Identity operators as explained below:

Operator Meaning Example


Is Evaluates to true if the variables x is y, here is results
on either side in 1 if id(x) equals id(y).
of the operator point to the same
object and false otherwise.
Is not Evaluates to false if the variables x is not y, here is not results in 1 if
on either id(x) is not equal to id(y).

6
side of the operator point to the
same object and true otherwise.

Decision Control Statements

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.

Decision Control Statements are classified into

1. Selection or Conditional Branching Statements


2. Looping Structures or Iterative Control Statements

Selection or Conditional Branching Statements are classified into

1. Conditional (if)
2. Alternative execution (if… else)
3. Chained conditionals (if-elif-else)
4. Nested if Statements

Looping Structures or Iterative Control Statements are classified into

1. While Loop
2. For Loop
3. Nested Loop

SELECTION or CONDITIONAL BRANCHING STATEMENTS

Conditional (if)

Conditional statements give us the ability to check conditions and change the
behaviourof the program accordingly.

The syntax for if statement:

if <test_expression>:
<body>

Flowchart:

7
Example:
x=10
if x> 0 :
print('x is positive')

Alternative execution (if… else)

A second form of the if statement is alternative execution, in which there are


two possibilities and the condition determines which one gets executed

The syntax for if… else statement:

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.

syntax for if-elif-else statement:

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:

print('a is less than b')

elif a > b:

print('a is greater than b')

else:

print('a and b are equal')

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

syntax for Nested conditionals statement:

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

statement x=4 replaces the old value of x (x=5).

Example 2:

x=5

y = x # x and y are now equal

x = 3 # x and y are no longer equal


Print x

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

A while loop statement in Python programming language repeatedly executes a target


statement as long as a given condition is true.

11
Syntax of while Loop

While test_expression:

Body of while

Example:

count=0

while(count <9):

print'The count is:', count

count= count +1

print"Good bye!"

For loop Statement:

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.

Syntax of For Loop

forval in sequence:
Body of for

Example 1:

primes = [2, 3, 5, 7]

forprime in primes:

print(prime)

For loop using range() function:

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

The range function can be used in three different ways.

Range (n) # generates numbers from 0 to n-1

Range ( m,n) # generates numbers for m to n-1

Range(m,n, x) # generates numers from m upto n-1 with skip counting of x

The following program code generates the different sequence of elements.


12
print(range(5))

print(list(range(5)))

print(list(range(2, 5)))

print(list(range(2, 15, 3)))

Result:

range (0, 5)

[0, 1, 2, 3, 4]

[2, 3, 4]

[2, 5, 8, 11, 14]

Python program to print range values

print ‘first loop values’

for x in range(5):

print(x)

print ‘second loop values’

for x in range(3, 6):

print(x)

print ‘third loop values’

for x in range(3, 8, 2):

print(x)

The result is:

First loop values

Second loop values

Third loop values

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.

Syntax for Nested for Loop

foriterating_var in sequence:

foriterating_var in sequence:

statements(s)

statements(s)

Syntax for Nested while Loop

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

if(j > i/j):print i," is prime"

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.

Syntax for Break

For var in sequence:

If condition:

Break

Example:

for i in range(0, 11):


if i == 6:
break
print("The Value of the Variable i is: ", i)

Output:

The Value of the Variable i is: 0

The Value of the Variable i is: 1

The Value of the Variable i is: 2

The Value of the Variable i is: 3

The Value of the Variable i is: 4

The Value of the Variable i is: 5

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.

Syntax for Continue

For var in sequence:

If condition:

Continue

Example 1 :

for letter in'Python':

if letter =='h':

continue

print'Current Letter :', letter

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'Current variable value :',var

print"Good bye!"

Output:

Current variable value : 9


Current variable value : 8
Current variable value : 7
Current variable value : 6
Current variable value : 4
Current variable value : 3
Current variable value : 2

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.

Syntax for Pass

For var in sequence:

If condition:

Pass

Example:

for letter in'Python':

if letter =='h':

pass

print'This is pass block'

print'Current Letter :', letter

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

Data sent to one function from another.

Formal parameter

The parameter defined as part of the function definition,

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)

Local and Global scope:

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():

print("x inside :", x)

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:

NameError: name 'y' is not defined

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:

radius = distance(xc, yc, xp,


yp)

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)

Return result Wrapping that up in a function, we get:

def area2(xc, yc, xp, yp):


radius = distance(xc, yc, xp, yp)
result = area(radius) return
result

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:

def area2(xc, yc, xp, yp):


return area(distance(xc, yc, xp, yp))

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)

You will get the error:

RuntimeError: maximum recursion depth exceeded

The Advantages of recursion

1. Recursive functions make the code look clean and elegant.


2. A complex task can be broken down into simpler sub-problems using recursion.
3. Sequence generation is easier with recursion than using some nested iteration.

The Disadvantages of recursion

1. Sometimes the logic behind recursion is hard to follow through.


2. Recursive calls are expensive (inefficient) as they take up a lot of memory and
time.
3. Recursive functions are hard to debug.

STRINGS:

A Python string is a sequence of characters. There is a built-in class ‘str’ for handling
Python string.

Strings in Python are identified as a contiguous set of characters represented in the


quotation marks. Python allows for either pairs of single or double quotes. Subsets
of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at
0 in the beginning of the string and working their way from -1 at the end.

The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator.

Declaring a Python String

21
declare a string using either single quotes or double quotes.

a=’success is starts here’

print(a)

a=”success is starts here”

print(a)

output

success is starts here

success is starts here

Accessing Characters In Python Strings.

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

-13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

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:

It is used to Combining two Strings into one.

Operator :+

Example:
var1 = ‘Python’
var2 = ‘String’
print (var1+var2)

Output

22
PythonString

2. Appending

It is used to append a string

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

It is used to Prints the character at given index


Operator: [ ]

Example:
var1 = ‘Python’
print (var1[2])

Output
t

5. Range Slicing

It is used to Prints the characters present at the given range .

Operator :[ : ]

Example:

23
var1=‘Python’
print(var1[2:5])

Output

tho

6. Membership in

It is used to Returns ‘True’ value if character is present in the given String.

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

It is used to we can iterate through all the characters of the String.

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[-1] is 'o' -- last char (1st from the end)

 s[-4] is 'e' -- 4th from the end

 s[:-3] is 'He' -- going up to but not including the last 3 chars.

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

The following are some immutable objects:

 int
 float
 decimal
 complex
 bool
 string
 tuple
 range
 frozenset
 bytes

The following are some mutable objects:


 list
 dict
 set
 bytearray
 user-defined classes (unless specifically made immutable)

Built-In String Methodsand Functions In Python.

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:

1. Python String Conversion Functions.

Function Name Description Example Code

capitalize() Returns the String with first var = ‘PYTHON’


character capitalized and rest of print (var.capitalize())
26
the characters in lower case. # Python

lower() Converts all the characters of the var = ‘TechBeamers’


String to lowercase. print (var.lower())
# techbeamers

upper() Converts all the characters of the var = ‘TechBeamers’


String to uppercase. print (var.upper())
# TECHBEAMERS

swapcase() Swaps the case of every character var = ‘TechBeamers’


in the String means that lowercase print (var.swapcase())
characters are changed to # tECHbEAMERS
uppercase and vice-versa.

title() Returns the ‘titlecased’ version of var = ‘welcome to Python


String which means that all words programming’
start with uppercase and rest of print (var.title())
the characters in the words are in # Welcome To Python
lowercase. Programming

count( str[,beg Returns the number of times var=’TechBeamers’


[,end]]) substring ‘str’ occurs in range [beg, str=’e’
end] if beg and end index are print (var.count(str))
given. If it is not given then #3
substring is searched in whole var1=’Eagle Eyes’
String. print (var1.count(‘e’))
Search is case-sensitive. #2
var2=’Eagle Eyes’
print (var2.count(‘E’,0,5))
#1

2. Python Strings Comparison Functions

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

isdecimal() Returns ‘True’ if all the characters in String are num=u’2016′


decimal. If anyone character in the String is of print
other data-type, it will return ‘False’. (num.isdecimal())
Decimal characters are those from Unicode # True
category ‘Nd’.

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.

isnumeric() Returns ‘True’ if all the characters of the Unicode num=u’2016′


String lie in any one of the category ‘Nd’,’No’ and print (num.isnumeric())
‘NI’. # True
If there are any characters other than these, it will num=u’year2016′
return ‘False’. print (num.isnumeric())
Precisely, Numeric characters are those for which # False
Unicode property includes Numeric_Type=Digit,
Numeric_Type=Decimal or
Numeric_Type=Numeric.

isalpha() Returns ‘True’ if String contains at least one print


character (non-empty String) and all the characters (‘python’.isalpha())
are alphabetic, ‘False’ otherwise. # True
print
(‘python3’.isalpha())
# False

isalnum() Returns ‘True’ if String contains at least one print


character (non-empty String) and all the characters (‘python’.isalnum())
are either alphabetic or decimal digits, ‘False’ # True
otherwise. print
(‘python3’.isalnum())
# True

3. Python String Padding Functions

Function Name Description Examples

rjust(width[,fillchar]) Returns a padded version of String with var=’Python’


the original String right-justified to a print (var.rjust(10))
total of width columns. # Python
By default, Padding is done by using print (var.rjust(10,’-‘))
space. Otherwise ‘fillchar’ specifies the # Python—-
filler character.

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.

center(width[,fillchar]) Returns a padded version of String with var=’Python’


the original String moved to center to a print (var.center(20))
total of width columns. # Python
By default, Padding is done by using print
space. Otherwise ‘fillchar’ specifies the (var.center(20,’*’))
filler character. #
*******Python*******

zfill(width) Returns a padded version of String with var=’Python’


the original String padded on the left print (var.zfill(10))
with zeros so that total length of String # 0000Python
becomes equal to width. var=’+Python’
If there is a leading sign (+/-) present in print (var.zfill(10))
the String, then with this function # +000Python
padding is done after the sign, not
before it.

4. Functions To Find A String In Python

Function Name Description Example Code

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

count(str[,i [,j]]) Returns the number of occurrences of var=’This is a good


substring ‘str’ in the String. Searches for ‘str’ example’
in complete String (if i and j not defined) or in str=’is’
a sub-string of String (if i and j are defined). print (var.count(str))
where, #2
i=search starts from this index print
j=search ends at this index. (var.count(str,4,10))
#1

5. Functions To Replace A String In Python.

Function Name Description Example Code

replace(old,new[,count]) Replaces all the occurrences of var=’This is a good


substring ‘old’ with ‘new’ in the String. example’
If ‘count’ is defined then only ‘count’ str=’was’
number of occurrences of ‘old’ will be print
replaced with ‘new’. (var.replace(‘is’,str))
where, # Thwas was a good
old =substring to be replaced exampleprint
new =substring that will replace the (var.replace(‘is’,str,1))
old # Thwas is a good
count =number of occurrences of old example
that will be replaced with new.

split([sep[,maxsplit]]) Returns a list of substring obtained var = “This is a good


after splitting the String with ‘sep’ as example”
delimiter. print (var.split())
where, # [‘This’, ‘is’, ‘a’,
sep= delimiter, default is space ‘good’, ‘example’]print
maxsplit= number of splits to be done (var.split(‘ ‘, 3))
# [‘This’, ‘is’, ‘a’, ‘good
example’]

splitlines(num) Splits the String at line breaks and var=’Print new


returns the list after removing the line line\nNextline\n\nMove
breaks. again to new line’
where, print (var.splitlines())
num = if this is positive value. It # [‘Print new line’,
indicates that line breaks to be ‘Nextline’, ”, ‘Move
included in the returned list. again to new line’]print
(var.splitlines(1))
# [‘Print new line\n’,
‘Nextline\n’, ‘\n’, ‘Move
again to new line’]

join(seq) Returns a String obtained after seq=(‘ab’,’bc’,’cd’)


concatenating the sequence ‘seq’ with str=’=’
a delimiter string. print (str.join(seq))
where, # ab=bc=cd
seq= sequence of elements to be
30
joined

6. Misc String Handling Functions In Python.

Function Name Description Example Code

lstrip([chars]) Returns a String after removing the var=’ This is a good


characters from the beginning of the String. example ‘
where, print (var.lstrip())
Chars=this is the character to be trimmed # This is a good
from the String. Default is whitespace example
character. var=’*****This is a
good example*****’
print (var.lstrip(‘*’))
# This is a good
example**********

rstrip() Returns a String after removing the var=’ This is a good


characters from the End of the String. example ‘
where, print (var.rstrip())
Chars=this is the character to be trimmed # This is a good
from the String. Default is whitespace example
character. var=’*****This is a
good example*****’
print (var.lstrip(‘*’))
# *****This is a good
example

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

len(string) Returns the length of given String var=’This is a good


example’
print (len(var))
# 22

Simple Example for string:

str = 'Hello World!'


printstr # Prints complete string
printstr[0] # Prints first character of the string
printstr[2:5] # Prints characters starting from 3rd to 5th
printstr[2:] # Prints string starting from 3rd character
printstr * 2 # Prints string two times
printstr + "TEST" # Prints concatenated string

This will produce the following result:

Hello World!
31
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

String Module:

The string module provides additional tools to manipulate strings.

This module contains a number of functions to process standard Python strings. Most
functions are available as string methods as well

Example: Using the string module

import string

text = "Monty Python's Flying Circus"

print "upper", "=>", string.upper(text)


print "lower", "=>", string.lower(text)
print "split", "=>", string.split(text)
print "join", "=>", string.join(string.split(text), "+")
print "replace", "=>", string.replace(text, "Python", "Java")
print "find", "=>", string.find(text, "Python"), string.find(text, "Java")
print "count", "=>", string.count(text, "n")

upper => MONTY PYTHON'S FLYING CIRCUS


lower =>monty python's flying circus
split => ['Monty', "Python's", 'Flying', 'Circus']
join =>Monty+Python's+Flying+Circus
replace => Monty Java's Flying Circus
find => 6 -1
count => 3

List as Arrays:

Array:

Array is a collection of similar elements. Elements in the array can be


accessed by index. Index starts with 0. Array can be handled in python by module
named array.

To create array have to import array module in the program.

Syntax :

import array

Syntax to create 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

Program to find sum of array Elements:

import array

sum=0

a=array.array(‘i’,[1,2,3,4,5])

for i in a:

sum=sum+i

print(sum)

Output:

15

Convert list into array:

fromlist() function is used to append list to array. Here the list is act like a array.

Syntax:

arrayname.fromlist(list_name)

Program to convert list into array:

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)

Processing the Array

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

1.Sum the array of numbers:

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

whilepos<len(alist) and not found:

ifalist[pos] == item:

found = True

else:

pos=pos+1

return found

testlist = [1, 2, 32, 8, 17, 19, 42, 13, 0]

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

while first<=last and not found:

midpoint = (first + last)//2

ifalist[midpoint] == item:

found = True

else:

if item <alist[midpoint]:

last = midpoint-1

else:

first = midpoint+1

return found

testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,]

print(binarySearch(testlist, 3))

print(binarySearch(testlist, 13))

Output:

False

True

Important Questions:

Part A:

1. What are Boolean values?


2. Define operator and operand?
3. Write the syntax for if with example?
4. Write the syntax and flowchart for if else.
5. Write the syntax and flowchart for chained if.
6. Write the syntax for while loop with flowchart.
7. Write the syntax for for loop with flowchart.
8. Differentiate break and continue.
9. what is fruitful function and void function.
10. What is parameter and list down its type?
11. What is local and global scope?
12. Differentiate local and global variable?
13. What is function composition, give an example?
14. Define recursion.
15. Define string. How to get a string at run time.
16. What is slicing? Give an example.
35
17. What is immutability of string?
18. List out some string built in function with example?
19. Define string module?
20. How can list act as array?
Part B

1. Explain conditional statements in detail with example(if, if..else, if..elif..else)


2. Explain in detail about operators in detail
3. Explain in detail about iterations with example.(for, while)
4. Explain the usage of else statements in loops
5. Explain in detail about using for loop in sequence.
6. Explain in detail about string built in function with suitable examples?
7. Explain about loop control statement(break, continue, pass)
8. Briefly discuss about fruitful function.
9. Discuss with an example about local and global variable
10. Discuss with an example about function composition
11. Explain in detail about recursion with example.
12. Explain in detail about strings and its operations(slicing,immutablity)
13. Write a program to find sum of array elements.
14. Write a program to search an element using linear search.
15. Write a program to search an element using binary element.

36

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy