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

Unit-III Python (1)

Uploaded by

ragavan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
16 views36 pages

Unit-III Python (1)

Uploaded by

ragavan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 36

GE3151 - Problem Solving And Python Programming

UNIT III CONTROL FLOW, FUNCTIONS, STRINGS


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 can be tested for truth value, and used for IF and WHILE condition. There
are two values True and False. 0 is considered as False and all other values considered as True.
Boolean Operations:

Consider x=True, y= False


Operator Example Description
and x and y- returns false Both operand should be true
or x or y- returns true Anyone of the operand should be true
not not x returns false Not carries single operand

3.1 OPERATORS:
Operators are the construct which can manipulate the value of operands.
Eg: 4+5=9
Where 4, 5, 9 are operand
+ is Addition Operator
= is Assignment Operator
Types of Operator:
1. Arithmetic Operator
2. Comparison Operator (or) Relational Operator
3. Assignment Operator
4. Logical Operator
5. Bitwise Operator
6. Membership Operator
7. Identity Operator

1. Arithmetic Operator
It provides some Arithmetic operators which perform some arithmetic operations
Consider the values of a=10, b=20 for the following table.
Operator Meaning Syntax Description
+ Addition a+b It adds and gives the value 30

Unit III Page 3.1


GE3151 - Problem Solving And Python Programming

- Subtraction a-b It subtracts and gives the value -10


* Multiplication a*b It multiplies and gives the value 200
/ Division a/b It divides and gives the value 0.5
% Modulo a%b It divides and return the remainder 0
** Exponent a**b It performs the power and return 1020
// Floor a//b It divides and returns the least quotient

Example Program:
1.Write a Python Program with all arithmetic operators
>>>num1 = int(input('Enter First number: '))
>>>num2 = int(input('Enter Second number '))
>>>add = num1 + num2
>>>dif = num1 - num2
>>>mul = num1 * num2
>>>div = num1 / num2
>>>modulus = num1 % num2
>>>power = num1 ** num2
>>>floor_div = num1 // num2
>>>print('Sum of ',num1 ,'and' ,num2 ,'is :',add)
>>>print('Difference of ',num1 ,'and' ,num2 ,'is :',dif)
>>>print('Product of' ,num1 ,'and' ,num2 ,'is :',mul)
>>>print('Division of ',num1 ,'and' ,num2 ,'is :',div)
>>>print('Modulus of ',num1 ,'and' ,num2 ,'is :',modulus)
>>>print('Exponent of ',num1 ,'and' ,num2 ,'is :',power)
>>>print('Floor Division of ',num1 ,'and' ,num2 ,'is :',floor_div)
Output:
>>>
Enter First number: 10
Enter Second number 20
Sum of 10 and 20 is : 30
Difference of 10 and 20 is : -10
Product of 10 and 20 is : 200
Division of 10 and 20 is : 0.5
Modulus of 10 and 20 is : 10
Exponent of 10 and 20 is : 100000000000000000000
Floor Division of 10 and 20 is : 0
>>>

Unit III Page 3.2


GE3151 - Problem Solving And Python Programming

2. Comparison Operator (or) Relational Operator


These operators compare the values and it returns either True or False according to the
condition. Consider the values of a=10, b=20 for the following table.
Operator Syntax Meaning Description
== a==b Equal to It returns false
!= a!=b Not Equal to It returns true
> a>b Greater than It returns false
< a<b Lesser than It returns true
>= a>=b Greater than or Equal to It returns false
<= a<=b Lesser than or Equal to It returns true

3. Assignment Operator
Assignment operators are used to hold a value of an evaluated expression and used for
assigning the value of right operand to the left operand.
Consider the values of a=10, b=20 for the following table.
Operator Syntax Meaning Description
= a=b a=b It assigns the value of b to a.
+= a+=b a=a+b It adds the value of a and b and assign it to a.
-= a-=b a=a-b It subtract the value of a and b and assign it to a.
*= a*=b a=a*b It multiplies the value of a and b and assign it to a.
/= a/=b a=a/b It divides the value of a and b and assign it to a.
%= a%=b a=a%b It divides the value of a and b and assign the
remainder to a.
It takes ‘a’ as base value and ‘b’ as its power and
**= a**=b a=a**b
assign the answer to a.
It divides the value of a and b and takes the least
//= a//=b a=a//b
quotient and assign it to a.

4. Logical Operator
Logical Operators are used to combine two or more condition and perform logical
operations using Logical AND, Logical OR, Logical Not.
Consider the values of a=10, b=20 for the following table.
Operator Example Description
AND if(a<b and a!=b) Both Conditions are true
OR if(a<b or a!=b) Anyone of the condition should be true
The condition returns true but not
NOT not (a<b)
operator returns false

