Cat 2 Question Bank With All Part PDF
Cat 2 Question Bank With All Part PDF
Cat 2 Question Bank With All Part PDF
www.Vidyarthiplus.com
9 string = "PYTHON" P, Y, T, H, O, N,
for i in string:
print (i, end=", ")
www.Vidyarthiplus.com
Department of Computer Science and Engineering, REC Page |1
GE17151-Problem Solving and Python Programming -
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Department of Computer Science and Engineering, REC Page |2
GE17151-Problem Solving and Python Programming -
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Department of Computer Science and Engineering, REC Page |3
GE17151-Problem Solving and Python Programming -
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Department of Computer Science and Engineering, REC Page |1
GE17151-Problem Solving and Python Programming -
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Department of Computer Science and Engineering, REC Page |2
GE17151-Problem Solving and Python Programming - CAT2 - QUESTION BANK
www.Vidyarthiplus.com
2. Write a python program to generate odd and even numbers using for
statement.
#To generate Even number
n=int(input("Enter n Value"))
for i in range(n,2):
print(i)
i=0 Answer:
s=0 s=0
while (i<=50): for i in range(51):
if (i%7==0): if(i%7==0):
s=s+i s=s+i
i=i+7 i=i+7
print(s) print(s)
The body of the loop should change the value of one or more variables so that the
condition becomes false eventually and the loop terminates. Otherwise the loop will
repeat forever, which is called an infinite loop.
Example.
i=1
while (i!=0):
i=i+1
print(i)
www.Vidyarthiplus.com
Department of Computer Science and Engineering, REC Page |1
GE17151-Problem Solving and Python Programming - CAT2 - QUESTION BANK
www.Vidyarthiplus.com
5. Write the syntax and draw the flow chart for “for” statement in Python.
Syntax
for variable in sequence:
body of the loop
Statement-x
6. Write a Python program to find the factorial of a given number using for loop.
Syntax
while(test-condition):
body of the loop
statement-x
Flowchart
The continue statement is used to skip the rest of the code inside a loop for the current
iteration only. Loop does not terminate but continues on with the next iteration.
For example we wish to print the squares of all the odd numbers below 10, which are
not multiples of 3, we would modify the for loop as follows.
www.Vidyarthiplus.com
Department of Computer Science and Engineering, REC Page |3
GE17151-Problem Solving and Python Programming - CAT2 - QUESTION BANK
www.Vidyarthiplus.com
10. Differentiate break and continue statements.
There is no limit on the number of statements that can appear in the body, but there
has
to be at least one. Occasionally, it is useful to have a body with no statements (usually
as a place keeper for code you haven‟t written yet). In that case, you can use the pass
statement, which does nothing.
if x < 0:
pass # TODO: need to handle negative values!
“pass” statement acts as a place holder for the block of code. It is equivalent to a null
operation. It literally does nothing. It can used as a place holder when the actual code
implementation for a particular block of code is not known yet but has to be filled up
later.
www.Vidyarthiplus.com
Department of Computer Science and Engineering, REC Page |4
GE17151-Problem Solving and Python Programming - CAT2 - QUESTION BANK
www.Vidyarthiplus.com
Part C
1. Develop a program in Python to find sum of the digits, reversal of the digits
and largest digit of a given integer number using while statement.
Output:
Enter the number : 861
The sum of the digits = 15
The reverse of the digits = 168
The largest digit = 8
www.Vidyarthiplus.com
Department of Computer Science and Engineering, REC Page |5
GE17151-Problem Solving and Python Programming - CAT2 - QUESTION BANK
www.Vidyarthiplus.com
3. Develop a python program to the sum of Fibonacci series using for
statement.
Output:
Enter the number of terms: 7
The fibonacci series is:
0 1 1 2 3 5 8
The sum of the series is: 20
www.Vidyarthiplus.com
Department of Computer Science and Engineering, REC Page |6
GE17151-Problem Solving and Python Programming - CAT2 - QUESTION BANK
www.Vidyarthiplus.com
UNIT III
PART –B
A string is a sequence of characters. You can access the characters one at a time with
the bracket operator
Calling the function generates a return value, which we usually assign to a variable or
use as part of an expression.
The example is area, which returns the area of a circle with the given radius:
def area(radius):
a = math.pi * radius**2
return a
In a fruitful function the return statement includes an expression. This statement
means:
“Return immediately from this function and use the following expression as a return
value.” The expression can be arbitrarily complicated, so we could have written this
function more concisely:
def area(radius):
return math.pi * radius**2
4. Write a Python script that takes input from the user and displays that
input back in upper and lower cases.
s = input("Enter the string : ")
print("String in upper case : ", s.upper())
print("String in lower case : ", s.lower())
www.Vidyarthiplus.com
Department of Computer Science and Engineering, REC Page |7
GE17151-Problem Solving and Python Programming - CAT2 - QUESTION BANK
www.Vidyarthiplus.com
5. Differentiate fruitful functions and void functions.
Some of the functions we have used, such as the math functions, return results;
for lack of a better name, we call them fruitful functions. Other functions, like
print_twice, perform an action but don‟t return a value. They are called void
functions.
When you call a fruitful function, you almost always want to do something with
the result;
for example, you might assign it to a variable or use it as part of an expression:
>>> x = math.cos(radians)
>>> golden = (math.sqrt(5) + 1) / 2
When you call a function in interactive mode, Python displays the result:
>>> math.sqrt(5)
2.2360679774997898
But in a script, if you call a fruitful function all by itself, the return value is lost
forever!
math.sqrt(5)
www.Vidyarthiplus.com
Department of Computer Science and Engineering, REC Page |8
GE17151-Problem Solving and Python Programming - CAT2 - QUESTION BANK
www.Vidyarthiplus.com
7. List the advantages of functions in Python.
It may not be clear why it is worth the trouble to divide a program into functions.
There are several reasons:
Creating a new function gives you an opportunity to name a group of
statements, which makes your program easier to read and debug.
Functions can make a program smaller by eliminating repetitive code. Later, if
you make a change, you only have to make it in one place.
Dividing a long program into functions allows you to debug the parts one at a
time and then assemble them into a working whole.
Well-designed functions are often useful for many programs. Once you write
and debug one, you can reuse it.
def countdown(n):
if n <= 0:
print(„rec‟)
else:
print(n)
countdown(n-1)
\" Print the next character as a double quote, not a string closer
\' print the next character as a single quote, not a sting closer
\n print a new line character (remember our print statements?)
\t print a tab character
\r print a carriage return(not used very often)
\$ print the next character as a dollar, not as part of a variable
\\ print the next character as a backslash, not an escape character
\n new line
www.Vidyarthiplus.com
Department of Computer Science and Engineering, REC Page |9
GE17151-Problem Solving and Python Programming - CAT2 - QUESTION BANK
www.Vidyarthiplus.com
10. What are keyword arguments? Give example.
Keyword arguments are related to the function calls. When you use keyword
arguments in a function call, the caller identifies the arguments by the parameter
name.
This allows you to skip arguments or place them out of order because the
Python interpreter is able to use the keywords provided to match the values with
parameters.
Example:
def printinfo(name, age):
print ("Name :", name)
print ("Age :", age)
printinfo(age = 18, name = "Raj")
Output:
Name : Raj
Age : 18
www.Vidyarthiplus.com
Department of Computer Science and Engineering, REC P a g e | 10
GE17151-Problem Solving and Python Programming - CAT2 - QUESTION BANK
www.Vidyarthiplus.com
12.Write a Python program to count the number of vowels in a string.
Output:
Name : Arun
Age : 20
Name : Babu
Age : 19
www.Vidyarthiplus.com
Department of Computer Science and Engineering, REC P a g e | 11
GE17151-Problem Solving and Python Programming - CAT2 - QUESTION BANK
www.Vidyarthiplus.com
15. What is the purpose of import statement? Give example.
16. Define String. Explain how to initialize string variable with suitable
example.
Strings are not like integers, floats, and booleans. A string is a sequence, which
means it is an ordered collection of other value.
Example:
www.Vidyarthiplus.com
Department of Computer Science and Engineering, REC P a g e | 12
GE17151-Problem Solving and Python Programming - CAT2 - QUESTION BANK
www.Vidyarthiplus.com
18. Write a Python program to count the number of digits, letters and
other characters in a string
s = input("Enter the string : ")
digits = 0
letters = 0
others = 0
for c in s:
if c.isdigit():
digits = digits + 1
elif c.isalpha():
letters = letters + 1
else:
others = others + 1
print("Digits : ", digits)
print("Letters : ", letters)
print("Other characters : ", others)
Output:
Enter the string : Thandalam - 602 105
Digits : 6
Letters : 9
Other characters : 4
19. Develop a Python program to using function to print all the letters from
word1 that also appear in word2.
Program:
def in_both(word1, word2):
for letter in word1:
if letter in word2:
print(letter)
a = input("Enter the first word : ")
b = input("Enter the second word : ")
in_both(a, b)
Output:
Enter the first word : apples
Enter the second word : oranges
a
e
s
www.Vidyarthiplus.com
Department of Computer Science and Engineering, REC P a g e | 13
GE17151-Problem Solving and Python Programming - CAT2 - QUESTION BANK
www.Vidyarthiplus.com
20. Develop a Python program to calculate the length of a string without
using a built-in function.
Program:
s = input("Enter the string : ")
count = 0
for i in s:
count = count + 1
print("Length of the string :", count)
Output:
Enter the string : Rajalakshmi
Length of the string : 11
www.Vidyarthiplus.com
Department of Computer Science and Engineering, REC P a g e | 14
GE17151-Problem Solving and Python Programming - CAT2 - QUESTION BANK
www.Vidyarthiplus.com
PART –C
It is legal for one function to call another; it is also legal for a function to call
itself. It may not be obvious why that is a good thing, but it turns out to be one
of the most magical things a program can do.
A function that calls itself is recursive; the process of executing it is called
recursion. If you looked up the definition of the factorial function, denoted with
the symbol!, you might get something like this:
Briefly explain the various string methods in Python with suitable example.
0! = 1
n! = n(n-1)!
This definition says that the factorial of 0 is 1, and the factorial of any other
value, n, is n multiplied by the factorial of n-1.
So 3! is 3 times 2!, which is 2 times 1!, which is 1 times 0!. Putting it all
together, 3! equals 3 times 2 times 1 times 1, which is 6.
If you can write a recursive definition of something, you can write a Python
program to evaluate it. The first step is to decide what the parameters should be.
In this case it should be clear
that factorial takes an integer:
def factorial(n):
If the argument happens to be 0, all we have to do is return 1:
def factorial(n):
if n == 0:
return 1
Otherwise, and this is the interesting part, we have to make a recursive call to
find the factorial of n-1 and then multiply it by n:
def factorial(n):
if n == 0:
return 1
else:
recurse = factorial(n-1)
result = n * recurse
www.Vidyarthiplus.com
Department of Computer Science and Engineering, REC P a g e | 15
GE17151-Problem Solving and Python Programming - CAT2 - QUESTION BANK
return result www.Vidyarthiplus.com
The flow of execution for this program is similar to the flow of countdown in
“Recursion”. If
we call factorial with the value 3:
Since 3 is not 0, we take the second branch and calculate the factorial of n-1...
Since 2 is not 0, we take the second branch and calculate the factorial of n-1...
Since 1 is not 0, we take the second branch and calculate the factorial of n-1...
Since 0 equals 0, we take the first branch and return 1 without making any more
recursive calls.
The return value, 1, is multiplied by n, which is 1, and the result is returned.
The return value, 1, is multiplied by n, which is 2, and the result is returned.
The return value (2) is multiplied by n, which is 3, and the result, 6, becomes
the return value of the function call that started the whole process.
Figure shows what the stack diagram looks like for this sequence of function
calls.
The return values are shown being passed back up the stack. In each frame, the
return value is the value of result, which is the product of n and recurse.In the
last frame, the local variables recurse and result do not exist, because the branch
that creates them does not run.
www.Vidyarthiplus.com
Department of Computer Science and Engineering, REC P a g e | 16
GE17151-Problem Solving and Python Programming - CAT2 - QUESTION BANK
www.Vidyarthiplus.com
2. Briefly explain the various string methods in Python with suitable
example.
str.capitalize()
Return a copy of the string with its first character capitalized and the rest
lowercased.
Example:
s = "python programming"
print(s.capitalize())
Output:
Python programming
str.count()
Return True if the string ends with the specified suffix, otherwise return False.
suffix can also be a tuple of suffixes to look for. With optional start, test
beginning at that position. With optional end, stop comparing at that position.
Example:
s = "python programming"
print(s.endswith("ing"))
print(s.endswith("ogy"))
Output:
True
False
www.Vidyarthiplus.com
Department of Computer Science and Engineering, REC P a g e | 17
GE17151-Problem Solving and Python Programming - CAT2 - QUESTION BANK
str.find() www.Vidyarthiplus.com
Return the lowest index in the string where substring sub is found within the
slice s[start:end]. Optional arguments start and end are interpreted as in slice
notation. Return
-1 if sub is not found. The find() method should be used only if you need to
know the position of sub.
Example:
s = "python programming"
print(s.find("on"))
print(s.find("va"))
Output:
4
-1
str.index()
Like find(), but raise ValueError when the substring is not found.
Example:
s = "python programming"
print(s.index("on"))
print(s.index("va"))
Output:
4
ValueError: substring not found
str.lower()
Return a copy of the string with all the cased characters [4] converted to
lowercase.
The lowercasing algorithm used is described in section 3.13 of the Unicode
Standard.
Example:
s = "python programming"
p = "PSPP"
t = "CSE Lab"
print(s.lower())
print(p.lower())
print(t.lower())
www.Vidyarthiplus.com
Department of Computer Science and Engineering, REC P a g e | 18
GE17151-Problem Solving and Python Programming - CAT2 - QUESTION BANK
Output: www.Vidyarthiplus.com
python programming
pspp
cse lab
str.replace()
Return a copy of the string with all occurrences of substring old replaced by
new. If the
optional argument count is given, only the first count occurrences are replaced.
Example:
s = "python programming"
print(s.replace("python", "java"))
Output:
java programming
str.startswith()
Return True if string starts with the prefix, otherwise return False. prefix can
also be a tuple
of prefixes to look for. With optional start, test string beginning at that position.
With
optional end, stop comparing string at that position.
Example:
s = "python programming"
print(s.startswith("py"))
print(s.startswith("ja"))
Output:
True
False
str.swapcase()
str.title()
Return a title cased version of the string where words start with an uppercase
character
and the remaining characters are lowercase.
Example:
s = "python programming"
p = "CSE Lab"
print(s.title())
print(p.title())
Output:
Python Programming
Cse Lab
str.upper()
Return a copy of the string with all the cased characters converted to uppercase.
Example:
s = "python programming"
p = "PSPP"
print(s.upper())
print(p.upper())
Output:
PYTHON PROGRAMMING
PSPP
www.Vidyarthiplus.com
Department of Computer Science and Engineering, REC P a g e | 20
GE17151-Problem Solving and Python Programming - CAT2 - QUESTION BANK
www.Vidyarthiplus.com
3. Discuss the different argument passing mechanism in Python with
suitable examples.
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 printme(s):
print(s)
printme()
To call the function printme(), you definitely need to pass one argument,
otherwise it gives a syntax error as follows: Traceback (most recent call last):
printme() TypeError: printme() missing 1 required positional argument: 's'
Keyword Arguments
Keyword arguments are related to the function calls. When you use keyword
arguments in a function call, the caller identifies the arguments by the parameter
name. This allows you to skip arguments or place them out of order because the
www.Vidyarthiplus.com
Department of Computer Science and Engineering, REC P a g e | 21
GE17151-Problem Solving and Python Programming - CAT2 - QUESTION BANK
www.Vidyarthiplus.com
Python interpreter is able to use the keywords provided to match the values with
parameters.
Example:
def printinfo(name, age):
print ("Name :", name)
print ("Age :", age)
printinfo(age = 19, name = "Arun")
Output:
Name : Arun
Age : 19
Note that the order of parameters does not matter. Python expects all the
keyword to be present towards the end.
Default Arguments
A default argument is an argument that assumes a default value if a value is not
provided in the function call for that argument. The following example gives an
idea on default arguments, it prints default age if it is not passed:
Example:
def printinfo(name, age = 19):
print ("Name :", name)
print ("Age :", age)
printinfo("Arun", 20)
printinfo("Babu")
Output:
Name : Arun
Age : 20
Name : Babu
Age : 19
Note that when defining a function all the argument with default values should
come at
www.Vidyarthiplus.com
Department of Computer Science and Engineering, REC P a g e | 22
GE17151-Problem Solving and Python Programming - CAT2 - QUESTION BANK
the end. www.Vidyarthiplus.com
Variable-length Arguments
You may need to process a function for more arguments than you specified
while defining the function. These arguments are called variable-length
arguments and are not named in the function definition, unlike required and
default arguments.
Syntax for a function with non-keyword variable arguments is given below:
def functionname([formal_args,] *var_args_tuple):
'''function_docstring'''
function_suite
return [expression]
An asterisk (*) is placed before the variable name that holds the values of all
non-keyword variable arguments. This tuple remains empty if no additional
arguments are specified during the
function call. Following is a simple example:
def printargs(*vartuple):
print("Arguments are :")
for i in vartuple:
print(i)
printargs(10, 20)
printargs(10, 20, 30)
Output:
Arguments are :
10
20
Arguments are :
10
20
30
www.Vidyarthiplus.com
Department of Computer Science and Engineering, REC P a g e | 23
GE17151-Problem Solving and Python Programming - CAT2 - QUESTION BANK
www.Vidyarthiplus.com
4. Explain the purpose of slicing string in Python with suitable example.
If you omit the first index (before the colon), the slice starts at the beginning of
the string. If you omit the second index, the slice goes to the end of the string:
>>> fruit = 'banana'
>>> fruit[:3]
'ban'
>>> fruit[3:]
'ana'
If the first index is greater than or equal to the second the result is an empty
string, represented by two quotation marks:
>>> fruit = 'banana'
>>> fruit[3:3]
''
An empty string contains no characters and has length 0, but other than that, it is
the same as any other string. Continuing this example, what do you think fruit[:]
means? Try it and see.
www.Vidyarthiplus.com
Department of Computer Science and Engineering, REC P a g e | 24
GE17151-Problem Solving and Python Programming - CAT2 - QUESTION BANK
www.Vidyarthiplus.com
5. Briefly explain the function definition and function calling in Python.
So far, we have only been using the functions that come with Python, but it is
also possible to add new functions. A function definition specifies the name of a
new function and the sequence of statements that run when the function is
called.
Syntax
def function_name(parameters):
"""docstring"""
statement(s)
Here is an example:
def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print("I sleep all night and I work all day.")
def is a keyword that indicates that this is a function definition. The name of the
function is print_lyrics. The rules for function names are the same as for
variable names: letters, numbers and underscore are legal, but the first character
can‟t be a number. You can‟t use a keyword as the name of a function, and you
should avoid having a variable and a function with the same name.
The empty parentheses after the name indicate that this function doesn‟t take
any arguments.
The first line of the function definition is called the header; the rest is called the
body. The header has to end with a colon and the body has to be indented. By
convention, indentation is always four spaces. The body can contain any
number of statements. The strings in the print statements are enclosed in double
quotes. Single quotes and double quotes do the same thing; most people use
single quotes except in cases like this where a single quote (which is also an
apostrophe) appears in the string.
All quotation marks (single and double) must be “straight quotes”, usually
located next to Enter on the keyboard. “Curly quotes”, like the ones in this
sentence, are not legal in Python.
If you type a function definition in interactive mode, the interpreter prints dots
(...) to let you know that the definition isn‟t complete:
www.Vidyarthiplus.com
Department of Computer Science and Engineering, REC P a g e | 25
GE17151-Problem Solving and Python Programming - CAT2 - QUESTION BANK
www.Vidyarthiplus.com
>>> def print_lyrics():
... print("I'm a lumberjack, and I'm okay.")
... print("I sleep all night and I work all day.")
...
To end the function, you have to enter an empty line.
Defining a function creates a function object, which has type function:
>>> print(print_lyrics)
<function print_lyrics at 0x000001D41AD82EA0>
>>> type(print_lyrics)
<class 'function'>
The syntax for calling the new function is the same as for built-in functions:
>>> print_lyrics()
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
Once you have defined a function, you can use it inside another function. For
example, to repeat the previous refrain, we could write a function called
repeat_lyrics:
def repeat_lyrics():
print_lyrics()
print_lyrics()
And then call repeat_lyrics:
>>> repeat_lyrics()
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
www.Vidyarthiplus.com
Department of Computer Science and Engineering, REC P a g e | 26
GE17151-Problem Solving and Python Programming - CAT2 - QUESTION BANK
www.Vidyarthiplus.com
6. Explain the features of “in” operator for string in Python with suitable
example.
The word in is a boolean operator that takes two strings and returns True if the
first appears as a substring in the second:
>>> 'a' in 'banana'
True
>>> 'seed' in 'banana'
False
For example, the following function prints all the letters from word1 that also
appear in word2:
def in_both(word1, word2):
for letter in word1:
if letter in word2:
print(letter)
With well-chosen variable names, Python sometimes reads like English. You
could read thisloop, “for (each) letter in (the first) word, if (the) letter (appears)
in (the second) word, print (the) letter.”
Here‟s what you get if you compare apples and oranges:
>>> in_both('apples', 'oranges')
a
e
s
www.Vidyarthiplus.com
Department of Computer Science and Engineering, REC P a g e | 27