0% found this document useful (0 votes)
25 views41 pages

Unit 3 Q A

Uploaded by

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

Unit 3 Q A

Uploaded by

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

Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

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, scope: local and global,
function composition, recursion; Strings: string slices, immutability, string
functions and methods, string module; Lists as arrays. Illustrative programs:
square root, gcd, exponentiation, sum the array of numbers, linear search,
binary search.

PART - A
1) Define Boolean values.
 Boolean values are the two constant objects False and True.
 They are used to represent truth values (false or true).
 In numeric contexts (for example, when used as the argument to an arithmetic
operator), they behave like the integers 0 and 1, respectively.
 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
 They are written as False and True, respectively.
2) List out the Boolean operators:
 or operator
Example: x or y
 and operator
Example: x and y
 not operator
Example: not x
3) Define operator. Give example of operator.
 Operator is a symbol that is used to manipulate mathematical and other
expression.
 Expression is the combination of operator and operands.
Example: a + b
 a, b are operator
 + is a operands
4) List out the types of operator.
Python language supports the following types of operators.
o Arithmetic Operators
o Comparison (Relational) Operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators

Unit III 58
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

5) Define conditional statements.


Decision structures evaluate multiple expressions which produce TRUE or
FALSE as outcome. Let need to determine which action to take and which statements
to execute if outcome is TRUE or FALSE otherwise.
Types of Conditional statements
 if statements (conditional)
 if-else statements (alternative)
 if-elif-else (chained conditional)
 Nested Conditional
6) What is the purpose of iteration? Give example
Iteration is simply known as looping. A loop statement allows us to execute a
statement or group of statements multiple times. Repeated execution of a set of
statements is called iteration.
Types
i) while loop
ii) for loop
iii) nested loop
Example
count = 0
while (count < 9):
print(“The count is:”, count )
count = count + 1
7) What are unconditional looping statements?
Any loop that needs to be executed compulsorily without any condition is
called an unconditional loop. This means that the loop will be executed in the program
without any conditional checks and the output of the loop is an essential one for the
completion of the program.
Example:
i) break statement
ii) continue statement
iii) pass statement

8) What is the purpose break, continue and pass statement in python?


break: It terminates the loop statement and transfers execution to the statement
immediately following the loop.
Continue: It 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 you do not want any command or code to execute.
9) Write a Python program to accept two numbers, multiply them and print the
result. [AU – Jan 2018]

Unit III 59
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

a=int(input(“Enter A:”))
b=int(input(“Enter B:”))
c=a*b
print(“The product of the given two numbers:”,c)
10) Write a Python program to accept two numbers, find the greatest and print the
result. [AU – Jan 2018]
a=int(input(“Enter A:”))
b=int(input(“Enter B:”))
if a > b:
print(“First number is largest “,a)
else:
print(“Second number is largest “,b)
11) Do Loop statements have else clause? When will it be executed? [AU – Dec
2019]
Yes, In Python, else clause is associated with looping statements. But, it is optional one.
The else clause executes after the loop completes normally. This means that the loop did not
encounter a break statement.
Example:
i=1
while i<5:
print(i)
i=i+1
else:
print("After Loop")
print("The End")
Output:
1
2
3
4
5
After Loop
The End

12) Write a program to display a set of strings using range() function. [AU –
Dec 2019]
for i in range(3):
print(“Success”)
print(“**********”)

for i in range(2**3):
print(“Success”)
print(“**********”)
Output:
Success
Success
Success
**********
Success
Success
Success
Success

Unit III 60
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

Success
Success
Success
Success
**********
13) What are function and fruitful function? Function
Function is a block of statement that will execute for a specific task.
Fruitful function
Functions that return values are sometimes called fruitful functions. In many
other languages, a function that doesn’t return a value is called a procedure, but we will stick
here with the Python way of also calling it a function, or if we want to stress it, a non-
fruitful function.
14) Define parameter. List out its types.
Data sent to one function from another is called parameter. There are two
types of parameters are available in general, they are given below.
i) Formal parameter
ii) Actual Parameter
15) How will you call a function by arguments?
You can call a function by using the following types of formal arguments:
 Required arguments
 Keyword arguments
 Default arguments
 Variable-length arguments
16) Define scope of the variable and its types.
All variables in a program may not be accessible at all locations in that program.
This depends on where you have declared a variable. The scope of a variable determines
the portion of the program where you can access a particular identifier.
There are two basic scopes of variables in Python:
 Global variables
 Local variables
17) What is composition?
In situation to call one function from within another function. This
ability is called composition.
Example:
radius = distance(xc, yc, xp, yp)
result=area(radius)
return result
18) Define recursion with example. [AU – Jan
2019]
The function call by itself, this is known as recursion.
Example:
def factorial(n):
if n == 0:

Unit III 61
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

return 1
else:
fact = n*factorial(n-1)
return result
19) List out the advantages of recursion.
 Recursion adds clarity and (sometimes) reduces the time needed to write and debug
code (but doesn't necessarily reduce space requirements or speed of execution).
 Reduces time complexity.
 Performs better in solving problems based on tree structures.
20) List out the disadvantages of recursion.
 It is usually slower due to the overhead of maintaining the stack.
 It usually uses more memory for the stack.
21) What is a module? give example.
A Module is a file containing Python definitions and statements. The file name is the
module name with the suffix .py appended.
Example:
import math
import string
import DateTime

22) What is string? Give example.


A sequence of character enclosing within quotes. Python treats single quotes the same
as double quotes.

Creating strings is as simple as assigning a value to a variable.


Example:
var1 = 'Hello World!'
(or)
var1 = "Hello World!"