Unit III Page 3.3


GE3151 - Problem Solving And Python Programming

5. Bitwise Operator
Bitwise Operator works on bits and performs bit by bit operation.
Consider the values of a=60, b=13 for the following table.
Operator Syntax Example Description
Binary AND It do the and operation
& a&b= 12
between two operations
Binary OR It do the or operation between
| a|b= 61
two operations
Binary Ones It do the not operation
~ ~a=61
Complement between two operations
<< Binary Left Shift <<a It do the left shift operation
>> Binary Right Shift >>a It do the right shift operation

A B A&B A|B ~A
0 0 0 0 1
0 1 0 1 1
1 0 0 1 0
1 1 1 1 0

1. Write a Python Program with all Bitwise Operator


a = 10 # 10 = 0000 1010
b = 20 # 20 = 0001 0100
c=0
c = a & b; # 0 = 0000 0000
print ("Line 1 - Value of c is ", c)
c = a | b; # 30 = 0001 1110
print ("Line 2 - Value of c is ", c)
c = ~a; # -11 = 0000 1011
print ("Line 3 - Value of c is ", c)
c = a << 2; # 40 = 0011 1000
print ("Line 4 - Value of c is ", c)
c = a >> 2; # 2 = 0000 0010
print ("Line 5 - Value of c is ", c)

Output:
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is -61
Line 4 - Value of c is 240
Line 5 - Value of c is 15

Unit III Page 3.4


GE3151 - Problem Solving And Python Programming

6. Membership Operator
Membership Operator test for membership in a sequence such as strings, lists or tuples.
Consider the values of a=10, b=[10,20,30,40,50] for the following table.
Operator Syntax Example Description
value in String or If the value is ‘in’ the list then
in a in b returns True
List or Tuple it returns True, else False
value not in String If the value is ‘not in’ the list
not in a not in b returns False
or List or Tuple then it returns True, else False
Example: Output:
x=’python programming’ False
print(‘program’ not in x) True
print(‘program‘ in x) False
print(‘ Program‘ in x)

7. Identity Operator
Identity Operators compare the memory locations of two objects.
Consider the values of a=10, b=20 for the following table.
Operator Syntax Example Description
If the variable 1 value is pointed
to the same object of variable 2
is variable 1 is variable 2 a is b returns False
value then it returns True, else
False
If the variable 1 value is not
variable 1 is not a is not b returns pointed to the same object of
is not
variable 2 False variable 2 value then it returns
True, else False

Example:
x1=7
y1=7
x2=’welcome’
y2=’Welcome’
print (x1 is y1)
print (x2 is y2)
print(x2 is not y2)

Unit III Page 3.5


GE3151 - Problem Solving And Python Programming

Output:
True
False
True

3.2CONTROL STRUCTURES

Control structures

Decision Making Iteration Unconditional Stmt

if statement while loop break statement


if-else statement for loop pass statement
if-elif-else statement nested loop continue statement
Nested Conditional

3.2.1 Decision Making (or) Conditionals (or) Branching


The execution of the program depends upon the condition. The sequence of the control
flow differs from the normal program. The decision making statements evaluate the conditions
and produce True or False as outcome.

Types of conditional Statement


1. if statement
2. if-else statement
3. if-elif-else statement
4. Nested Conditional
1.if statement
If statement contains a logical expression using which data is compared and a decision is
made based on the result of comparison.
Syntax

if expression:
true statements

Unit III Page 3.6


GE3151 - Problem Solving And Python Programming

Flow Chart

Test False
Expressi
on

True

Body of if stmt

Example:
a=10
if a==10:
print(“a is equal to 10”)
Output:
a is equal to 10
2. if else statement
The second form of if statement is “alternative execution” in which there are two possibilities and
the condition determines which block of statement executes.
Syntax
if test_expression:
true statements
else:
false statements

If the testexpression evaluates to true then truestatements are executed else falsestatements are
executed.
Flow Chart

Test
Example: True Expressi False
on
a=10
if a==10:
print(“a is equal to 10”)
Body of if Body of else
else:
print(“a is not equal to 10”)
Output:
End of Code
a is equal to 10

Unit III Page 3.7


GE3151 - Problem Solving And Python Programming

3.elif else Statement(chained conditionals)


The elif statement or chained conditional allows you to check multiple expressions for true
and execute a block of code as soon as one of the conditions evaluates to true. The elif statement
has more than one statements and there is only one if condition.
Syntax

if expression 1:
true statements
elif expression 2:
true statements
elif expression 3:
true statements
else:
false statement

Flow Chart

Test
Expression False
of if

Test
True Expression False
Body of if of elif

