0% found this document useful (0 votes)
28 views29 pages

Python Programming: Control Flow Basics

3 unit python

Uploaded by

PPTV
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)
28 views29 pages

Python Programming: Control Flow Basics

3 unit python

Uploaded by

PPTV
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

GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING

CK COLLEGE OF ENGINEERING & TECHNOLOGY


Approved by AICTE, New Delhi, Affiliated to
Anna University.
Accredited by NAAC with ‘B’ Grade, An ISO 9001:2015
Certified institute
Jayaram Nagar, Chellangkuppam, Cuddalore

CLASS – I YEAR (I SEM)


SUBJECT CODE: GE3151 (R-2021)
SUBJECT NAME: 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.

3.1 Boolean values and Operators


The Boolean data type have 2 values (usually denoted by True or False), When converting a
Boolean to an integer, the integer value is always 0 or 1, but when converting an integer to a
Boolean, the Boolean value is true for all integers except 0.

Boolean and logical operators:


Boolean values respond to logical operators ( AND / OR)
True AND False = False
True AND True = True
False AND True= False
False OR True= True
False Or False= False

 A boolean expression is an expression that is either true or false.

BOOLEAN OPERATORS( and,or,not)


These are the Boolean operation, ordered by ascending priority:

1
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING

Operation Result
X or Y If X is false then y, else X
X and Y If X is false, then x else Y
Not X If x is false, then true else False

The following examples use the operator ==, which compares two operands and produces
True if they are equal and False
Otherwise:
>>> 5 == 5
True
>>> 5 == 6
False
True and False are special values that belong to the type bool; they are not strings:
>>>type (True)
<type 'bool'>
>>>type(False)
<type 'bool'>
Boolean and Comparison operators:
The == operator is one of the comparison 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
Although these operations are probably familiar to you, the Python symbols are different
from the mathematical symbols. A common error is to use a single equal sign (=) instead of a
double equal sign (==). Remember that = is an assignment operator and == is a comparison
operator.
3.2. Branching Statements (or) Conditional Statements
 Control Flow is the order in which individual Statements, instructions are executed or
evaluated.
 Flow is just a way or sequence of program Execution.
 Every Statement of a program is executed one by one. Python provides various tools
for flow Control.
 Some of them are if, if...else, if...elif...else, Nested if...elif...else, For, While, Nested,
Break, Continue etc.

2
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING

FLOW CONTROL

Conditional Statements Looping Control Structure

 if  While Loop  Break


 if...else  For Loop  Continue
 if..elif..else  Nested loop  Pass
 Nested if..elif..else

Conditional Statements:

 The execution of the program acts according the conditions. This concept is known
as Conditional statements or Branching Statements.

 Conditional Statements are used to perform different computation or action


depending on whether a condition evaluates to TRUE or FALSE.
,
1. if Statement
2. if...else Statement
3. if..elif..else Statement
4. nested if...elif..else Statement

1. Conditional (if Statement):


 The Boolean expression after the if statement is called the condition. If it is true, then
the indented statement gets executed.
 If the text condition is FALSE, the Statements are not executed.

Syntax:
if (Condition):
True Statement Block

3
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING

Flowchart for if statement:


Example 1:
age=int(input('Enter your age'))
if age>=60: Test
print('You are a Senior Citizen') Condition
print('Good Bye!')

Output 1:
Enter your age69
You are a Senior Citizen TRUE
Good Bye! True Statement Block
Output 2:
Enter your age45
Good Bye!

Example 2:
age=int(input('Enter your age'))
if age>=60:
print('You are eligible for voting')
print('Good Bye!')
Output 1:
Enter your age19
You are eligible for voting
Good Bye!
Output 1:
Enter your age17
Good Bye!
2. Alternative (IF....Else Statement):
 A second form of the if statement is alternative execution, in which there are two
possibilities and the condition determines which one gets executed.

Syntax:
if (Condition):
True Statement Block
else:
False Statement Block

Flowchart for if..else statement

4
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING

Test
Condition

else If Condition is true