23) List out some escape sequence in python.

Description
notation

\a Bell or alert

\b Backspace

\cx Control-x

\C-x Control-x

Unit III 62
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

Description
notation

\e Escape

\f Formfeed

\M-\C-x Meta-Control-x

\n Newline

\nnn Octal notation, where n is in the range 0.7

\r Carriage return

\s Space

\t Tab

\v Vertical tab

\x Character x

\xnn Hexadecimal notation, where n is in the range 0.9, a.f, or


A.F
24) How will you slice the given string in python?
The slice s[start:end] is the elements beginning at start and extending up to but not
including end. (Or) piece of string
Example:
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
25) Is strings are immutable in python?
Yes, strings are immutable, which means cannot change an existing string. The best
you can do is creating a new string that is a variation on the original.
Example:
sample = "Hello, world!"
sample1 = 'J' + greeting[1:]
print(sample1)
print(sample) # same as it was

Output
Jello, world!
Hello, world!
26) List out some important string methods.

SN Methods with Description

1 capitalize()- Capitalizes first letter of string

Unit III 63
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

2 isalnum()- Returns true if string has at least 1 character and all characters are
alphanumeric and false otherwise.

3 isalpha()- Returns true if string has at least 1 character and all characters are
alphabetic and false otherwise.

4 isdigit()- Returns true if string contains only digits and false otherwise.

5 islower()- Returns true if string has at least 1 cased character and all cased
characters are in lowercase and false otherwise.

6 isnumeric()- Returns true if a unicode string contains only numeric characters and
false otherwise.

7 isspace()- Returns true if string contains only whitespace characters and false
otherwise.

27) Present the flow of execution for a while statement. [AU – Jan 2019]
Step 1: Evaluate the condition, yielding true or false.
Step 2: If the condition is true, execute the body and then go back to step 1.
Step 3: If the condition is false, exit from the block of looping.

28) Is array act as major role in python? Justify.


No, One of the most fundamental data structures in any language is the array. Python
doesn't have a native array data structure, but it has the list which is much more general
and can be used as a multidimensional array quite easily.
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.

PART – B
1) EXPLAIN THE BRANCHING STATEMENTS IN PYTHON WITH RELEVANT SYNTAX AND
EXAMPLE.
(or)
LIST THE THREE TYPES OF CONDITIONAL STEMENTS AND EXPLAIN THEM. [AU – Jan 2019]
The execution of the program taking action according to the conditions.
This concept is also known as
 Conditional statements or

Unit III 64
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

 Branching statements
This technique is somewhat differ from normal program. The sequence of the control
flow may differ from normal logical code. Decision structures evaluate multiple expressions
which produce TRUE or FALSE as outcome. You need to determine which action to take and
which statements to execute if outcome is TRUE or FALSE otherwise.

Types of Conditional statements


 if statements (conditional)
 if-else statements (alternative)
 if-elif-else (chained conditional) [AU – Jan 2018] – PART B
 Nested Conditional [AU – Jan 2018] – PART B
Let us see each decision making in briefly manner:
i) If Statement
It is similar to that of other languages. The if statement contains a logical expression
using which data is compared and a decision is made based on the result of the comparison.
Syntax
if expression:
statement(s)

If the boolean expression evaluates to TRUE, then the block of statement(s) inside the
if statement is executed. If boolean expression evaluates to FALSE, then the first set of code
after the end of the if statement(s) is executed.

Flowchart

Unit III 65
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

Example

sal=int(input(“Enter salary:”))
if sal>=10000:
sal=sal+2000
print(“salary=”,sal)
Output
Enter salary: 11000
Salary=13000

ii) If…else Statement


An else statement can be combined with an if statement. An else statement contains
the block of code (false block) that executes if the conditional expression in the if statement
resolves to 0 or a FALSE value.
The else statement is an optional statement and there could be at most only one else
statement following if.

Syntax
if expression:
statement(s)
else:
statement(s)

Flowchart

Example 1
sal=int(input(“Enter salary:”))
if sal>=10000:
sal=sal+2000
else:
sal=sal+1000
print(“salary=”,sal)
Output

Unit III Enter salary:8000 66


Salary=9000
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

iii) The elif Statement (chained conditional) [AU – Jan 2018] – PART B
The elif statement allows you to check multiple expressions for TRUE and execute a
block of code as soon as one of the conditions evaluates to TRUE. Similar to the else, the elif
statement is optional. However, unlike else, for which there can be at most one statement,
there can be an arbitrary number of elif statements following an if.
Syntax
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)

Core Python does not provide switch or case statements as in other languages, but
We can use if..elif...statements to simulate switch case as follows:
Flowchart
Example
a=int(input(“Enter A:”))
b=int(input(“Enter B:”))
c=int(input(“Enter C:”))
if a>b and a>c:
print(“A is Greater”)
elif b>c:
print(“B is Greater”)
else:
print(“C is Greater”)
Output
Enter A: 12
Enter B: 22
Enter C: 2
B is Greater

iv) Nested Conditionals [AU – Jan 2018] – PART B


One conditional can also be nested within another. (It is the same theme of composibility,
again!) We could have written the previous example as follows:
Syntax
if expression1:

Unit III 67
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

statement(s)
else:
if expression2:
statement(s)
else:
statement(s)

Flowchart
Example
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")

Output 1
Enter a number: 5
Positive number

2) EXPLAIN THE ITERATION IN PYTHON WITH RELEVANT SYNTAX AND EXAMPLE.