True
Body of elif Body of else

End of Code

Unit III Page 3.8


GE3151 - Problem Solving And Python Programming

Example:
a=9
if a==10:
print(“a is equal to 10”)
elif a<10:
print(“a is lesser than 10”)
elif a>10:
print(“a is greater than 10”)
else
print(“a is not equal to 10”)
Output::
a is less than 10

Nested Conditionals (or) Nested if-else


One conditional can also be nested with another condition.(ie) we can have if…elif….else
statement inside another if …elif…else statements.
Syntax

if expression 1:
true statements
else:
if expression 2:
true statements
else:
false statement

Unit III Page 3.9


GE3151 - Problem Solving And Python Programming

Flow Chart

Test
True Condition False
1

Body of if
Test
True Condition False
2

Body of if Body of else

End of Code

Example:
a=10
if a==100:
print(“a is equal to 10”)
else:
if a>100:
print(“a is greater than 100”)
else
print(“a is lesser than 100”)
Output:
a is lesser than 100
3.1.2 Iteration (or) Looping Statement
An Iterative statement allows us to execute a statement or group of statement multiple
times. Repeated execution of a set of statements is called iteration or looping.
Types of Iterative Statement
1. while loop
2. for loop
3. Nested loop

Unit III Page 3.10


GE3151 - Problem Solving And Python Programming

1. while loop
A while loop executes a block of statements again and again until the condition gets false.
The while keyword is followed by test expression and a colon. Following the header is an
indented body.

Syntax
while expression:
true statements

Flow Chart
Entering While
loop

Test
Expression False

True

Body of while
Exit Loop
Example-1:
1.Write a python program to print the first 100 natural numbers
i=1
while (i<=100):
print(i)
i=i+1
Output:
Print numbers from 1 to 100

Example-2:
2. Write a python program to find factorial of n numbers.
n=int(input("Enter the number:"))
i=1
fact=1
while(i<=n):
fact=fact*i
i=i+1
print("The factorial is",fact)

Unit III Page 3.11


GE3151 - Problem Solving And Python Programming

Output:
Enter the number: 5
The factorial is 120
2. for loop
The for loop is used to iterate a sequence of elements (list, tuple, string) for a specified
number of times.
For loop in python starts with the keyword “for”followed by an arbitrary variable name,which
holds its value in the following sequence objects.

Syntax
for iterating_variable in sequence:
statements

A sequence represents a list or a tuple or a string. The iterating variable takes the first item
in the sequence. Next, the statement block is executed. Each item in the list is assigned to the
iterating variable and the statements will get executed until the last item in the sequence get
assigned.

Flow Chart
Entering for each item in
for loop sequence

Is Last
Item
Reached ?No Yes

Body of for
Exit Loop

Unit III Page 3.12


GE3151 - Problem Solving And Python Programming

Example-1:
for letter in”python”:
print(“The current letter:”, letter)
Output:
The current letter: p
The current letter: y
The current letter: t
The current letter: h
The current letter: o
The current letter: n
Example-2:
>>>fruit=[‘apple’, ‘orange’, ‘mango’]
>>>for f in fruit:
print(“The current fruit”, f)
>>>print(“End of for”)
Output:
The current fruit: apple
The current fruit: orange
The current fruit: mango
End of for
3.Nested loop
Python Programming allows using one loop inside another loop. For example using a
while loop or a for loop inside of another while or for loop.

Syntax- nested for loop


for iterating_variable in sequence:
for iterating_variable in sequence:
Innerloop statements
Outer Loop statements

3.1.3.Unconditional Statement
In a situation the code need to exit a loop completely when an external condition is
triggered or need to skip a part of the loop. In such situation python provide unconditional
statements.
Types of Unconditional looping Statement
1. break statement
2. continue statement
3. pass statement

Unit III Page 3.13


GE3151 - Problem Solving And Python Programming

1.break statement
A break statement terminates the current loop and transfers the execution to statement
immediately following the loop. The break statement is used when some external condition is
triggered.
Syntax

break

Flow Chart

Condition Code

If condition
is true break
Condition

If condition is False

Example:
for letter in”python”:
if letter==’h’:
break
print(letter)
print(“bye”)
Output:
pyt
bye

2. continue statement
A continue statement returns the control to the beginning of the loop statement. The
continue statement rejects all remaining statement and moves back to the top of the loop.
Syntax

continue

Unit III Page 3.14


GE3151 - Problem Solving And Python Programming

Flow Chart

Condition Code

If condition
is true
Condition contin
ue

If condition is False

Example:
for letter in”python”:
if letter==’h’:
continue
print(letter)
print(“bye”)
Output:
pyton
bye

3. pass statement
A pass statement is a null operation, and nothing happens when it executed.
Syntax