False Statement True Condition


Statement

Program:

#Odd (or) Even


num=int(input('Enter a number'))
if num%2==0:
print('The given number is even')
else:
print('The given number is odd')

Output:
Enter a number4567
The given number is odd
[Link] condidtional (If...elif...else Statement):
 If there are more than two possibilities and need more than two branches.
 One way to express a computation like that is a chained conditional.
 elif is an abbreviation of “else if.”
 There is no limit onthe number of elif statements
Syntax:
if Condition 1:
Statement Block1
elif Condition 2:
Statement Block 2
elif Condition 3:
Statement Block 3
else:
False Statement

5
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING

Flowchart for if..elif...else statement:

False
Test
Condition 1

True
elif Test False
Condition 2
True Statement of
condition1 False Statement
True

Statement2 of
condition2

Program
#Greatest among three numbers
x=int(input('Enter a first number'))
y=int(input('Enter a second number'))
z=int(input('Enter a third number'))
if x>y and x>z:
print('x is greater')
elif y>z:
print('y is greater')
elif x==y==z:
print('All are equal')
else:
print('z is greater')
Output:
Enter a first number345

6
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING

Enter a second number678


Enter a third number12
y is greater
[Link] if......Statement:
 if statement can be used inside another if…. statement. This is called nesting. One
condition can also be nested within another.

Syntax:
if Condition 1:
if Condition 2:
True Statement
else :
False Statement

Flowchart for Nested if………. statement:

False True
Test
Condition 1

True Test False


Condition 2
False Statement1

False Statement 2
TrueStatement 2

7
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING

Program:
#Greatest among three numbers
a=int(input('Enter a value'))
b=int(input('Enter b value'))
c=int(input('Enter c value'))
if a>b:
if a>c:
print('a is greater')
elif b>c:
print('b is greater')
else:
print('c is greater')
Output:
Enter a value234
Enter b value67
Enter c value78
a is greater
3.3. Iteration (or) Repetition(or)Looping:
 Computers often do repetitive task. There is a situation when programmers used to
execute a block of code several number of times.
 Repeated execution of a set of statements is called Iteration/Looping.

Python Programming Language provide following types of Iterative Statements.


1. For Loop
2. While Loop
3. Nested for Loop
Loop Type Description
For Loop Executes the sequence of statements multiple times and abbreviates the code that
manages the loop
While Loop Repeats a statement until a give condition is TRUE. It test the While condition
before executing the loop body
Nested for Loop You can use one or more loop inside any other While or For Loop

8
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING

[Link] loop:
 It executes the sequence of statements multiple times based on the condition given.
 The for – loop repeats a given block of codes by specified number of times.

Syntax:

for <variable> in <sequence>:


<statement 1 >
<statement 2>
<statement 3>
.
.
.
<statement n>
Flowchart:

Program – for Loop message = “PROGRAM”


pets_list=[‘Parrot’, ‘Rabbit’, ‘Pigeon’, ‘Dog’] for i in message:
for mypets in pets_list: print(i,end=’ ‘)
print(mypets) Output:
Output: PROGRAM
Parrot
Rabbit
Pigeon
Dog

9
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING

Program: Output:
# Print 'n' natural numbers Enter n value10
n=int(input('Enter n value')) 1 2 3 4 5 6 7 8 9 10
for i in range(1,n+1):
print(i,end=' ')
[Link] loop:
 While loop is used, when we need to repeatedly execute a statement or group of
statements until the condition is true.
 It tests the condition before executing the loop body so this technique is known as
Entry Controlled Loop.
 Here, statements may be a single statement or a block of statements.
 The condition may be any expression, the loop iterates while the condition is true,
when the condition becomes false, program control passes to the line immediately
following the loop.

Syntax:
while expression:
Statement(s)
Flowchart:

10
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING

Program:
# Print 'n' natural numbers using while loop Output:
n=int(input('Enter n value')) Enter n value10
i=1 #loop variable initialization 1 2 3 4 5 6 7 8 9 10
while i<=n: #condition checking
print(i,end=' ') #loop statement
i=i+1 #loop variable incrementation
[Link] Loop:
 Nesting is defined as placing of one loop inside the body of another loop.
 It can use one or more loop inside any another while, for..loop etc.,
