Cat 2 Question Bank With All Part PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 32

GE17151-Problem Solving and Python Programming -

www.Vidyarthiplus.com

RAJALAKSHMI ENGINEERING COLLEGE


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
GE17151 – PROBLEM SOLVING AND PYTHON PROGRAMMING
LOOPING AND FUNCTION
Part – A
S.NO QUESTION ANSWER
1 n=1 1
while n <= 2: 2
print(n)
n=n+1 END
print('END')
2 for i in range(1,4,2): Welcome
print('Welcome') Welcome
3 for i in range(3): Welcome
print('Welcome') Welcome
Welcome
4 i=1 1
while True: 2
if i%5 == 0:
break
3
print(i) 4
i= i+1
5 i=1 3
while (i<5): exit
if i==3:
print(i)
i= i+1
else:
print('exit')
6 Updating a variable by adding 1 is called an _____; subtracting 1 is Increment,
called a _____. decrement
7 _ statement acts as a place holder for the block of code. Colon
8 z=1 5
while z<5:
if z%5==0:
break
z=z+2
print(z)

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

S.NO QUESTION ANSWER


10 count=5 2
for x in range(0,10):
count=count-1
if x==2:
break
print(count)
11 _____ statement is used to break out of the innermost loop. break
12 In a computer program, repetition is also called _____. Looping
13 By default, while is: c
a. condition control statement
b. Loop control Statement
c. Both a and b
d. None of the above
14 The continue statement is a keyword. a.True
a. True
b. False
15 The break statement is a keyword. a.True
a. True
b. False
16 i=1 64
for x in range (1,4):
for y in range(1,3):
i=i+(i*1)
print(i)
17 ---statement is used to skip execution of the rest of the loop on this continue
iteration and continue to the end of this iteration.

18 The loop will repeat forever, is called an _____. Indefinite loop

19 >>> round (5.4432) 5


20 >>>max(1, 3, 2, 5, 4) 5
>>>min (1, 3, 2, 5, 4) 1
21 def firstfunction(): I Love Python
print('I Love Python') I Love Python
for i in range(3):
I Love Python
firstfunction()
22 def square(x): 25
return x * x
x = square(5)
print(x)

www.Vidyarthiplus.com
Department of Computer Science and Engineering, REC Page |2
GE17151-Problem Solving and Python Programming -
www.Vidyarthiplus.com

S.NO QUESTION ANSWER


23 i=0 0
def change(i):
i=i+1
return i
change(10)
print(i)
24 >>> round(5.5676, 3) 5.568
25 def say(message, times=1): Hello
print(message * times) WorldWorldWorldWorldWorld
say('Hello')
say('World', 5)
26 a = 10 10
b = 20 56
def change():
global b
a = 45
b = 56
change()
print(a)
print(b)
27 Before we can use the functions in a module, we Import
have to import it with an _____ statement
28 >>> import math 5
>>> math.sqrt(25)
29 >>>pow(2,2) 4
30 def change(i = 1, j = 2): 32
i=i+j
j=j+1
print(i, j)
change(j = 1, i = 2)
31 To ensure that a function is defined before its Flow of execution.
first use, you have to know the order
statements run in, which is called the----------
32 Code that appears after a return statement, or Dead code.
any other place the flow of execution can never
reach, is called-------

www.Vidyarthiplus.com
Department of Computer Science and Engineering, REC Page |3
GE17151-Problem Solving and Python Programming -
www.Vidyarthiplus.com

RAJALAKSHMI ENGINEERING COLLEGE


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
GE17151 – PROBLEM SOLVING AND PYTHON PROGRAMMING
STRINGS
Part – A
S.NO QUESTION ANSWER
What is the output of the following? 'a'
>>> fruit = 'banana'
1
>>> letter = fruit[1]
>>> letter
What is the output of the following? 'a'
>>> fruit = 'banana'
2
>>> letter = fruit[3]
>>> letter
s1=(" Welcome to java programming") Welcome to java programming
s2=s1.replace("java","python") Welcome to python programming
3
print(s1)
print(s2)
What will be the output of the RE
following program?
4 str1="REC"
str2=str1[:-1]
print(str2)
What will be the output of the RE
following program?
5 str1="REC"
str2= str2=str1[:2]
print(str2)
6 A string is a sequence of _____. characters
_____ is a built-in function that returns len
7
the number of characters in a string.
In slicing, if the first index is greater empty string
8 than or equal to the second the result is two quotation marks
an _____, represented by _____.
s1=("python programming") Error
9 s1[0]="J"
print(s1)
The first line of the function definition header
10 is called the _____; the rest is called the body
_____.