pass

Example:
for letter in”python”:
if letter==’h’:
pass
print(letter)
print(“bye”)
Output:
python
bye

Unit III Page 3.15


GE3151 - Problem Solving And Python Programming

3.2 Fruitful Functions:


Function that returns value are called as fruitful functions. The return statement is followed
by an expression which is evaluated, its result is returned to the caller as the “fruit” of calling this
function.
Input the valuefruitful functionreturn the result

len(variable) – which takes input as a string or a list and produce the length of string or a list as an
output.
range(start, stop, step) – which takes an integer as an input and return a list containing all the
numbers as the output.
Example-1:
Write a python program to find distance between two points:
import math
def distance(x1,y1,x2,y2): # Defining the Function Distance
dx=x2-x1
dy=y2-y1
print("The value of dx is", dx)
print("The value of dy is", dy)
d= (dx**2 + dy**2)
dist=math.sqrt(d)
return dist
x1 = float(input("Enter the first Number: ")) #Getting inputs from user
x2 = float(input("Enter the Second Number: "))
y1 = float(input("Enter the third number: "))
y2 = float(input("Enter the forth number: "))
print("The distance between two points are",distance(x1,x2,y1,y2))
#Calling the function distance
Output:
>>> Enter the first Number: 2
Enter the Second Number: 4
Enter the third number: 6
Enter the forth number: 12
The value of dx is 4.0
The value of dy is 8.0
The distance between two points are 8.94427190999916
>>>
Explanation for Example 1:
Function Name – ‘distance()’
Function Definition – def distance(x1, y1, x2, y2)
Formal Parameters - x1, y1, x2, y2
Actual Parameter – dx, dy
Return Keyword – return the output value ‘dist’
Function Calling – distance(x1, y1, x2, y2)

Unit III Page 3.16


GE3151 - Problem Solving And Python Programming

Parameter in fruitful function


A function in python
 Take input data, called parameter
 Perform computation
 Return result
def funct(param1,param2):
statements
return value

Once the function is defined,it can be called from main program or from another function.
Function call statement syntax

Result=function_name(param1,param2)

Parameter is the input data that is sent from one function to another. The parameters are of two
types
1. Formal parameter
 The parameter defined as part of the function definition.
 The actual parameter is received by the formal parameter.
2. Actual parameter
 The parameter is defined in the function call

Example-1:
def cube(x):
return x*x*x #x is the formal parameter
a=input(“Enter the number=”)
b=cube(a) #a is the actual parameter
print”cube of given number=”,b
Output:
Enter the number=2
Cube of given number=8

Unit III Page 3.17


GE3151 - Problem Solving And Python Programming

3.3 Composition:
A Composition is calling one function from another function definition.

Example:
Write a python program to add three numbers by using function:
def addition(x,y,z): #function 1
add=x+y+z
return add
def get(): #function 2
a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
c=int(input("Enter third number:"))
print("The addition is:",addition(a,b,c)) #Composition function calling
get() #function calling
Output:
Enter first number:5
Enter second number:10
Enter third number:15
The addition is: 30

3.4 SCOPE :GLOBAL AND LOCAL

Scope is the portion of the program from where a namespace can be accessed directly
without any prefix. When a reference is made inside a function, the name is searched in the local
namespace, then in the global namespace and finally in the built-in namespace.

Local scope Example:


def outer_function():
a=”I am in india”
def inner_function():
a=” I am in TamilNadu”
print(“a=”a)
inner_function()
print(‘a=”,a)

>>>a=”I am in world”
>>>outer_function()
>>>print(‘a=’,a)
Output:
a=I am in TamilNadu
a=I am in India
a=I am in World

Unit III Page 3.18


GE3151 - Problem Solving And Python Programming

Global scope Example:


def outer_function():
global a
a=”I am in india”
def inner_function():
a=” I am in TamilNadu”
print(“a=”a)
inner_function()
print(‘a=”,a)

>>>a=”I am in world”
>>>outer_function()
>>>print(‘a=’,a)
Output:
a=I am in TamilNadu
a=I am in TamilNadu
a=I am in TamilNadu

3.5 Recursion:
A Recursive function is the one which calls itself again and again to repeat the code. The
recursive function does not check any condition. It executes like normal function definition and
the particular function is called again and again
Syntax:

def function(parameter):
#Body of function

Example-1:
Write a python program to find factorial of a number using Recursion:

(Positive value of n , then n! can be calculated as n!=(n-1)….2.1 it can be written as (n-1)!


Hence n! is the product of n and (n-1)! n!=n.(n-1)! )

def fact(n):
if(n<=1):
return n
else:
return n*fact(n-1)
n=int(input("Enter a number:"))
print("The Factorial is", fact(n))