Syntax:
For <variable> in <sequence>:
For<variable> in <sequence>:
Statement(s)
Statement(s)
#nested for-->define one for loop with in another for loop
#print 'n' prime numbers
num=int(input('Enter range:'))
print('Prime numbers:',end=' ')
for i in range(1,num+1):#outer loop
for j in range(2,i):#inner loop
if i%j==0:
break # when encounter break statement exit the loop where it is placed.
else:
print(i,end=' ')

[Link]:
 An algorithm is deterministic automation for accomplishing a goal which, given an
initial state, will terminate in a defined end-state.
 When an algorithm is associated with processing information, data is read from an
input source or device, written to an output device, and/or stored for further
processing.
 Stored data is regarded as part of the internal state of the algorithm.
 The state is stored in a data structure.

11
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING

3.4. Loop Control Statements:


 It controls the flow of program execution to get desired result.

Python supports following three control statements:


1. Break.
2. Continue.
3. Pass.

Control Statements Explanation


Break It terminates the loop statement and transfers execution to the
statement immediately following loop.
Continue Causes the loop to skip the remainder of its body and immediately
retest its condition prior to reiterating
Pass The pass statement in python is used when a statement is required
syntactically but we do not want any command or code to execute.

1. Break Statement:
 It 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 you are using nested loops, the break statement stops the execution of the
innermost loop and start executing the next line of code after the block.

Syntax:
Break

Flow Diagram for Break Statement:

Condition Code

If
Condition
is True
Break
Condition

If condition is false

12
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING

Program 1:
for letter in 'python':
if letter=='h':
break
print('current letter:',letter)
Output:
current letter: p
current letter: y
current letter: t
Program 2:
var = 10
while var> 0:
print ('Current variable value :', var)
var = var-1
if var == 5:
break
print( "Good bye!")
Output:
Current variable value : 10
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Good bye!
[Link] statement:
 It returns the control to the beginning of the while loop.
 The continue statementrejects all the remaining statements in the current
iteration of the loop and movesthe control back to the top of the loop.
 The continue statement can be used in both while and for loops.

Syntax:
Continue

13
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING

Flow Diagram for continue Statement:

Condition Code

If
Condition
is True
Continue
Condition

If condition is false

Program 1: Output:
for letter in 'Python': Current Letter : P
if letter == 'h': Current Letter : y
continue Current Letter : t
print('Current Letter :',letter) Current Letter : o
Current Letter : n
Program 2: Output:
var = 10
Current variable value : 9
while var> 0:
Current variable value : 8
var = var -1
Current variable value : 7
if var==5:
Current variable value : 6
continue
Current variable value : 4
print('Current variable value :',var)
Current variable value : 3
print('Good bye!')
Current variable value : 2
Current variable value : 1
Current variable value : 0
Good bye!
[Link] statement:
 It 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.

14
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING

 The pass is also useful in places where your code will eventually go, but has not been
written yet (e.g., in stubs for example)

Syntax:
Pass
Program: Output:
for letter in 'Python': Current Letter: P
if letter=='h': Current Letter: y
pass Current Letter: t
print('This is pass block') This is pass block
print('Current Letter:',letter) Current Letter: h
print('Good bye') Current Letter: o
Current Letter: n
Good bye

3.5 Function:
 A function is a named sequence of statements that performs a computation.
 When define a function, specify the name of the function and the sequence of
statements.
 Call the function by name.
 Commonly function takes” an argument and “returns” a result. The result is called
 the return value.
 The expression in parentheses is called the argument of the function. The result, for
this function, is the type of the argument.
 Functions usually take in data, process it, and return a result. Once a function is
written, it can be used again and again.
 Functions can be from inside of other functions.
Syntax of Function
def function_name(parameters):
function body
return

Function has two types:


 built-in function
 user defined function