A loop statement allows us to execute a statement or group of statements multiple
times. Repeated execution of a set of statements is called iteration. Programming languages
provide various control structures that allow for more complicated execution paths. Python has
two statements for iteration they are given below
Types
i) while loop [AU – Jan 2018] – PART B
ii) for loop
iii) nested loop
Let us see one by one as follows

i) While Loop [AU – Jan 2018] – PART B


A while loop statement executes a block of statement again and again until the
condition will occur false (or) Repeats a statement or group of statements while a given
condition is TRUE.
It tests the condition before executing the loop body so this technique is known as
Entry controlled loop.
Syntax
while expression:
statement(s)

Unit III 68
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

Flowchart
Example
count = 0
while (count < 9):
print(“The count is:”, count)
count = count + 1
print("The End")
Output 1
The count is: 0
The count is: 1…..

The count is: 8


The End

ii) For Loop


Executes a sequence of statements multiple times and abbreviates the code that
manages the loop variable.
Syntax
for iterating_var in sequence:
statements(s)
Flowchart
Example
for letter in 'Python':
print(“Current Letter :”, letter)

fruits = ['banana', 'apple', 'mango']


for fruit in fruits: # Second Example
print(”Current fruit :”, fruit)

print("The End")

iii) Nested Loops


Python programming language allows using one loop inside another loop. Following section
shows few examples to illustrate the concept. You can use one or more loop inside any
another while, for or do...while loop.
Syntax - nested for loop
for iterating_var in sequence:
for iterating_var in sequence:

Unit III 69
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

statements(s)
statements(s)

Syntax - nested while loop


while expression:
while expression:
statement(s)
statement(s)

Note:
loop nesting is that you can put any type of loop inside of any other type of loop. For
example a for loop can be inside a while loop or vice versa.
Example
# Find the prime numbers from 2 to 100:
i=2
while(i < 100):
j=2
while(j <= (i/j)):
if not(i%j): break
j=j+1
if (j > i/j) :
print( i, " is prime")
i=i+1
print("The End")
Output
2 is prime
3 is prime
…..
89 is prime
97 is prime
The End

3) EXPLAIN ABOUT UNCONDITIONAL LOOPING STATEMENTS WITH RELEVANT


EXAMPLE.
Types:
 break statement [AU –JAN 2018] – PART B
 continue statement [AU –JAN 2018] – PART B
 pass statement
Let us see one by one as follows
i) Break Statement

Unit III 70
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

Terminates the loop statement and transfers execution to the statement immediately
following the loop. 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
Flowchart

Example
for letter in 'Python': # First Example
if letter == 'h':
break
print(“Current Letter :”, letter)
var = 10 # Second Example
while var > 0:
print(“Current variable value :”, var)
var = var -1
if var == 5:
break
print( "The End")
Output
Current Letter : P
Current Letter : y
Current Letter : t
Current variable value : 10
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6

Unit III 71
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

The End
ii) Continue Statement
It 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 continue statement can be used in both while and for loops.
Syntax
Continue
Flowchart

Example
for letter in 'Python': # First Example
if letter == 'h':
continue
print(”Current Letter :”, letter)
var = 10 # Second Example
while var > 0:
var = var -1
if var == 5:
continue
print(“Current variable value :”, var)
print("The End”)
Output
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6

Unit III 72
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

Current variable value : 4


Current variable value : 3
Current variable value : 2
Current variable value : 1
Current variable value : 0
The End
ii) 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. The pass is
also useful in places where your code will eventually go, but has not been written yet.
Syntax
pass
Example
for letter in 'Python':
if letter == 'h':
pass
print(“This is pass block”)
print(“Current Letter :”, letter)
print("The End")
Output
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
The End
4) BRIEFLY EXPLAIN ABOUT THE FUNCTION WITH CLEAR EXAMPLE.
(OR)
EXPLAIN THE SYNTAX AND STRUCTURE OF USER DEFINED FUNCTIONS IN PYTHON
WITH EXAMPLES. ALSO DISCUSS ABOUT PARAMETER PASSING IN FUNCTIONS.
[AU-JAN 19]
A function is a named container for a block of code that will execute for a specific task.
Functions help programmers to break the program into small manageable units or modules.
Functions may or may not take arguments and may or may not produce a result.
Advantages of using functions in Python
 Reusability
 Better readability
 Easy to debug and testing

Unit III 73
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

There are two types of functions:


(i) User-defined functions and
(ii) Library functions/PREDEFINED function,

(i) USER-DEFINED FUNCTION


ELEMENTS OF USER DEFINED FUNCTIONS
In python the user defined functions contain two elements. They are,
 Function definition
 Function call
Function definition

A function definition specifies the name of a new function and the sequence of
statements that run when the function is called.
Syntax

def functionname(parameters): // function


header
statement(s) // function body
….
The elements….of a function definition are,
1. Function return
header
2. Function body
Function Header
 The first line of a function definition is the function header.
 A function header starts with the keyword def, followed by the function name.
 The function name is followed by a comma-separated list of identifiers called formal
parameters, or simply parameters.
 The parameter list is ended with a colon ( : ).

Function Body
 The function body follows the function header.
 The function body contains one or more valid Python statements or the function's
instructions.
 Statements must have same indentation level, relative to the function header.
Example:
def greet(name):
print(“Hello,” + name + “. Good morning!”)
greet(‘saravanan’)

Output:
Hello, saravanan. Good morning

Unit III 74
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

Function Call
 A function call is a statement that runs a function.
 It consists of the function name followed by an argument list in parentheses.
 Once function is defined, it can be called from another function, program or even the
Python prompt.
 To call a function, simply type the function name with appropriate parameters.