Output:
>>> Enter a number:5
>>> The Factorial is 120

Unit III Page 3.19


GE3151 - Problem Solving And Python Programming

Explanation:
First Iteration - 5*fact(4)
Second Iteration - 5*4* fact(3)
Third Iteration - 5*4*3*fact(2)
Fourth Iteration - 5*4*3*2* fact(1)
Fifth Iteration - 5*4*3*2*1

Example-2:
Write a python program to find the sum of a ‘n’ natural number using Recursion:
def nat(n):
if(n<=1):
return n
else:
return n+nat(n-1)
>>>n=int(input("Enter a number:"))
>>>print("The Sum is", nat(n))
Output:
>>> Enter a number: 5
The Sum is 15
>>>
Explanation:
First Iteration – 5+nat(4)
Second Iteration – 5+4+nat(3)
Third Iteration – 5+4+3+nat(2)
Fourth Iteration – 5+4+3+2+nat(1)
Fifth Iteration – 5+4+3+2+1
3.6 String:
A string is a combination of characters. A string can be created by enclosing the characters
within single quotes or double quotes. The character can be accessed with the bracket operator.
Example:
var1=’Hello’
var2=”Python Programming”
print(var1) # Prints Hello
print(var2) # Prints Python Programming
Traversal with a for Loop
A lot of computations involve in processing a string, one character at a time. Often they
start at the beginning, select each character in turn, do something to it, and continue until the end.
This pattern of processing is called a traversal.
Example:
>>>index = 0
>>>str="Python"
Unit III Page 3.20
GE3151 - Problem Solving And Python Programming

>>>while index < len(str):


letter = str[index]
print(letter, end="")
index = index+1
Output:
Python
3.6.1 String Slices:
A segment of a string is called a slice. Selecting a slice is similar to selecting a character.
Syntax:
variable [start:stop]
<String_name> [start:stop]
Example
Char a= “B A N A N A”
Index from Left 0 1 2 3 4 5
Index from Right -6 -5 -4 -3 -2 -1
>>>print(a[0])  prints B #Prints B Alone 0th Position
>>>print(a[5])  prints A #Prints A Alone Last Position
>>>print(a[-4])  print N #Print From Backwards -4th Position
>>>a[:]  'BANANA' #Prints All
>>>print(a[1:4])  print ANA #Print from 1st Position to 4th Position
>>> print(a[1:-2])  ANA #Prints from 1st position to -3th Position
3.6.2 Strings are Immutable:
Strings are immutable which mean we cannot change the exiting string.
>>>var1=”Hello”
>>>var1[0]=”J” #Displays Error
3.6.3 Strings Methods (or) Types of functions in String:
Consider the value of a, b, c be
a=”Hello”, b=”hELLO”, c=”1234+56”
S.No Method Syntax Description Example
1. len() len(String) Returns the length of the String len(a) 5
The String will be centered
String.center(width,fill along with the width specified a.center(20,+) 
2. center()
char) and the characters will fill the ++++Hello++++
space
Converts all upper case into
3. lower() String.lower() b.lower()  hello
lower case

Unit III Page 3.21


GE3151 - Problem Solving And Python Programming

Converts all lower case into


4. upper() String.upper() a.upper()  HELLO
upper case
It converts the first letter into
5. capitalize() String.capitalize() b.capitalize()  Hello
capital
splits according to the character
c.split(“+”) 
6. split() String.split(“Char”) which is present inside the
[‘1234’,’56’]
function
It concatenates the string with a.join(b) 
7. join() String1.join(String2)
the sequence Hello hELLO
It checks the string is alpha
numeric or not. If the string
8. isalnum() String.isalnum() contains 1 or more c.isalnum()  returns 1
alphanumeric characters it
returns 1, else its returns 0
Returns true if it has at least 1
9. isalpha() String.isalpha() or more alphabet characters, b.isalpha() returns 1
else it return false
Returns true if it has at least 1
10. isdigit() String.isdigit() or more digits, else it return b.isdigit() returns 0
false
Returns true if the string has all
11. islower() String.islower() Lower case characters, else it b.islower()  returns 0
return false
Returns true if the string has all
12. isupper() String.isupper() Upper case characters, else it b.isupper() returns 0
return false
Returns true if the string
a.isnumeric() returns
13. isnumeric() String.isnumeric() contains only numeric character
0
or false otherwise
Returns true if the string a.isspace()  returns 0
14. isspace() String.isspace() contains only wide space e=” ”
character or false otherwise e.isspace()  returns 1
Returns true if the string is
d=”Hello How R U”
15. istitle() String.istitle() properly titled or false
d.istitle() returns 1
otherwise
Returns true if the string
c.isdecimal()  returns
16. isdecimal() String.isdecimal() contains decimal value or false
1
otherwise
Returns title cased, all the d=”hello how h u”
17. title() String.title() characters begin with upper d.title()  ”Hello How
case R U”
a.find(“e”,0,4) 
String.find(“text”, If the string is found it returns
18. find() returns 1 (index
start,end) index position or it returns -1
position)

