GE8151 Python Programming Unit 3 Question Bank With Sample Code
GE8151 Python Programming Unit 3 Question Bank With Sample Code
SYLLABUS
Conditionals: Boolean values and operators, conditional (if), alternative (if-else), chained conditional (if-elif-
else); Iteration: state, while, for, break, continue, pass; Fruitful functions: return values, parameters, local and
global scope, function composition, recursion; Strings: string slices, immutability, string functions and
methods, string module; Lists as arrays. Illustrative programs: square root, gcd, exponentiation, sum an array
of numbers, linear search, binary search.
PART-A
Q. Q&A
No.
Slicing
In Python slice operator is used to slice a part of a string. The syntax uses start and end index with a “:” in
between as shown in the following example:
>>> str = "Python is great"
>>> first_six = str[0:6]
>>> first_six
OUTPUT : Python
if test expression:
statement(s)
num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")
1
OUTPUT
3 is a positive number.
This is always printed.
Python if...else Statement
Syntax of if...else
if test expression:
Body of if
else:
Body of else
num = 3
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
OUTPUT
‘Positive or zero’
3. List out the applications of arrays.
Arrays
Arrays are used to store multiple values in one single variable:
cars = ["Ford", "Volvo", "BMW"]
print(cars)
OUTPUT
['Ford', 'Volvo', 'BMW']
4. Discuss about continue and pass statements.
for i in 'hello':
if(i == 'e'):
print('pass executed')
pass
print(i)
print('----')
for i in 'hello':
if(i == 'e'):
print('continue executed')
continue
print(i)
2
Output :-
h
pass executed
e
l
l
o
----
h
continue executed
l
l
o
A function in Python is defined by a def statement. The general syntax looks like this:
The parameter list consists of none or more parameters. Parameters are called arguments, if the function is called. The
function body consists of indented statements. The function body gets executed every time the function is called.
Parameter can be mandatory or optional.
Function bodies can contain one or more return statement. They can be situated anywhere in the function body. A
return statement ends the execution of the function call and "returns" the result, i.e. the value of the expression
following the return keyword, to the caller. Example:
def fahrenheit(T_in_celsius):
""" returns the temperature in degrees Fahrenheit """
return (T_in_celsius * 9 / 5) + 32
22.6 : 72.68
25.8 : 78.44
27.3 : 81.14
29.8 : 85.64
3
The continue Statement:
The continue statement in Python 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.
In the following script , when we have encountered a spam item, continue prevents us from eating spam!
OUTPUT:
$ python for.py
Great, delicious ham
No more spam please!
Great, delicious eggs
Great, delicious nuts
I am so glad: No spam!
Finally, I finished stuffing myself
Logical operators
Logical operators are the and, or, not operators.
The logical operators and, or and not are also referred to as boolean operators.
4
Boolean and operator returns Boolean or operator returns The not operator returns true if
true if both operands return true if any one operand is true its operand is a false expression
true. and returns false if it is true.
Example:
5
>>> fruit[:3]
'ban'
>>> fruit[3:]
'ana'
Syntax of if...elif...else
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
The elif is short for else if. It allows us to check for multiple expressions.
If the condition for if is False, it checks the condition of the next elif block and so on.
If all the conditions are False, body of else is executed.
Only one block among the several if...elif...else blocks is executed according to the condition.
The if block can have only one else block. But it can have multiple elif blocks.
Flowchart of if...elif...else
Example of if...elif...else
# In this program, we check if the number is positive or negative or zero
# and display an appropriate message
num = 3.4
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
6
When variable num is positive, Positive number is printed.
If num is equal to 0, Zero is printed.
If num is negative, Negative number is printed
7
>>> print(mystr1.split(","))
['Hello', '', 'Python']
Advantages of Recursion
1. Recursive functions make the code look clean and elegant.
2. A complex task can be broken down into simpler sub-problems using recursion.
3. Sequence generation is easier with recursion than using some nested iteration.
Disadvantages of Recursion
1. Sometimes the logic behind recursion is hard to follow through.
2. Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
3. Recursive functions are hard to debug.
For Loops
For loop is a programming language statement, i.e. an iteration statement, which allows a code block to be repeated a
certain number of times.
The Python for loop is an iterator based for loop. It steps through the items of lists, tuples, strings, the keys of
dictionaries and other iterables. The Python for loop starts with the keyword "for" followed by an arbitrary variable
name, which will hold the values of the following sequence object, which is stepped through. The general syntax
looks like this:
The items of the sequence object are assigned one after the other to the loop variable; to be precise the variable points
to the items. For each item the loop body is executed.
8
>>> languages = ["C", "C++", "Perl", "Python"]
>>> for x in languages:
... print(x)
...
C
C++
Perl
Python
>>>
Example
Example
print(x)
OUTPUT
Ford
9
<statements>
A while loop statement in Python programming language repeatedly executes a target statement as long as
a given condition is true.
Syntax
s=0
counter = 1
while counter <= n:
s = s + counter
counter += 1
OUTPUT
Sum of 1 until 100: 5050
Local Variables
When you define variables inside a function definition, they are local to this function by default. This
means that anything you will do to such a variable in the body of the function will have no effect on other
variables outside of the function, even if they have the same name. This means that the function body is
the scope of such a variable, i.e. the enclosing context where this name with its values is associated.
The following example, demonstrates, how global values can be used inside the body of a
function:
def f():
10
print(s)
#s is global variable
s = "I love Paris in the summer!"
f()
Local Variable
def f():
#Here is id local variable
s = "I love London!"
print(s)
I love London!
I love Paris!
18. Write a Python program to accept two numbers, multiply them and print the result.
11
When you run the program, the output will be:
OUTPUT
First element: 2
Second element: 4
Last element: 8
PART-B
1. i. Write a Python program to find the sum of N natural numbers.
12
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 (e.g., in stubs for example):
Example:
#!/usr/bin/python
Returns a copy of the string with its first >>> print(capitalize(“Hello Python”)
capitalize() character capitalized and the rest
lowercased. Hello python
13
1
>>> print(mystr.count("H"))
1
>>> print(mystr.count("hH"))
0
while l <= r:
mid = l + (r - l)/2;
# Test array
arr = [ 2, 3, 4, 10, 40 ]
14
x = 10
# Function call
result = binarySearch(arr, 0, len(arr)-1, x)
if result != -1:
print "Element is present at index %d" % result
else:
print "Element is not present in array"
Output:
Element is present at index 3
4. What is call by value and call by reference and explain it with suitable example
call-by-value :
1. >def plus_1(x) :
2. > x=x+1
3. >
4. >x=5
5. >plus_1(x)
6. >print x
7. 5
Here, x was passed by value - local changes within the function didn’t echo back to the
calling scope.
1. >def plus_1(x) :
2. > x[0]=x[0]+1
3. >
4. >x=[5]
5. >plus_1(x)
6. >print x[0]
7. 6
Enter a number: 77
77 is Odd
6. Write a Python program to count the number of vowels in a string provided by the user.
Counting vowels: String Way
In this method, we will store all the vowels in a string and then pick every character from the enquired
string and check whether it is in the vowel string or not. The vowel string consists of all the vowels with
both cases since we are not ignoring the cases here. If the vowel is encountered then count gets
15
incremented and stored in a list and finally printed.
# Driver Code
string = "I wandered lonely as a cloud"
vowels = "AaeEeIiOoUu"
Check_Vow(string, vowels);
Output:
10
['I', 'a', 'e', 'e', 'o', 'e', 'a', 'a', 'o', 'u']
Function Arguments
There are three types of Python function arguments using which we can call a function.
Default Arguments.
Keyword Arguments.
Variable-length Arguments.
# Function call with variable arguments
def display(*name, **address):
for items in name:
print (items)
16
#Calling the function
display('john','Mary','Nina',John='LA',Mary='NY',Nina='DC')
john
Mary
Nina
('John', 'LA')
('Mary', 'NY')
('Nina', 'DC')
3
6
For Loops
Introduction
For loop is a programming language statement, i.e. an iteration statement, which allows a code block to be
repeated a certain number of times. The Python for loop is an iterator based for loop. It steps through the
items of lists, tuples, strings, the keys of dictionaries and other iterables. The Python for loop starts with the
keyword "for" followed by an arbitrary variable name, which will hold the values of the following sequence
object, which is stepped through. The general syntax looks like this:
The items of the sequence object are assigned one after the other to the loop variable; to be precise the
17
variable points to the items. For each item the loop body is executed.
while test_expression:
Body of while
In while loop, test expression is checked first. The body of the loop is entered only if
the test_expression evaluates to True. After one iteration, the test expression is checked again. This process
continues until the test_expression evaluates to False.
In Python, the body of the while loop is determined through indentation.
Body starts with indentation and the first unindented line marks the end.
Python interprets any non-zero value as True. None and 0 are interpreted as False.
18
Example: Python while Loop
# Program to add natural numbers upto n
# sum = 1+2+3+...+n
# To take input from the user,
# n = int(input("Enter n: "))
n = 10
# initialize sum and counter
sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum
print("The sum is", sum)
OUTPUT
Enter n: 10
The sum is 55
19
Enter a number: 5
Positive number
Output 2
Enter a number: -1
Negative number
Output 3
Enter a number: 0
Zero
0,1,1,2,3,5,8,13,21,34,55,89, ...
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
10. Create a Python program to find the given year is leap year or not.
# Python program to check if year is a leap year or not.
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year". format(year))
if (year % 4) is not 0:
print("{0} is NOT a leap year". format(year))
20
OUTPUT
Enter a year: 2019
2019 is NOT a leap year
Enter a year: 2000
2000 is a leap year
Investigate on mutability and immutability in Python.
message = "strings immutable" my_list = [10, 20, 30] my_yuple = (10, 20, 30)
21
variable/value, the output will
always be the same.
11. Explain the different types of the function prototype with an example.
Foreign functions can also be created by instantiating function prototypes. Function
prototypes are similar to function prototypes in C; they describe a function (return
type, argument types, calling convention) without defining an implementation. The
factory functions must be called with the desired result type and the argument types
of the function.
Examine a Python program to generate first ‘N’ Fibonacci numbers.
print(fib(100))
#[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Note: The Fibonacci numbers are 0,1,1,2,3,5,8,….. where each number is the sum of preceding two.
12. Generate a program that uses lambda function to multiply two numbers.
multi = lambda x, y : x * y
print(multi(5, 20))
print(multi_func(5, 20))
OUTPUT
100
Python Arrays
22
We can treat lists as arrays. However, we cannot constrain the type of elements stored in a list.
Here, we created an array of float type. The letter 'd' is a type code. This determines the type of the
array during creation.
How to access array elements?
23
Arrays are mutable; their elements can be changed in a similar way like lists.
import sys
from past.builtins import xrange
24
print (sys.getsizeof(x))
Output:
The size allotted using range() is :
80064
The size allotted using xrange() is :
40
14. Create a program to find the factorial of given number without recursion and with recursion.
# Factorial of a number using recursion
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num = 6
n=int(input("Enter number:"))
fact=1
while(n>0):
fact=fact*n
n=n-1
print("Factorial of the number is: ")
print(fact)
Enter number: 6
OUTPUT
Factorial of the number is:
720
25