d ef fu n ctio n N am e():
... .... ...
... ...
...
... .. .. ......
fu n ctio n N am e()
...
... .. .. ......
Program:
def swap(a,b):
a,b=b,a
print("After swap :")
print("First number = ",a)
print("second number = ",b)
a=int(input(“Enter the first number :"))
b=int(input("Enter the second number :"))
print("Before swap :")
print("First number = ",a)
print("second number = ",b)
swap(a,b)
Output:
Enter the first number:56
Enter the second number: 97
Before swap:
First number = 56
second number = 97
After swap:
First number = 97
second number = 56

(ii) BUILT-IN FUNCTIONS


 Built-in-functions are predefined functions. The Python interpreter has a number of
built-in functions and types, they are always available.
 The user can use the functions but cannot modify them. abs(), float(), format(),
help(), input() etc., are some of the built in functions in Python.

Example:

Unit III 75
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

>>>divmod (14,5)
(2,4) // 2 is quotient and 4 is remainder
>>>import math
>>>math.sqrt(4)
2.0
PARAMETER PASSING IN FUNCTION

5) EXPLAIN IN DETAIL ABOUT THE CONCEPT OF PARAMETERS & ARGUMENTS.

 Parameter: A name used inside a function to refer to the value passed as an


argument.
 Argument: A value provided to a function when the function is called. This value is
assigned to the corresponding parameter in the function.
 Some of the functions require arguments. For example, math.sin requires number as an
argument.
 Some functions take more than one argument. For example, math.pow takes two
arguments, the base and the exponent.
 Inside the function, the arguments are assigned to variables called parameters. Here is
a definition for a function that takes an argument:
Example
def print_twice(Hello):
print(Hello)
print(Hello)

6) ILLUSTRATIVE ARGUMENTS IN FUNCTION AND EXPLAIN THE TYPES OF


ARGUMENTS WITH NEAT EXAMPLES. [AU, Dec 2019]

ARGUMENTS

 The ‘arguments’ means parameter in a function.


 An argument is a way of passing data into a function when we don’t
know which variable or variables that data is going to be in.
 Arguments are defined inside the parentheses.
 And each argument is given a name, with a comma separating each.
 An argument acts as a temporary reference to the data that you
passed in while the function is running.
Example 1:
a = 15
b = 20
c=5
d = 10
def calcu(no1, no2):
total = no1 + no2

Unit III 76
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

print(total )
calc(a,b)
Output:
35
Explanation:
When we call the calc function, the two variables that we’ve passed in (a and b) are
put into the arguments no1 and no2.
This always happens in the same order you define the argument in other words, the first
variable you pass in is assigned to the first argument, the second to the second argument, and
so on for as many arguments as your function takes.
TYPES:

(i) Required arguments


(ii) Default Arguments [AU, Dec 2019]
(iii) Keyword arguments [AU, Dec 2019]
(iv) Variable-length arguments

(i) Required arguments


Required arguments are the arguments passed to a function in correct positional order.
Here, the number of arguments in the function call should match exactly with the function
definition.
Example:
def add(a,b):
c=a+b
print(c)
add(10,20) # Output is 30
add(20) # Error: add() missing 1 required positional argument: 'b'

(ii) Default arguments


Let, provide a default value to an argument by using the assignment operator (=).
Example:
def add(a,b=25):
c=a+b
print(c)
add(10,20) # Output is 30

add(10) # Error: add() missing 1 required positional argument: 'b'


Output:
30
35
(iii) Keyword arguments
 Python allows functions to be called using keyword arguments.
 We can mix positional arguments with keyword arguments during a function call.
 But we must keep in mind that keyword arguments must follow positional
arguments.

Unit III 77
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

Example:
def details(rno, name="arun",dept="CSE"):
print("Reg No=",rno,"Name=",name,"Department=",dept)

details(121)
details(122,name="Basha")
details(123,name="David",dept="Mech")

Output:
Reg No= 121 Name= arun Department= CSE
Reg No= 122 Name= Basha Department= CSE
Reg No= 123 Name= David Department= Mech
iv) Variable-length arguments
 The number of arguments that will be passed into a function is not known in advance.
 Python allows us to handle this kind of situation through function calls with arbitrary
number of arguments.
 Use an asterisk (*) before the parameter name to denote this kind of arguments.
Example:
def welcome(*names):
for i in names:
print(i)
welcome(“Arun”,”Basha”,”David”,”Zahir”)
Output:
Arun
Basha
David
Zahir

7) WITH CLEAR EXAMPLE, EXPLAIN RETURN STATEMENT IN FUNCTION. RETURNING


VALUES
The return statement is used to exit a function and go back to the place from where it
was called. Let see in example program.
Example 1: (without return statement)
a = 15
b = 20
c=5
d = 10
def calcu(no1, no2):
total = no1 + no2
print(total)
calcu(a, b)
calcu(c, d)
Output:
35
15

Example 2: (with return statement)


a = 15
b = 20
c=5
d = 10
def calcu(no1, no2):
total = no1 + no2

Unit III 78
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

return total

ans1 = calcu(a, b)
ans2 = calcu(c, d)
print( ans1)
print( ans2)

Output:
35
15
8) BRIEFLY EXPLAIN ABOUT FRUITFUL FUNCTIONS WITH EXAMPLES.
The user can not only pass a parameter value into a function, a function can also
produce a value.
Functions that return values are sometimes called fruitful functions. In many other
languages, a function that doesn’t return a value is called a procedure, but we will stick here
with the Python way of also calling it a function, or if we want to stress it, a non-
fruitful function.