Unit III Page 3.22


GE3151 - Problem Solving And Python Programming

The string will check for


whether the character is ending
String.endswith(“text” a.endswith(i,0) 
19. endswith() with the specified character. If
, beg, end) returns false
it found it returns true, else
false
It is same as find(). but it raises
String.index(‘text’,beg a.index(‘l’,0)  returns
20. index() exception when the string is not
, end) 2
found
String.count(‘text’,beg It counts howmany times a a.count(‘l’,0)  returns
21. count()
, end) string appears 2
String.rfind(‘text’,beg, It finds a string from right to
22. rfind() a.rfind(‘i’) -1
end) left
String.rindex(‘text’, Same as index() but moves a.rindex(‘l’,0) 
23. rindex()
beg, end) from right to left returns 3
String.rjust(width, It will justify the character into a.rjust(10,’-‘)
24. rjust()
fillchar) right and fill with the character -----Hello
String.ljust(width, It will justify the character into a.ljust(10,a,’+‘)
25. ljust()
fillchar) left and fill with the character Hello+++++
It removes all the spaces at the
26. rstrip() rstrip() rstrip(a)  it returns -1
end
startswith(text, beg, It checks whether the character a.stratswith(H,0) 
27. startswith()
end) starts with the specified one returns true

3.6.4 Strings Modules:


This module contains a number of functions to process standard python strings. Using
import string’ we can invoke string functions.
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"))
Output:
upper => MONTY PYTHON'S FLYING CIRCUS
lower => monty python's flying circus

Unit III Page 3.23


GE3151 - Problem Solving And Python Programming

split => ['Monty', "Python's", 'Flying', 'Circus']


join => Monty+Python's+Flying+Circus
replace => Monty Java's Flying Circus
find => 6 -1
count => 3

The ‘in’ Operator


The word in is a boolean operator that takes two strings and returns True if the first appears as a
substring in the second:
>>>‘t’ in 'python'
True
>>> 'jan' in 'python'
False
3.9 List as Array
To store such data, in Python uses the data structure called list (in most programming
languages the different term is used — “array”).
Arrays are sequence types and like lists, except that the type of objects stored in them is
constrained. A list (array) is a set of objects. Individual objects can be accessed using ordered
indexes that represent the position of each object within the list (array).
The list can be set manually by enumerating of the elements the list in square brackets, like here:
Primes = [2, 3, 5, 7, 11, 13]
Rainbow = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo', 'Violet']
The list Primes has 6 elements, namely:
Primes[0] = 2, Primes[1] = 3, Primes[2] = 5, Primes[3] = 7,Primes[4] = 11, Primes[5] = 13.

ILLUSTRATIVE EXAMPLES
Note- Always get an Input from the USER.
1. Program to find the square root using Newton Method.
2. Program to find the GCD of two numbers
3. Program to find the exponential of a number
4. Program to find the sum of n numbers.
5. Program to find the maximum and minimum in a list
6. Program to perform the linear search
7. Program to perform Binary search

Unit III Page 3.24


GE3151 - Problem Solving And Python Programming

3.1. Write a python Program to Check if a Number is Positive, Negative or 0


Using if...elif...else
num = float(input("Enter a number: "))
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Output:
>>> Enter a number: 5
Positive number
3.2 Using Nested if
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
Output:
>>> Enter a number: 5
Positive number
3.3 Write a Python Program to Check a year is Leap Year or not.
year = int(input("Enter a year: ")) # To get year (integer input) from the user
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
else:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
Output:
>>>
Enter a year: 2000
2000 is a leap year
>>>
Enter a year: 1991
1991 is not a leap year

Unit III Page 3.25


GE3151 - Problem Solving And Python Programming

3.4 Write a Python Program to Print the Fibonacci sequence


nterms = int(input("How many terms? "))
# first two terms
n1 = 0
n2 = 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence upto",nterms,":")
while count < nterms: # Starting of While loop
print(n1,end=' , ')
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1 # Ending of While loop

Output:
How many terms? 10
Fibonacci sequence upto 10 :
0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 ,
>>>

3.5 Write a Python Program to Check a number is Armstrong Number or not.


num = int(input("Enter a number: "))
sum = 0 # initialize sum
temp = num # find the sum and cube of each digit
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
if num == sum: # display the result
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")
Output:
>>> Enter a number: 121
121 is not an Armstrong number
>>>