built-in function:
 bin()  Returns the binary version of a number
Program: Output:
x = bin(36) 0b100100
print(x)
 bool() - Returns the boolean value of the specified object

15
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING

Program: Output:
x = bool(1) True
print(x)
 eval()  Evaluates and executes an expression
Program: Output:
x = '3*(3+1)*(3+2)' 60
print(eval(x))
 float()  float converts integers and strings to floating-point numbers
Program: Output:
float(32) 32.0

User defined function:


Program:
def add(x,y): #function defintion
z=x+y
return z Function Call
print('Addition value is', add(3,4))

Output:

Addition value is 7
Advantages of Functions:
 Make a code modular
 Functions are reusable
 A program divided into functions, easier to understand and maintain.
Parts of a function
 Function call – add(3,4)
 Function definition – def add( x,y):
z=x+y
return z
Steps to Writing a function
 Understand the purpose of the function.
 Define the data that comes into the function from the caller.
 Define data variables are needed inside the function to accomplish a goal.
 Decide on the steps that the program will use to accomplish this goal.

3.6 Fruitful function


 Functions that return values are called fruitful function.

Input the value


Fruitful functions Return the result

16
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING

 Example: The square function will take one number as parameter and return the
result of squaring that number.

Return values:

Return is a keyword which is used to return a value from the function definition
block to the function calling line.

Return takes zero, values or an expression.

Default value is none.

If many values are used then, use a tuple or list.

Arguments (or) Parameters:

A function in python,
 Takes input data, called parameters or arguments.
 Perform computation
 Returns the result.

def func(param1,param2):
#computations
return result

 Parameter is the input data that is sent from one function to another.
 Parameter is of two types,
 Actual Arguments.
 Formal Arguments.
Actual arguments:
 Argument is defined in the function call.
Formal arguments:
 Argument is defined as part of function definition.
 Actual parameter value is received by formal parameter.
Program:
# Function with actual and formal parameters
def cube(x):#x is formal parameter
return x*x*x
a=int(input('enter the number:'))
b=cube(a)# a is actual parameter
print('cube of the given number:',b)
Output:
enter the number:3
cube of the given number: 27

17
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING

Types of Parameters / Arguments:


1. Required arguments.
2. Keyword arguments.
3. Default arguments.
4. Variable-length arguments.
#Example for Required argument
[Link]
def a(s):
print(s)
return
a(100)
a(100,2)

Output:
100
TypeError: a() takes 1 positional argument but 2 were given
>>>
#Example for Keyword argument
[Link]
def a(s,d):
print(s,d)
return
a(s=100,d="Black")
a(d="Black",s=100)
Output:
Black
Black
#Example for Default argument
[Link]
def a(s,d=20):
print(d,s)
return
a(15)
a(15,5)
Output:
15
15
#Example for Variable-length argument
[Link]
def a(*s):
for i in s:
print(i)
return
a(10,20,30)
a("hai")

18
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING

Output:
10
20
30
hai
#Program to add two numbers by passing parameters
[Link]
def add(a,b):
c=a+b
return c
y=add(2,2)
print(y)
Output:
4

Parameter passing techniques:


 Call by value
 Call by reference
Call by value:
 A copy of actual parameter is passed to formal arguments and any changes made to
the formal arguments have no effect on the actual arguments.
Call by reference:
 A copy of actual parameter is passed to formal arguments and any changes made to
the formal arguments will affect the actual arguments.

SCOPE OF THE VARIABLE:


 A variable in the program can be either local variable or global variable.
 A global variable is a variable that is declared in the main program while a local
variable is a variable declared within the function.

Program:
def f1():
s=55
print(s)
s=10
f1()
Output:
55

19
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING

3.7 Function Composition:


The ability of calling one function from within another function is called as composition.
[Link]
#Program to find square of a number
c=float(input("Enter a value:"))
d=c**2
print(d)

Output:
Enter a value: 2.5
6.25
 Here the input function is used inside float function.
 Input function considers any input value as a string, and according to our needs we
have to use either int() or float() to convert the input value into integer or floating value
to process in our program.