The square function will take one number as a parameter and return the result of
squaring that number. Here is the black-box diagram with the Python code following.

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.
Example:
def add(a,b):
c=a+b
return c
x = int(input(“Enter Number1:”))
y = int(input(“Enter Number2:”))
z=add(x,y)
print(“Addition of two number is “,z)
Output:
Enter number1:12
Enter number2:25
Addition of two number is 37
In Python, any functions that return values, which we will call fruitful functions.
PARAMETERS IN FRUITFUL FUNCTIONS
Once a function is defined, it can be called from the main program or from
another function.

Unit III 79
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

Parameter is the “input data that is sent from function call to function definition”.
Types:
i) Actual parameters
ii) Formal parameters
Let see one by one as follows.
(i) Actual parameters : This parameter defined in the function call.

(ii) Formal parameters : This parameter defined as the part of function definition.
Example:
def add(a,b): a, b are formal arguments
c=a+b
return c

x = int(input(“Enter Number1:”))
y = int(input(“Enter Number2:”))
z=add(x,y) x, y are formal arguments
print(“Addition of two number is “,z)

9) GIVE CLEAR EXAMPLES FOR RETURN VALUES WITH EXPLANATION.


Example 1:
def area(radius):
b = 3.14159 * radius**2
return b

Explanation:
In the above program, which return area of circle with the statement of return b.
Before this statement, the variable b evaluated already.

Example 2:
def area(radius):
return 3.14159 * radius**2

Explanation:
In the above program, which is also return area of circle, but it have slightly differ
from example 1. Yes, the expression includes in the single statement of return statement.

10) WHAT IS FUNCTION COMPOSITION? EXPLAIN IN DETAILS WITH EXAMPLE.


Composition is the ability to take small building blocks (variables, expressions and
statements) and compose them (or) Call one function from within another function, this
technique is known as composition.

Unit III 80
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

Syntax:
def function1():
def function2():
-----------
return x

a=function1()
a

Example 1:
x = math.sin(degrees / 360.0 * 2 * math.pi)
Here the argument of a function can be any kind of expression, including arithmetic
operators and function calls.

Example 2:
def sam(x):
def add(y):
print(x+y)
return add

s=sam(5)
print("Answer",s(12))

Output:
17
None

11) BRIEFLY EXPLAIN ABOUT RECURSION WITH EXAMPLE PROGRAM.


A recursive definition is similar to a circular definition, i.e., “function call itself”
this is known as recursion.
Syntax:
def function_name(a):
------------
------------

function_name(b)
------------

Example:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)

Unit III 81
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

n=int(input(“Enter N:”))
f=factorial(n)
print(“The factorial of “,n,” is “,f)

Output:
Enter N:5
The factorial of 5 is 120

Explanation
Here is what the stack diagram looks like for this sequence of function calls:

12. EXPLAIN IN DETAILS ABOUT STRINGS WITH EXAMPLE.


Strings are amongst the most popular types in Python. We can create them simply by
enclosing characters in quotes. Python treats single quotes the same as double quotes.
Creating strings is as simple as assigning a value to a variable.
Example:
var1 = 'Hello World!' #Single quotes
var2 = "Python” #Double quotes
var2 = ’’’ Programming’’’ #Triple Single quotes
var3=”””Python Programming””” #Triple double quotes

ACCESSING VALUES IN STRINGS


 An individual character in a string is accessed using a subscript (index). The subscript
should always be an integer (positive or negative). A subscript starts from 0.
 Positive subscript helps in accessing the string from the beginning

Unit III 82
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

 Negative subscript helps in accessing the string from the end.


 From left to right, the first character of a string has the index 0
 From right end to left, the first character of a string is –1.
Example
String ‘Computer’ with a Positive or Negative Index Position Number

Program
>>>fruit='banana'
>>>fruit[0]
'b'
>>>fruit[1]
'a'
>>>fruit[4]
'n'
>>>fruit[6]

Traceback (most recent call last):


File "<pyshell#15>", line 1, in <module>
fruit[6]
IndexError: string index out of range

>>>fruit[5]
'a‘
>>>fruit[-5]
'a'
>>>fruit[-4]
'n'
>>>fruit[-2]
'n'
>>>fruit[-1]
'a'
>>>fruit[0]
'b'

UPDATING STRINGS
You can "update" an existing string by (re)assigning a variable to another string. The
new value can be related to its previous value or to a completely different string altogether.
Example:
var1 = 'Hello World!'
print("Updated String :- ", var1[:6] + 'Python')
When the above code is executed, it produces the following result:
Output:

Unit III 83
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

Updated String :- Hello Python

ESCAPE CHARACTERS
Following table is a list of escape or non-printable characters that can be represented
with backslash notation.
An escape character gets interpreted; in a single quoted as well as double quoted strings.

Backslash Hexadecimal Description


notation character

\a 0x07 Bell or alert

\b 0x08 Backspace

\cx Control-x

\C-x Control-x

\e 0x1b Escape

\f 0x0c Formfeed

\M-\C-x Meta-Control-x

\n 0x0a Newline

\nnn Octal notation, where n is in the range 0.7

\r 0x0d Carriage return

\s 0x20 Space

\t 0x09 Tab

\v 0x0b Vertical tab

\x Character x

\xnn Hexadecimal notation, where n is in the range 0.9, a.f, or A.F

13) LIST OUT THE STRING SPECIAL OPERATORS WITH EXAMPLES.


Assume string variable a holds 'Hello' and variable b holds 'Python',

Operato Description Example


r

+ Concatenation - Adds values on either side of the a + b will give HelloPython


operator