Unit III Page 3.26


GE3151 - Problem Solving And Python Programming

3.6 Write a Python Program to Find LCM of two numbers


def lcm(x, y):
if x > y:
greater = x
else:
greater = y
while(True):
if((greater % x == 0) and (greater % y == 0)):
lcm = greater
break
greater += 1
return lcm
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("The L.C.M. of", num1,"and", num2,"is", lcm(num1, num2))
Output:
>>> Enter first number: 10
Enter second number: 15
The L.C.M. of 10 and 15 is 30
>>>

3.7 Write a Python Program to Add Two Matrices


X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1],
[6,7,3],
[4,5,9]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]
for r in result:
print(r)

Output:
>>>
[17, 15, 4]
[10, 12, 9]
[11, 13, 18]
>>>

Unit III Page 3.27


GE3151 - Problem Solving And Python Programming

3.8 Write a Python Program to Transpose a Matrix


X = [[12,7],
[4 ,5],
[3 ,8]]
result = [[0,0,0],
[0,0,0]] # iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[j][i] = X[i][j]

for r in result:
print(r)

Output:
>>>
[12, 4, 3]
[7, 5, 8]
>>>

3.9 Python Program to Multiply Two Matrices


# 3x3 matrix
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
# result is 3x4
result = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
# iterate through rows of X
for i in range(len(X)):
# iterate through column Y
for j in range(len(Y[0])):
# iterate through rows of Y
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
for r in result:
print(r)

Output:
>>> [114, 160, 60, 27]
[74, 97, 73, 14]
[119, 157, 112, 23]

Unit III Page 3.28


GE3151 - Problem Solving And Python Programming

3.10 Write a Python Program to Check Whether a String is Palindrome or Not


my_str = 'madame'
my_str = my_str.casefold() # it suitable for case less comparison
rev_str = reversed(my_str) # reverse the string
if list(my_str) == list(rev_str): # check the string is equal to its reverse
print("It is palindrome")
else:
print("It is not palindrome")
Output:
>>>
It is not palindrome
3.11 Write a Python Program to count the number of each vowel in a string.
vowels = 'aeiou' # string of vowels
ip_str = 'Hello, have you tried our turorial section yet?' # change this value
ip_str = input("Enter a string: ")
ip_str = ip_str.casefold() # make it suitable for caseless comparisions
count = {}.fromkeys(vowels,0) # make a dictionary with each vowel a key and value 0
for char in ip_str: # count the vowels
if char in count:
count[char] += 1
print(count)
Output:
>>>{'o': 5, 'i': 3, 'a': 2, 'e': 5, 'u': 3}

Unit III Page 3.29


GE3151 - Problem Solving And Python Programming

TWO MARKS
1. Define Boolean expression with example.
A boolean expression is an expression that is either true or false. The values true and false
are called Boolean values.
Eg :
>>> 5 == 6
>>> False
True and False are special values that belongs to the type bool; they are not strings.