3.8 Recursion:
Recursion is a process of calling a function by itself again and again until some
 condition is satisfied.

A recursive function must have,
 A statement to test whether the function is calling itself again.
 A statement that calls the function itself must be an argument.
 A conditional statement
 A return statement.
Advantages:
 The code looks clean and elegant.
 Large problems broken down into small problems
Disadvantages:
 Logic is hard to follow.
 It takes more memory.
 It is hard to debug.

20
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING

Program:
#Program to find factorial using recursion
def factorial(n):
if n==1:
return 1
else:
return n*factorial(n-1)
num=int(input('Enter the number'))
print('Factorial of given number is',factorial(num))
Output:
Enter the number5
Factorial of given number is 120

3.9 Strings:
 A string is a sequence of characters. (i.e) it can be a letter , a number, or a backslash.
 Python strings are immutable, which means they cannot be changed after they are
created.
String slice:

 A segment of a string is called a slice. Selecting a slice is similar to selecting a


character.
Example:
>>> s = 'MontyPython'
>>> print s[0:5]
Monty
>>> print s[6:13]
Python

 Start- start index value which is included


 End- end index value which is excluded

Example

0 1 2 3 4
B L A C K
-5 -4 -3 -2 -1
The above example contains both positive and negative indexing.

21
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING

[Link]

b='Live and let live'


print(b[0:5])
print(b[3:])
print(b[:6])
print(b[:])
Output:
Live
e and let live
Live a
Live and let live

3.10 Immutability:

Strings in python are immutable i.e after created it cannot be changed.

No assignments can be done later but updating is possible.

[Link]
#NO ITEM ASSIGNMENT IN PYTHON
var1="python"
var1[2]="T"
Output:
var1[2]="T"
Type Error: 'str' object does not support item assignment

[Link]

#NO ITEM DELETION IN PYTHON


var1="python"
del var1
Output:
Type Error: 'str' object does not support item deletion

3.11 String Functions and Methods:

[Link] Operators:

Example
Operator Description a=’Hello’
b=’boys’
Concatenation - Adds values on either side
+ a + b will give ‘Helloboys’
of the operator

22
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING

Repetition - Creates new strings,


* concatenating multiple copies of the same a*2 will give ‘HelloHello’
string
Slice - Gives the character from the given
[] a[1] will give ‘e’
index
Range Slice - Gives the characters from the
[:] a[1:4] will give ‘ell’
given range
Membership - Returns true if a character
in ‘H’ in a will give ‘true’
exists in the given string
Membership - Returns true if a character
not in ‘M’ not in a will give true
does not exist in the given string

Program:

a='I hate bitter food'


b="badly"
print("The Concatenation of the String is:",a+b)
print("The Repetition of the String is:",a*2)
print("The Slicing of the string is:",a[2])
print("The Slicing of the string is:",a[3:6])
print("The membership operator of the string is:",'t' in a)
print("The membership operator of the string is:",'B' not in b)

Output:
The Concatenation of the String is: I hate bitter foodbadly
The Repetition of the String is: I hate bitter foodI hate bitter food
The Slicing of the string is: h
The Slicing of the string is: ate
The membership operator of the string is: True
The membership operator of the string is: True

[Link] Functions and Methods:


A string method is similar to a function; it takes an argument and returns a result. Various
string methods are,
(i)Capitalize the first character of a string.
EX:
[Link]()
(ii)count()
Count the number of characters in a string.
EX:
[Link](‘sustring’,start,end)
(iii) find()
Find the given substring position in a string.

23
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING

EX: [Link](‘substring’,start,end)
(iv) isalpha()
Return True, if one character (or) all the characters are alphabetical.
EX:[Link]()
(v) isdigit()
Return True, if one character (or) all the characters are digit.
EX:[Link] ()
(vi) islower()
Return True, if one character (or) all the characters are in lowercase.
EX:[Link]()
(vii) isupper()
Return True, if one character (or) all the characters are in uppercase.
EX:[Link]()
(viii) isspace()
Return True, if the string has white space.
EX:[Link] ()
(ix) lower()
Covert the string into lowercase.
EX: [Link]()
(x) upper()
Convert the string into uppercase.
EX: [Link]()
(xi) max()
Returns the maximum alphabetical character in a string.
EX:max(s)
(xii) min()
Returns the minimum alphabetical character in a string.
EX: min(s)
(xiii) replace()
Replace the old string with new string.
EX: [Link](‘old’,’new’,maxtime) (or) [Link](‘old’,’new’)
(xiv) len()
Returns the length of the string.
EX: len(s)
Program:
s='welcome'
print(max(s))
print(min(s))
print(len(s))
print([Link]('e',0,7))
print([Link]())
print([Link]())
print([Link]('c',0,7))
print([Link]())
print([Link]('e','c',1))

24
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING

Output:
w
c
7
2
WELCOME
Welcome
3
True
Wclcome

3.12. String Module:

String module has numerous predefined methods to process in Python.


[Link] (String module)
import string
s="Welcome to the world of Robotics"
print("Upper case:",[Link](s))
print("Lower case:",[Link](s))
print("Split:",[Link](s))
print("Join:"," ".join(s))
print("Replace:",[Link](s,"Robotics","Innovation"))
print("Find:",[Link](s,"world"),[Link](s,"of"))
print("Count:",[Link](s,"t"))

Output:

Upper case: WELCOME TO THE WORLD OF ROBOTICS


Lower case: welcome to the world of robotics
Split: ['Welcome', 'to', 'the', 'world', 'of', 'Robotics']
Join: W e l c o m e to the world of Robotics
Replace: Welcome to the world of Innovation
Find: 15 21
Count: 3
3.13 List as Array

 A list in Python is just an ordered collection of items which can be of any type.
 By comparison an array is an ordered collection of items of a single type - so in
principle a list is more flexible than an array but it is this flexibility that makes things
slightly harder when you want to work with a regular structure.
 A list is also a dynamic mutable type and this means you can add and delete
elements from the list at any time.
 To define a list you simply write a comma separated list of items in square brackets,

25
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING

myList=[1,2,3,4,5,6]
 This looks like an array because you can use "slicing" notation to pick out an
individual element - indexes start from 0.
For example print myList[2]
 It will display the third element, i.e. the value 3 in this case. Similarly to change the
third element you can assign directly to it:
myList[2]=100
 The slicing notation looks like array indexing but it is a lot more flexible.
For example myList[2:5]
 It is a sublist from the third element to the fifth i.e. from myList[2] to myList[4].
 The final element specified i.e. [5] is not included in the slice.

3.14 Illustrative Programs:

#1. Square root of a given number


n = int(input("Enter a number")) Output:
Enter a number36
approx = 0.5 * n The square root of a number is: 6.0
for i in range(n):
betterapprox = 0.5 *(approx + n/approx)
approx = betterapprox
print("The square root of a number is:", betterapprox)

# GCD of given numbers Output:


d1 = int(input("Enter a number:")) Enter a number:8
d2 = int(input("Enter another number"))
Enter another number24
rem = d1 % d2
while rem != 0 : gcd of given numbers is : 8
d1 = d2
d2 = rem
rem=d1 % d2
print ("gcd of given numbers is :", d2)
#3. Exponential of a given number Output:
n = input ("Enter a number : ") Enter a number: 4
n = int(n) Enter an exponent: 3
e = input ("Enter an exponent : ")
64
e = int(e)
r=n
for i in range (1,e):
r=n*r
print(r)

26
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING

#4. Sum of an array elements Output:


a = [] Enter number of elements:5
n = int(input("Enter number of elements:")) Enter element:2
for i in range(1,n+1): Enter element:4
b = int(input("Enter element:")) Enter element:12
[Link](b) Enter element:10
print('Sum of array elements=',sum(a)) Enter element:3
Sum of array elements= 31

#5. Linear Search Output 1:


list = [4,1,2,5,3] #Set up array Enter search number5
search = int(input("Enter search number")) 5found at position 3
for i in range(0,len(list)):# Repeat for each item in list
if search==list[i]: #if item at position i is search time Output 2:
print(str(search)+"found at position " + str(i)) #Report Enter search number10
found Element not found
break
else:
print('Element not found')

#6. Binary search Output:


def binary_search(item_list,item): False
first = 0
last = len(item_list)-1 True
found = False
while( first<=last and not found):
mid = (first + last)//2
if item_list[mid] == item :
found = True
elif item <item_list[mid]:
last = mid - 1
else:
first = mid + 1
return found
print(binary_search([1,2,3,5,8], 6))
print(binary_search([1,2,3,5,8], 5))

27
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING

Question Bank
GE3151 / Problem Solving and Python Programming

UNIT III CONTROL FLOW, FUNCTIONS, STRINGS

Knowledge
[Link]. Part –A (2 marks) Competence
Level
1. Write the syntax of if and if-else statements. BTL1 Remember
2. Differentiate for loop and while loop. BTL4 Analyze
3. Illustrate the flowchart of if-elif-else statements. BTL3 Apply
4. Present the flow of execution for a while statement. BTL1 Remember
5. Write the syntax for function definition BTL1 Remember
6. Name the type of Boolean operators. BTL1 Remember
7. Describe break statement with an example. BTL2 Understand
8. Write a program to find square root of a given number BTL3 Apply
9. Analyze different ways to manipulate strings in python. BTL4 Analyze
10. List out the applications of arrays. BTL1 Remember
11. Discuss about continue and pass statements. BTL2 Understand
12. What will be the output of print str[2:5] if str=’hello world!’? BTL1 Remember
13. Give the use of return () statement with a suitable example. BTL2 Understand
14. Write a program to iterate a range using continue statement. BTL1 Remember
15. Where does indexing starts in python? BTL1 Remember
16. Describe various methods used on a string. (Any Four) BTL3 Apply
17. What are the advantages and disadvantages of recursion function? BTL3 Apply
18. Explain the significance of for loop with else in an example BTL 5 Evaluate
19. Define array with an example. BTL1 Remember
20. Classify global variable with local variable BTL 4 Analyze
21. Summarize string modules BTL 5 Evaluate
22. Justify the effects of slicing operations on an array. BTL 5 Evaluate
23. How to access the elements of an array using index? BTL 4 Analyze
Part – B ( 16 Marks)

28
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING

1. (i) Write a python program to find the sum of N natural numbers. Remember
BTL1
(ii) What is the use of pass statement, illustrate with an example.
(i) Define methods in a string with an example program using at
2. least five methods. BTL1 Remember
(ii) How to access characters of a string?
3. Write a program for binary search using Arrays BTL1 Remember
(i). Write a python program to find the given number is odd or
4. even.
BTL2 Understand
(ii). Explain break and continue statement with the help of for loop
in an example.
5. Write a python program to count the number of vowels in a string
BTL 3 Apply
provided by the user.
6. Explain the types of function arguments in python. BTL2 Understand
7. Explain the syntax and flow chart of the following loop statements
BTL2 Understand
(i) for loop (ii) while loop
8. (i). Illustrate the flow chart and syntax of if-elif- else statements
BTL 3 Apply
(ii). Develop a program to find the largest among three numbers
9. Explain recursive function. How do recursive function works? BTL 3 Apply
10. (i). Create a python program to find the given year is leap or not BTL 4 Analyze
(ii). Investigate on mutability and immutability in python
11. Examine the program on Fibonacci series BTL 3 Apply
(i). Generate a program that uses lambda function to multiply two
12. numbers. BTL 4 Analyze
(ii). Discuss the methods to manipulate the arrays in python
13. (i). Create a program to reverse a string without using recursion BTL 3 Apply
(ii). Illustrate the concept of local and global variables
Write a python program to design simple calculator performing
14. arithmetic functions like addition, subtraction, multiplication and BTL 5 Evaluate
division with the input given by user.
Create a program to print the following pattern

15. BTL6 Create

29

You might also like