* Repetition - Creates new strings, concatenating a*2 will give -HelloHello


multiple copies of the same string

[] Slice - Gives the character from the given index a[1] will give e

Unit III 84
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

[:] Range Slice - Gives the characters from the given a[1:4] will give ell
range

in Membership - Returns true if a character exists in the H in a will give 1


given string

not in Membership - Returns true if a character does not M not in a will give 1
exist in the given string

r/R Raw String - Suppresses actual meaning of Escape print r'\n' prints \n and
characters. The syntax for raw strings is exactly the print R'\n'prints \n
same as for normal strings with the exception of the
raw string operator, the letter "r," which precedes the
quotation marks. The "r" can be lowercase (r) or
uppercase (R) and must be placed immediately
preceding the first quote mark.

14) LIST OUT THE STRING FORMATTING OPERATOR WITH EXAMPLE.


One of Python's coolest features is the string format operator %. This operator is
unique to strings and makes up for the pack of having functions from C's printf() family.
Example

Print("My name is %s and weight is %d kg!" % ('Zara', 21) )

Output

My name is Zara and weight is 21 kg!

Here is the list of complete set of symbols which can be used along with % −

Format Symbol Conversion

%c character

%s string conversion via str() prior to formatting

%i signed decimal integer

%d signed decimal integer

%u unsigned decimal integer

%o octal integer

%x hexadecimal integer (lowercase letters)

%X hexadecimal integer (UPPERcase letters)

%e exponential notation (with lowercase 'e')

%E exponential notation (with UPPERcase 'E')

%f floating point real number

Unit III 85
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

%g the shorter of %f and %e

%G the shorter of %f and %E

Other supported symbols and functionality are listed in the following table

Symbol Functionality

* argument specifies width or precision

- left justification

+ display the sign

<sp> leave a blank space before a positive number

# add the octal leading zero ( '0' ) or hexadecimal leading '0x' or


'0X', depending on whether 'x' or 'X' were used.

0 pad from left with zeros (instead of spaces)

% '%%' leaves you with a single literal '%'

(var) mapping variable (dictionary arguments)

m.n. m is the minimum total width and n is the number of digits to


display after the decimal point (if appl.)
15) DISCUSS BRIEFLY ABOUT STRING SLICES WITH EXAMPLES.
 A segment of a string is called a slice. Selecting a slice is similar to selecting a
character.
 Subsets of strings can be taken using the slice operator with two indices in square
brackets separated by a colon ([ ] and [m:n]).
 The operator [m:n] returns the part of the string from the mth character to
the nth character, including the first but excluding the last.
Example:
>>>a='Python Programming‘
>>>a[0:5]
'Pytho‘
>>>a[:5]
'Pytho‘
>>>a[5:]
'n Programming‘
>>>a[5:10]
'n Pro‘
>>>a[:]
'Python Programming‘
It is a neat truism of slices that for any index n, a[:n] + a[n:] == a. This works even for
n negative or out of bounds. Or put another way a[:n] and a[n:] always partition the string into

Unit III 86
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

two string parts, conserving all the characters. As we'll see in the list section later, slices work
with lists too.

16) LIST OUT THE STRING FUNCTIONS AND METHODS WITH EXAMPLES.
Python includes the following built-in methods to manipulate strings.

SN Methods with Description

1 capitalize() Capitalizes first letter of string

2 center(width, fillchar) Returns a space-padded string with the original string


centered to a total of width columns.

3 count(str, beg= 0,end=len(string)) Counts how many times str occurs in string or
in a substring of string if starting index beg and ending index end are given.

4 decode(encoding='UTF-8',errors='strict') Decodes the string using the codec


registered for encoding. encoding defaults to the default string encoding.

5 encode(encoding='UTF-8',errors='strict') Returns encoded string version of


string; on error, default is to raise a ValueError unless errors is given with 'ignore' or
'replace'.

6 endswith(suffix, beg=0, end=len(string)) Determines if string or a substring of


string (if starting index beg and ending index end are given) ends with suffix; returns
true if so and false otherwise.

7 expandtabs(tabsize=8) Expands tabs in string to multiple spaces; defaults to 8


spaces per tab if tabsize not provided.

8 find(str, beg=0 end=len(string)) Determine if str occurs in string or in a


substring of string if starting index beg and ending index end are given returns index
if found and -1 otherwise.

9 index(str, beg=0, end=len(string)) Same as find(), but raises an exception if str


not found.

10 isalnum() Returns true if string has at least 1 character and all characters are
alphanumeric and false otherwise.

11 isalpha() Returns true if string has at least 1 character and all characters are
alphabetic and false otherwise.

12 isdigit() Returns true if string contains only digits and false otherwise.

13 islower() Returns true if string has at least 1 cased character and all cased
characters are in lowercase and false otherwise.

14 isnumeric() Returns true if a unicode string contains only numeric characters and
false otherwise.

15 isspace() Returns true if string contains only whitespace characters and false
otherwise.

16 istitle() Returns true if string is properly "titlecased" and false otherwise.

17 isupper() Returns true if string has at least one cased character and all cased

Unit III 87
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

characters are in uppercase and false otherwise.

18 join(seq) Merges (concatenates) the string representations of elements in sequence


seq into a string, with separator string.

19 len(string) Returns the length of the string

20 ljust(width[, fillchar]) Returns a space-padded string with the original string left-
justified to a total of width columns.

21 lower() Converts all uppercase letters in string to lowercase.

22 lstrip() Removes all leading whitespace in string.

23 maketrans() Returns a translation table to be used in translate function.

24 max(str) Returns the max alphabetical character from the string str.