2. What are the different types of operators?


 Arithmetic Operator (+, -, *, /, %, **, // )
 Relational operator ( == , !=, <>, < , > , <=, >=)
 Assignment Operator ( =, += , *= , - =, /=, %= ,**= )
 Logical Operator (AND, OR, NOT)
 Membership Operator (in, not in)
 Bitwise Operator (& (and), | (or) , ^ (binary Xor), ~(binary 1’s complement , << (binary
left shift), >> (binary right shift))
 Identity(is, is not)

3. Explain modulus operator with example.


The modulus operator works on integers and yields the remainder when the first operand is
divided by the second. In Python, the modulus operator is a percent sign (%). The syntax is the
same as for other operators:
Eg:
>>> remainder = 7 % 3
>>> print remainder 1
So 7 divided by 3 is 2 with 1 left over.

Unit III Page 3.30


GE3151 - Problem Solving And Python Programming

4. Explain relational operators.


The == operator is one of the relational operators; the others are:
x! = y # x is not equal to y
x > y # x is greater than y
x < y # x is less than y
x >= y # x is greater than or equal to y
x <= y # x is less than or equal to y

5. Explain Logical operators(University question)


There are three logical operators: and, or, and not. For example, x > 0 and x < 10 is true
only if x is greater than 0 and less than 10. n%2 == 0 or n%3 == 0 is true if either of the conditions
is true, that is, if the number is divisible by 2 or 3. Finally, the not operator negates a Boolean
expression, so not(x > y) is true if x > y is false, that is, if x is less than or equal to y. Non-zero
number is said to be true in Boolean expressions.

6. What is conditional execution?


The ability to check the condition and change the behavior of the program accordingly is
called conditional execution. Example:
If statement:
The simplest form of if statement is:
Syntax:
if statement:
Eg:
if x > 0:
print 'x is positive'
The boolean expression after ‘if’ is called the condition. If it is true, then the indented
statement gets executed. If not, nothing happens.

7. What is alternative execution?


A second form of if statement is alternative execution, that is, if …else, where there are
two possibilities and the condition determines which one to execute.
Eg:
if x%2 == 0:
print 'x is even'

Unit III Page 3.31


GE3151 - Problem Solving And Python Programming

else:
print 'x is odd'

8. What are chained conditionals?


Sometimes there are more than two possibilities and we need more than two branches. One
way to express a computation like that is a chained conditional:
Eg:
if x < y:
print 'x is less than y'
elif x > y:
print 'x is greater than y'
else:
print 'x and y are equal'

elif is an abbreviation of “else if.” Again, exactly one branch will be executed. There is no
limit on the number of elif statements. If there is an else clause, it has to be at the end, but there
doesn’t have to be one.
9. Explain while loop with example. Eg:
def countdown(n):
while n > 0:
print n
n = n-1
print 'Blastoff!'
More formally, here is the flow of execution for a while statement:
1. Evaluate the condition, yielding True or False.
2. If the condition is false, exit the while statement and continue execution at the next
statement.
3. If the condition is true, execute the body and then go back to step 1
10. Explain ‘for loop’ with example.
The general form of a for statement is
Syntax:
for variable in sequence:

Unit III Page 3.32


GE3151 - Problem Solving And Python Programming

code block
Eg:
x=4
for i in range(0, x):
print i
11. What is a break statement?
When a break statement is encountered inside a loop, the loop is immediately terminated
and the program control resumes at the next statement following the loop.
Eg:
while True:
line = raw_input('>')
if line == 'done':
break
print line
print'Done!'

12. What is a continue statement?


The continue statement works somewhat like a break statement. Instead of forcing
termination, it forces the next iteration of the loop to take place, skipping any code in between.
Eg:
for num in range(2,10):
if num%2==0;
print “Found an even number”, num
continue
print “Found a number”, num
13.Compare return value and composition.
Return Value:
Return gives back or replies to the caller of the function. The return statement causes our
function to exit and hand over back a value to its caller.
Eg:
def area(radius):
temp = math.pi * radius**2 return temp
Composition:
Calling one function from another is called composition.

Unit III Page 3.33


GE3151 - Problem Solving And Python Programming

Eg:
def circle_area(xc, yc, xp, yp):
radius = distance(xc, yc, xp, yp) result = area(radius)
return result

14.What is recursion?
The process in which a function calls itself directly or indirectly is called recursion and the
corresponding function is called as recursive function.
Eg:
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)

15. Explain global and local scope.


The scope of a variable refers to the places that we can see or access a variable. If we
define a variable on the top of the script or module, the variable is called global variable. The
variables that are defined inside a class or function is called local variable.
Eg:
def my_local():
a=10
print(“This is local variable”)
Eg:
a=10
def my_global():
print(“This is global variable”)
16.Compare string and string slices.
A string is a sequence of character.
Eg: fruit = ‘banana’
String Slices :
A segment of a string is called string slice, selecting a slice is similar to selecting a
character. Eg: >>> s ='Monty Python'
>>> print s[0:5] Monty

Unit III Page 3.34


GE3151 - Problem Solving And Python Programming

>>> print s[6:12] Python


17. Define string immutability.
Python strings are immutable. ‘a’ is not a string. It is a variable with string value. We can’t
mutate the string but can change what value of the variable to a new string.

18.Mention a few string functions.


s.captilize() – Capitalizes first character of string s.count(sub) – Count number of
occurrences of sub in string
s.lower() – converts a string to lower case
s.split() – returns a list of words in string

19. What are string methods?


A method is similar to a function—it takes arguments and returns a value—but the syntax
is different. For example, the method upper takes a string and returns a new string with all
uppercase letters. Instead of the function syntax upper(word), it uses the method syntax
word.upper().
>>> word = 'banana'
>>> new_word = word.upper()
>>> print new_word
BANANA

20. Explain about string module.


The string module contains number of useful constants and classes, as well as some
deprecated legacy functions that are also available as methods on strings.
Eg: import string
string.upper(text)  converts to upper case
string.lower(text)  converts to lower case

21. What is the purpose of pass statement?


Using a pass statement is an explicit way of telling the interpreter to do nothing.
Eg:
def bar():
pass
If the function bar() is called, it does absolutely nothing.

Unit III Page 3.35


GE3151 - Problem Solving And Python Programming

Unit III Page 3.36

You might also like