www.Vidyarthiplus.com
Department of Computer Science and Engineering, REC Page |1
GE17151-Problem Solving and Python Programming -
www.Vidyarthiplus.com

S.NO QUESTION ANSWER


>>> fruit = 'banana' 6
11
>>> len(fruit)
12 A segment of a string is called a ___ Slice
The word _____ is a boolean operator that takes in
13 two strings and returns True if the first appears
as a substring in the second
str1 = 'Hello' HelloWorld
14 str2 ='World!'
print(str1+str2)
Str1 ='World!' World!World!World!
15
print(str1*3)
>>> fruit = 'banana' 'a'
>>> length = len(fruit)
16 >>> last = fruit[length-1]
>>> last
>>> fruit = 'banana' ‘n’
>>> length = len(fruit)
17
>>> last=fruit[length-4]
>>> last
In String, the expression in brackets is called an index
18
_____.
>>> str='python' False
19
>>> 'a' in str
20 >>> "abcd"[2:] 'cd'

www.Vidyarthiplus.com
Department of Computer Science and Engineering, REC Page |2
GE17151-Problem Solving and Python Programming - CAT2 - QUESTION BANK
www.Vidyarthiplus.com

RAJALAKSHMI ENGINEERING COLLEGE


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
GE17151 – PROBLEM SOLVING AND PYTHON PROGRAMMING
CAT 2-QUESTION BANK
UNIT - II
Part – B
1. Define iteration.
Iteration - is the ability to run a block of statements repeatedly.

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)

#To generate odd number


n=int(input("Enter n Value"))
for i in range(1,n,2):
print(i)

3. Convert the following while loop into for loop.

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)

4. What is an infinite loop? Give example.

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.

n = int(input("Enter the number : "))


fact = 1
for i in range(1, n + 1):
fact = fact * i
print("The factorial of", n, "is", fact)

7. What is nested loop? Give example.


Nesting is defined as the placing of one loop inside the body of another loop.
When we nest two loops, the outer loop takes control of the number of complete
repetitions of the inner loop.
Example
for i in range(1, 6):
for j in range(1, i + 1):
print(j, end = " ")
print()
Output:
1
12
123
1234
www.Vidyarthiplus.com
Department of Computer Science and Engineering, REC Page |2
GE17151-Problem Solving and Python Programming - CAT2 - QUESTION BANK
www.Vidyarthiplus.com
8. Write the syntax and draw the flow chart for while statement in Python.

Syntax
while(test-condition):
body of the loop
statement-x

Flowchart

9. What is the purpose of continue statement? Give example.

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.

for n in range(1, 10, 2):


if n % 3 == 0:
continue
print (n * n)

Produces the output


1
25
49
12345

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.

break STATEMENT continue STATEMENT


Sometimes you don‟t know it‟s time to continue is used to skip execution of
end a loop until you get halfway the rest of the loop on this iteration and
continue to the end of this iteration.
through the body. In that case you can
For example we wish to print the
use the break statement to jump out of squares of all the odd numbers below
the loop. break is used to break out of 10, which are not multiples of 3, we
the innermost loop. would modify the for loop as follows.
For example,
i=1 for n in range(1, 10, 2):
while True: if n % 3 == 0:
print (i * i) continue
i=i+2 print (n * n)
if(i > 10): Produces the output
break 1
produces the output 25
1 49
9
25
81
49
11. What is the purpose of pass statement in Python? Give example.

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.

n = int(input("Enter the number : "))


s=0
rev = 0
large = 0
while(n > 0):
rem = n % 10
s = s + rem
rev = rem + (rev * 10)
if(rem > large):
large = rem
n = n // 10
print("The sum of the digits =", s)
print("The reverse of the digits =", rev)
print("The largest digit =", large)

Output:
Enter the number : 861
The sum of the digits = 15
The reverse of the digits = 168
The largest digit = 8

2. Develop a program in Python to generate the Armstrong numbers from 1-1000

print("The Armstrong numbers from 1 to 1000 are :")


for i in range(1, 1001):
n=i
s=0
while(n > 0):
rem = n % 10
s = s + (rem ** 3)
n = n // 10
if(s == i):
print(i, end = "\t")
Output:
The Armstrong numbers from 1 to 1000 are:
1 153 370 371 407

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.

n = int(input("Enter the number of terms : "))


a = -1
b=1
s=0
print("The fibonacci series is :")
for i in range(1, n + 1):
c=a+b
print(c, end = "\t")
s=s+c
a=b
b=c
print("\nThe sum of the series is :", s)

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

1. Write the syntax for defining the function.


Syntax
def function_name(parameters):
"""docstring"""
statement(s)

2. How to access string variable? Give example.