25 min(str) Returns the min alphabetical character from the string str.

26 replace(old, new [, max]) Replaces all occurrences of old in string with new or at
most max occurrences if max given.

27 rfind(str, beg=0,end=len(string)) Same as find(), but search backwards in string.

28 rindex( str, beg=0, end=len(string)) Same as index(), but search backwards in


string.

29 rjust(width,[, fillchar])Returns a space-padded string with the original string right-


justified to a total of width columns.

30 rstrip()Removes all trailing whitespace of string.

31 split(str="", num=string.count(str)) Splits string according to delimiter str (space


if not provided) and returns list of substrings; split into at most num substrings if
given.

32 splitlines( num=string.count('\n')) Splits string at all (or num) NEWLINEs and


returns a list of each line with NEWLINEs removed.

33 startswith(str, beg=0,end=len(string)) Determines if string or a substring of


string (if starting index beg and ending index end are given) starts with substring str;
returns true if so and false otherwise.

34 strip([chars]) Performs both lstrip() and rstrip() on string

35 swapcase() - Inverts case for all letters in string.

36 title() Returns "titlecased" version of string, that is, all words begin with uppercase
and the rest are lowercase.

37 translate(table, deletechars="") Translates string according to translation table


str(256 chars), removing those in the del string.

38 upper() Converts lowercase letters in string to uppercase.

Unit III 88
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

17) BRIEFLY DISCUSS ABOUT STRING MODULE WITH RELEVANT EXAMPLE.


This module contains a number of functions to process standard Python strings. In
recent versions, most functions are available as string methods as well.
Example: Using the string module
import string
text = "python programming"
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
split = ['Monty', "Python's", 'Flying', 'Circus']
join = Monty+Python's+Flying+Circus
replace = Monty Java's Flying Circus
find = 6 -1
count = 3
Example: Using string methods instead of string module functions (Python 1.6 and
later)
text = "Monty Python's Flying Circus"
print("upper", "=>", text.upper())
print("lower", "=>", text.lower())
print("split", "=>", text.split())
print("join", "=>", "+".join(text.split()))
print("replace", "=>", text.replace("Python", "Perl"))
print("find", "=>", text.find("Python"), text.find("Perl"))
print("count", "=>", text.count("n"))
Output
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 Perl's Flying Circus
find => 6 -1
count => 3
18) PYTHON STRINGS ARE IMMUTABLE. JUSTIFY WITH AN EXAMPLE.

Unit III 89
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

Yes, In python also, strings are immutable. That is, once defined a string, we cannot
modify a specific character in specific index.
It may be assumed to use [] operator on the left side of an augment, with the intention of
changing a character in a string.
Example:
sample=’Hello, world!’
sample[0]=’J’

The above code will make an error.


Reason:
The object in this case is the string and the item is the character tried to assign. For now,
an object is the same thing as a value, but we will refine that definition later. An item is one of
the values in a sequence. The reason for the error is that strings are immutable, which means
that existing string cannot be changed. The best option is to create a new string that is a
variation on the original.

Alternate idea to update string without affecting original:


sample=’Hello, world!’
sample1=’J’+sample[1:]
print(sample1)
Output:
Jello, world!

19) WHY WE NEED LIST INSTEAD OF ARRAY IN PYTHON? EXPLAIN IN DETAILS ABOUT
LISTS WITH EXAMPLE.
One of the most fundamental data structures in any language is the array. Python doesn't
have a native array data structure, but it has the list which is much more general and can be
used as a multidimensional array quite easily.
List basics
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:

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.

Unit III 90
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

Example
print(myList[2])
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.
Example
myList[2:5]
is a sublist from the third element to the fifth i.e. from myList[2] to myList[4].
Notice that the final element specified i.e. [5] is not included in the slice.
Also notice that you can leave out either of the start and end indexes and they will be
assumed to have their maximum possible value.
Example
myList[5:] is the list from List[5] to the end of the list and
myList[:5] is the list up to and not including myList[5] and
myList[:] is the entire list.
List slicing is more or less the same as string slicing except that you can modify a slice.
Example:
myList[0:2]=[0,1]
has the same effect as
myList[0]=0
myList[1]=1
Finally is it worth knowing that the list you assign to a slice doesn't have to be the
same size as the slice - it simply replaces it even if it is a different size.
Basic array operations
So far so good, and it looks as if using a list is as easy as using an array. The first thing
that we tend to need to do is to scan through an array and examine values.
Example
To find the maximum value (forgetting for a moment that there is a built-in max
function)
m=0
for e in myList:
if m<e:
m=e
This uses the for...in construct to scan through each item in the list. This is a very useful way
to access the elements of an array but it isn't the one that most programmers will be familiar
with. In most cases arrays are accessed by index and you can do this in Python:
m=0
for i in range(len(myList)):
if m<myList[i]:
m=myList[i]

Unit III 91
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

Notice that we are now using range to generate the sequence 0,1, and so on up to the length
of myList.
Let to admit that there is a lot to be said for the simplicity of the non-index version of
the for loop but in many cases the index of the entry is needed. There is the option of using
the index method to discover the index of an element but this has its problems.
Example
If you wanted to return not the maximum element but its index position in the list you
could use:
m=0
mi=0
for i in range(len(myList)):
if m<myList[i]:
m=myList[i]
mi=i
Also use the non-indexed loop and the index method:
m=0
for e in myList:
if m<e:
m=e
mi=myList.index(m)
print(mi)
The only problem is that index(m) returns the index of m in the list or an error if m isn't in the
list. There is also the slight problem that behind the scenes it is clear that index is performing
another scan of the entire list.
Two dimensions
It has to be said that one-dimensional arrays are fairly easy - it is when we reach two or
more dimensions that mistakes are easy to make. For a programmer moving to Python the
problem is that there are no explicit provisions for multidimensional arrays. As a list can
contain any type of data there is no need to create a special two-dimensional data structure.
All you have to do is store lists within lists - after all what is a two-dimensional array but a one-
dimensional array of rows.
In Python a 2x2 array is [[1,2],[3,4]] with the list [1,2] representing the first row and the
list [3,4] representing the second row. You can use slicing to index the array in the usual way.
Example
myArray=[[1,2],[3,4]]
then
myArray[0] is the list [1,2] and
myArray[0][1]

