Unit 3 Q A
Unit 3 Q A
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)
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
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
\r Carriage return
\s Space
\t Tab
\v Vertical tab
\x Character x
Output
Jello, world!
Hello, world!
26) List out some important string methods.
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.
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.
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
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
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
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
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…..
print("The End")
Unit III 69
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)
statements(s)
statements(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
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)
Unit III 73
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)
A function definition specifies the name of a new function and the sequence of
statements that run when the function is called.
Syntax
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
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
ARGUMENTS
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:
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
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.
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)
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.
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
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:
Unit III 82
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)
Program
>>>fruit='banana'
>>>fruit[0]
'b'
>>>fruit[1]
'a'
>>>fruit[4]
'n'
>>>fruit[6]
>>>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)
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.
\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
\s 0x20 Space
\t 0x09 Tab
\x Character x
[] 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
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.
Output
Here is the list of complete set of symbols which can be used along with % −
%c character
%o octal integer
Unit III 85
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)
Other supported symbols and functionality are listed in the following table
Symbol Functionality
- left justification
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.
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.
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.
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)
20 ljust(width[, fillchar]) Returns a space-padded string with the original string left-
justified to a total of width columns.
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.
36 title() Returns "titlecased" version of string, that is, all words begin with uppercase
and the rest are lowercase.
Unit III 88
Mailam Engineering College GE3151 - Problem Solving and Python Programming (2021-REG)
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’
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.
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)
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
print(listsum([1,3,5,7,9]))
OUTPUT
25
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
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
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