A string is a sequence of characters. You can access the characters one at a time with
the bracket operator

>>> fruit = 'REC'


>>> letter = fruit[1]
The second statement selects character number 1 from fruit and assigns it to letter.
>>> letter
E
3. What is the purpose of a return statement? Give example.

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)

6. Explain the replication and concatenation operator for strings in Python


with suitable examples.
replication :The * operator also works on strings; it performs repetition.
For example, 'Spam'*3 is 'SpamSpamSpam'. If one of the values is a string, the other
has to be an integer
Concatenation: The + operator performs string concatenation, which means it joins
the strings by linking them end-to-end.
For example:
>>> first = 'Rajalakshmi'
>>> second = ' Engineering college'
>>> first + second
Output:

„Rajalakshmi Engineering college'

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.

8. What is a recursive function? Give example.


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. For example, look at
the following function:

def countdown(n):
if n <= 0:
print(„rec‟)
else:
print(n)
countdown(n-1)

9.List any four escape sequences in Python.

\" 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

11. Explain string indexing in Python.


A string is a sequence of characters. You can access the characters one at a time with
the bracket operator:
>>> fruit = 'banana'
>>> letter = fruit[1]
The second statement selects character number 1 from fruit and assigns it to letter.
The expression in brackets is called an index. The index indicates which character in
the sequence you want (hence the name).
But you might not get what you expect:
>>> letter
'a'
For most people, the first letter of 'banana' is b, not a. But for computer scientists, the
index is an offset from the beginning of the string, and the offset of the first letter is
zero.
>>> letter = fruit[0]
>>> letter
'b'
So b is the 0th letter (“zero-eth”) of 'banana', a is the 1th letter (“one-eth”), and n is the
2th letter (“two-eth”).

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.

s = input("Enter the string : ")


count = 0
for c in s:
if c in 'aeiouAEIOU':
count = count + 1
print("Number of vowels : ", count)
Output:
Enter the string : Rajalakshmi
Number of vowels : 4

13. What are the two types of functions?


 Built-in functions
 User-defined functions

14. What do you mean by default arguments? Give example.

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:

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

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.

Importing Modules. To make use of the functions in a module, you'll need to


import the module with an import statement. An import statement is made up of
the import keyword along with the name of the module. In a Python file, this
will be declared at the top of the code, under any shebang lines or general
comments
Examble : import math

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:

A string can be initialized by using an assignment statement where it is enclosed


in pair of single or double or triple quotes.
>>> fruit = 'banana'

17. What is the purpose of slicing string in Python?

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


character:

>>> s = 'Monty Python'


>>> s[0:5]
'Monty
>>> s[6:12]
'Python'

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

21.Develop a Python program to find maximum of given three numbers


using Parameter passing
Program:
def maximum(a, b, c):
if(a > b and a > c):
return a
elif(b > a and b > c):
return b;
else:
return c;
a = int(input("Enter the first number : "))
b = int(input("Enter the second number : "))
c = int(input("Enter the third number : "))
print("The maximum number is", maximum(a, b, c))
Output:
Enter the first number : 20
Enter the second number : 30
Enter the third number : 10
The maximum number is 30

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

1. Illustrate with an example, the working of recursive functions.

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.

Fig : STACK DIAGRAM

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 the number of non-overlapping occurrences of substring sub in the range


[start, end]. Optional arguments start and end are interpreted as in slice notation.
Example:
s = "python programming"
print(s.count("a"))
Output:
1
str.endswith()

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()

Return a copy of the string with uppercase characters converted to lowercase


and vice
versa. Note that it is not necessarily true that s.swapcase().swapcase() == s.
Example:
s = "python programming"
p = "CSE Lab"
www.Vidyarthiplus.com
Department of Computer Science and Engineering, REC P a g e | 19
GE17151-Problem Solving and Python Programming - CAT2 - QUESTION BANK
print(s.swapcase()) www.Vidyarthiplus.com
print(p.swapcase())
Output:
PYTHON PROGRAMMING
cse lAB

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.

In Python, user-defined functions can take four different types of arguments.


The argument types and their meanings, however, are pre-defined and can‟t be
changed. But a developer can, instead, follow these pre-defined rules to make
their own custom functions. The following are the four types of arguments and
their rules.
 Required arguments
 Keyword arguments
 Default arguments
 Variable-length arguments

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.

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


character:
>>> s = 'Monty Python'
>>> s[0:5]
'Monty'
>>> s[6:12]
'Python'
The operator [n:m] returns the part of the string from the “n-eth” character to
the “m-eth” character, including the first but excluding the last. This behavior is
counterintuitive, but it might help to imagine the indices pointing between the
characters, as in Figure.

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

You might also like