is [1,2][1], i.e. 2.

Unit III 92
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

As long as you build your arrays as nested lists in the way described then you can use
slicing in the same way as you would array indexing. That is:
myArray[i][j]
is the i,jth element of the array.
Example
To do something with each element in myArray you might write:

for i in range(len(myArray)):
for j in range(len(myArray[i])):
print(myArray[i][j])

Where len(myArray) us used to get the number of rows and len(myArray[i])) to get the
number of elements in a row. Notice that there is no need for all of the rows to have the same
number of elements, but if you are using a list as an array this is an assumption you need to
enforce.

20) WRITE A PYTHON PROGRAM TO FIND THE FACTORIAL OF A GIVEN NUMBERS


WITHOUT RECURSION AND WITH RECURSION. [AU – Jan 2018]

Program 1
#Without recursion
n=int(input(“Enter N:”))
fact=1
i=1
while i<=n:
fact=fact * i
i=i+1
print(“The factorial is “,fact)
Output:
Enter N:5
The factorial is 120

Program 2
#With recursion
def fact(n):
if n ==1:
return 1
else:
return n*fact(n-1)

n=int(input(“Enter N:”))

Unit III 93
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

f=fact(n)

print(“The factorial is “,f)


Output:
Enter N:5
The factorial is 120
21) WRITE A PYTHON PROGRAM TO CALCULATE SQUARE ROOT
# Python Program - Find Square Root of a Number without looping
print("Square Root Program")
num = input("Enter a number: ")
number = float(num)
number_sqrt = number ** 0.5
print("Square Root of %0.2f is %0.2f" %(number, number_sqrt))

22) WRITE A PYTHON PROGRAM TO FIND EXPONENTIATION


n= int(input ("enter number : ") )
e= int(input ("enter exponent : ") )
r=1 i=1
while (i<=e):
r=n*r
i=i+1
print (r)
Output
Enter number : 3
Enter exponent : 3
27
23) WRITE A PYTHON PROGRAM TO CALCULATE GCD
n1=int(input("Enter the first number: "))
n2=int(input("Enter the second number: "))
i=1
while (i <= n1 and i <= n2):
if(n1%i==0 and n2%i==0):
gcd = i;
i=i+1
print("GCD of given numbers is :", gcd)

Output
Case 1:
Enter first number:5
Enter second number:15
GCD is: 5

Unit III 94
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

Case 2:
Enter first number:30
Enter second number:12
GCD is: 6

24) WRITE A PYTHON PROGRAM TO CALCULATE SUM THE ARRAYS OF NUMBERS


def listsum(numList):
if len(numList) == 1:
return numList[0]
else:
return numList[0] + listsum(numList[1:])

print(listsum([1,3,5,7,9]))

OUTPUT
25

25) WRITE A PYTHON PROGRAM TO SEARCH A REQUIRED NUMBER IN SET OF


NUMBERS USING THE CONCEPT OF LINEAR SEARCH. [AU – JAN 2018]
n = int(input("Enter N:")) x = []
i=1
while i <= n:
y = int(input("Enter value:")) x.append(y)
i=i+1
key = int(input("Enter searching element:"))
i=0
found = 0

while i < n:
if key == x[i]:
found = 1

b
r

Unit III 95
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

e
a
k
i=i+1

if found == 1:
print("Searching element is found")
else:
print("Searching element is NOT found")

OUTPUT
Enter N:5
Enter value:12
Enter value:13
Enter value:14
Enter value:2
Enter value:3
Enter searching element:4
Searching element is NOT found

26) WRITE A PYTHON PROGRAM TO SEARCH A REQUIRED NUMBER IN SET OF


NUMBERS USING THE CONCEPT OF BINARY SEARCH. [AU – Jan 2019]
n = int(input("Enter N:"))
x = []
i=0
while i < n:
y = int(input("Enter value:"))
x.append(y)
i=i+1
key = int(input("Enter Searching element"))
first = 0
last = n - 1
found = 0
while( first<=last and not found):
mid = (first + last)//2
if x[mid] == key :
found = 1
else:
if key < x[mid]:
last = mid - 1
else:

Unit III 96
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

first = mid + 1
if found == 1:
print("Searching element is found")
else:
print("Searching element is NOT found")
OUTPUT
Enter N:5
Enter value:12
Enter value:13
Enter value:14
Enter value:2
Enter value:3
Enter searching element:3
Searching element is found

27) WRITE A PYTHON PROGRAM TO GENERATE FIRST ‘N’ FIBONACCI NUMBERS.


[AU-JAN 2018]
Program:
n=int(input(“Enter N:”))
a=0
b=1
i=2
print(a)
print(b)
while i<n:
c=a+b
print(c)
a=b
b=c
i=i+1
Output:
Enter N: 5
0
1
1
2
3

Unit III 97
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)

“Successful people do
what failure people are
not willing to do”

Unit III 98

You might also like