0% found this document useful (0 votes)
582 views25 pages

GE8151 Python Programming Unit 3 Question Bank With Sample Code

Part 3 of question bank on GE8151 Problem solving and Python Programming - 2017 Regulations of Anna University for Ist year courses of B.E., B.Tech(Civil,CSE,EEE,ECE, Mechanical)
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
582 views25 pages

GE8151 Python Programming Unit 3 Question Bank With Sample Code

Part 3 of question bank on GE8151 Problem solving and Python Programming - 2017 Regulations of Anna University for Ist year courses of B.E., B.Tech(Civil,CSE,EEE,ECE, Mechanical)
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 25

GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING

UNIT 3 - CONTROL FLOW, FUNCTIONS

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.

1. Analyze different ways to manipulate strings in Python.

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

2. Write the syntax of if and if-else statements.


Python if Statement Syntax

if test expression:
statement(s)

Python if Statement Flowchart

# If the number is positive, we print an appropriate message

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

5. What will be the output of print(str[2:5]) if str=’hello world!’?


str='hello world!'
print(str[2:5])
output
llo
6. Give the use of return() statement with a suitable example.

A function in Python is defined by a def statement. The general syntax looks like this:

def function-name(Parameter list):


statements, i.e. the function body

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

for t in (22.6, 25.8, 27.3, 29.8):


print(t, ": ", fahrenheit(t))

The output of this script looks like this:

22.6 : 72.68
25.8 : 78.44
27.3 : 81.14
29.8 : 85.64

7. Write a program to iterate a range using continue statement.

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!

edibles = ["ham", "spam", "eggs","nuts"]


for food in edibles:
if food == "spam":
print("No more spam please!")
continue
print("Great, delicious " + food)
# here can be the code for enjoying our food :-)
else:
print("I am so glad: No spam!")
print("Finally, I finished stuffing myself")

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

8. Name the type of Boolean operators.

Logical operators
Logical operators are the and, or, not operators.
The logical operators and, or and not are also referred to as boolean operators.

Operator Meaning Example

and True if both the operands are true x and y

or True if either of the operands is true x or y

not True if operand is false (complements the operand) not x

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.

>>> a=50 >>> a=50 >>> a=10


>>> b=25 >>> b=25 >>> a>10
>>> a>40 and b>40 >>> a>40 or b>40 False
False True >>> not(a>10)
>>> a>100 and b<50 >>> a>100 or b<50 True
False True
>>> a==0 and b==0 >>> a==0 or b==0
False False
>>> a>0 and b>0 >>> a>0 or b>0
True True

9. Explain about break statement with an example.


The break Statement:
The break statement in Python terminates the current loop and resumes execution at the next statement.
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.

Example:

for letter in 'Python': # First Example


if letter == 't':
break
print 'Current Letter :', letter

var = 10 # Second Example


while var > 0:
print 'Current variable value :', var
var = var -1
if var == 8:
break

print "Good bye!"


OUTPUT:
Current Letter : P
Current Letter : y
Current variable value : 10
Current variable value : 9
Good bye!

10. Where does indexing starts in Python?

Indexing starts from 0.


Example

>>> fruit = "banana"

5
>>> fruit[:3]
'ban'
>>> fruit[3:]
'ana'

11. Illustrate the flowchart of if-elif-else statements.

Python if...elif...else Statement

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

12. Describe any 4 methods used on a string.


Python String Methods

Python provides lots of built-in methods which we can use on strings.


Below are the list of string methods available in Python 3.

Method Description Examples

>>> mystr = "Hello Python"


>>> print(mystr.count("o"))
2
>>> print(mystr.count("th"))
Returns the number of non- 1
overlapping occurrences of substring >>> print(mystr.count("l"))
Count(sub, [start], [end]) (sub) in the range [start, end]. 2
Optional arguments startand end are >>> print(mystr.count("h"))
interpreted as in slice notation. 1
>>> print(mystr.count("H"))
1
>>> print(mystr.count("hH"))
0

>>> mystr = "HelloPython"


>>> print(mystr.index("P"))
5
Searches the string for a specified
>>>
Index(sub, [start], [end]) value and returns the position of
print(mystr.index("hon"))
where it was found
8
>>> print(mystr.index("o"))
4

>>> mystr = "Hello Python.


Hello Java. Hello C++."
>>>
print(mystr.replace("Hello",
"Bye"))
Returns a string where a specified
Bye Python. Bye Java. Bye
replace(old, new[,count]) value is replaced with a specified
C++.
value
>>>
print(mystr.replace("Hello",
"Hell", 2))
Hell Python. Hell Java.
Hello C++.

>>> mystr = "Hello Python"


split(sep=None, maxsplit=- Splits the string at the specified >>> print(mystr.split())
1) separator, and returns a list ['Hello', 'Python']
>>> mystr1="Hello,,Python"

7
>>> print(mystr1.split(","))
['Hello', '', 'Python']

>>> mystr = "


Hello Python
"
>>> print(mystr.strip(),
Returns a trimmed version of the
strip([chars]) "!")
string
Hello Python !
>>> print(mystr.strip(), "
")
Hello Python

>>> mystr = "hello Python"


upper() Converts a string into upper case >>> print(mystr.upper())
HELLO PYTHON

13. What are the advantages and disadvantages of recursion function?

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.

14. Explain the significance of for loop with else in an example.

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.

Syntax of the For Loop

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:

for <variable> in <sequence>:


<statements>
else:
<statements>

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.

Example of a simple for loop in Python:

8
>>> languages = ["C", "C++", "Perl", "Python"]
>>> for x in languages:
... print(x)
...
C
C++
Perl
Python
>>>

15. Define array with an example.


Arrays

Arrays are used to store multiple values in one single variable:

Example

Create an array containing car names:

cars = ["Ford", "Volvo", "BMW"]

Access the Elements of an Array

You refer to an array element by referring to the index number.

Example

Get the value of the first array item:

cars = ["Ford", "Volvo", "BMW"]


x = cars[0]

print(x)

OUTPUT
Ford

16. Differentiate for loop and while loop.


The 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.

for <variable> in <sequence>:


<statements>
else:

9
<statements>

Example of a simple for loop in Python:

>>> languages = ["C", "C++", "Perl", "Python"]


>>> for x in languages:
... print(x)
...
C
C++
Perl
Python
>>>

A while loop statement in Python programming language repeatedly executes a target statement as long as
a given condition is true.

Syntax

The syntax of a while loop in Python programming language is −


while expression:
statement(s)
n = 100

s=0
counter = 1
while counter <= n:
s = s + counter
counter += 1

print("Sum of 1 until %d: %d" % (n,s))

OUTPUT
Sum of 1 until 100: 5050

17. Classify global variable with local variable.

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.

Global and local Variables in Functions

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)

s = "I love Paris!"


f()
print(s)

The output looks like this:

I love London!
I love Paris!

18. Write a Python program to accept two numbers, multiply them and print the result.

1. a = int(input("enter first number: "))


2. b = int(input("enter second number: "))
3. result = a * b.
4. print("result :", result)
OUTPUT
enter first number: 4
enter second number: 5
result : 20

19. Justify the effects of slicing operation on an array.


How to slice arrays?
We can access a range of items in an array by using the slicing operator :.
1. import array as arr
2.
3. numbers_list = [2, 5, 62, 5, 42, 52, 48, 5]
4. numbers_array = arr.array('i', numbers_list)
5.
6. print(numbers_array[2:5]) # 3rd to 5th
7. print(numbers_array[:-5]) # beginning to 4th
8. print(numbers_array[5:]) # 6th to end
9. print(numbers_array[:]) # beginning to end

11
When you run the program, the output will be:

array('i', [62, 5, 42])


array('i', [2, 5, 62])
array('i', [52, 48, 5])
array('i', [2, 5, 62, 5, 42, 52, 48, 5])

20. How to access the elements of an array using index.


How to access array elements?

We use indices to access elements of an array:

1. import array as arr


2. a = arr.array('i', [2, 4, 6, 8])
3.
4. print("First element:", a[0])
5. print("Second element:", a[1])
6. print("Last element:", a[-1])

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.

# Program to add natural numbers upto n


# sum = 1+2+3+...+n
# To take input from the user,
# n = int(input("Enter n: "))
n = 100
# 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 The sum is 5050

ii. What is the use of pass statement? Illustrate with an example.


The pass Statement:
The pass statement in Python is used when a statement is required syntactically but you do not want any
command or code to execute.

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

for letter in 'Python':


if letter == 'h':
pass
print 'This is pass block'
print 'Current Letter :', letter

print "Good bye!"


OUTPUT
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!

2. Define methods in a string with an example program using at least 5 methods.


Python String Methods

Python provides lots of built-in methods which we can use on strings.

Method Description Examples

Returns a copy of the string with its first >>> print(capitalize(“Hello Python”)
capitalize() character capitalized and the rest
lowercased. Hello python

Returns a casefolded copy of the string. >>> mystring = "hello PYTHON"


Casefold() Casefolded strings may be used for caseless >>> print(mystring.casefold())
matching. hello python

Returns the string centered in a string of >>> mystring = "Hello"


length width. Padding can be done using the >>> x = mystring.center(12,
Center(width, specified fillchar (the default padding uses "-")
[fillchar]) an ASCII space). The original string is >>> print(x)
returned if width is less than or equal to ---Hello----
len(s)

>>> mystr = "Hello Python"


>>> print(mystr.count("o"))
Returns the number of non-overlapping
2
occurrences of substring (sub) in the range
Count(sub, [start], >>> print(mystr.count("th"))
[start, end]. Optional
[end]) 1
arguments startand end are interpreted as in
>>> print(mystr.count("l"))
slice notation.
2
>>> print(mystr.count("h"))

13
1
>>> print(mystr.count("H"))
1
>>> print(mystr.count("hH"))
0

>>> mystr = "Python"


>>>
Returns True if the string ends with the print(mystr.endswith("y"))
endswith(suffix,
specified suffix, otherwise it returns False
[start], [end])
False. >>>
print(mystr.endswith("hon"))
True

How to access characters of a string?


Individual characters in a string can be accessed by specifying the string name followed by a number
in square brackets ( [] ). String indexing in Python is zero-based: the first character in the string has
index 0 , the next has index 1 , and so on.
3. Write a program for binary search using Arrays.

Python Program for Binary Search (Recursive and Iterative)

We basically ignore half of the elements just after one comparison.


1. Compare x with the middle element.
2. If x matches with middle element, we return the mid index.
3. Else If x is greater than the mid element, then x can only lie in right half subarray after the mid
element. So we recur for right half.
4. Else (x is smaller) recur for the left half.
Iterative:
# Iterative Binary Search Function
# It returns location of x in given array arr if present,
# else returns -1
def binarySearch(arr, l, r, x):

while l <= r:

mid = l + (r - l)/2;

# Check if x is present at mid


if arr[mid] == x:
return mid

# If x is greater, ignore left half


elif arr[mid] < x:
l = mid + 1

# If x is smaller, ignore right half


else:
r = mid - 1

# If we reach here, then the element was not present


return -1

# 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.

However, if we use a list, elements are passed by reference. So that here,

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

5. i) Write a python program to find the given number is odd or even

1. # Python program to check if the input number is odd or even.


2. # A number is even if division by 2 gives a remainder of 0.
3. # If the remainder is 1, it is an odd number.
4.
5. num = int(input("Enter a number: "))
6. if (num % 2) == 0:
7. print("{0} is Even".format(num))
8. else:
9. print("{0} is Odd".format(num))

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.

Python code to count and display number of vowels


# Simply using for and comparing it with a
# string containg all vowels
def Check_Vow(string, vowels):
final = [each for each in string if each in vowels]
print(len(final))
print(final)

# 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']

Explain the types of function arguments in Python

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)

for items in address.items():


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

#Function with Keyword argements


def print_name(name1, name2):
""" This function prints the name """
print (name2 + " and " + name1 + " are friends")
#calling the function
print_name(name2 = 'John',name1 = 'Gary')

John and Gary are friends

def sum(a=4, b=2): #2 is supplied as default argument


""" This function will print sum of two numbers
if the arguments are not supplied
it will add the default value """
print (a+b)
sum(1,2) #calling with arguments
sum( ) #calling without arguments

3
6

7. Explain the syntax and flowchart of the following loop statements


i) for loop

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:

for <variable> in <sequence>:


<statements>
else:
<statements>

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.

Example of a simple for loop in Python:

>>> languages = ["C", "C++", "Perl", "Python"]


>>> for x in languages:
... print(x)
...
C
C++
Perl
Python
>>>

ii) while loop


What is while loop in Python?
The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is
true.
We generally use this loop when we don't know beforehand, the number of times to iterate.
Syntax of while Loop in Python

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.

Flowchart of while Loop

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

8. Illustrate with an example nested if and elif header in Python.

Python Nested if statements


We can have a if...elif...else statement inside another if...elif...else statement. This is called nesting in
computer programming.
Any number of these statements can be nested inside one another. Indentation is the only way to figure out
the level of nesting. This can get confusing, so must be avoided if we can.

Python Nested if Example


1. # In this program, we input a number
2. # check if the number is positive or
3. # negative or zero and display
4. # an appropriate message
5.
6. num = float(input("Enter a number: "))
7. if num >= 0:
8. if num == 0:
9. print("Zero")
10. else:
11. print("Positive number")
12. else:
13. print("Negative number")
Output 1

19
Enter a number: 5
Positive number

Output 2

Enter a number: -1
Negative number

Output 3

Enter a number: 0
Zero

Develop a program to find the largest among three numbers.

9. Explain recursive function. How do recursive function works?

Recursive Functions in Python


A recursive function is a function defined in terms of itself via self-referential expressions. This means that
the function will continue to call itself and repeat its behavior until some condition is met to return a result.
The Fibonacci numbers are the numbers of the following sequence of integer values:

0,1,1,2,3,5,8,13,21,34,55,89, ...

The Fibonacci numbers are defined by:


Fn = Fn-1 + Fn-2
with F0 = 0 and F1 = 1

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.

# To get year (integer input) from the user.


year = int(input("Enter a year: "))

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.

Python: Mutable vs. Immutable


Everything in Python is an object . You have to understand that Python represents all its data as objects. An
object’s mutability is determined by its type. Some of these objects like lists and dictionaries are mutable ,
meaning you can change their content without changing their identity. Other objects like integers, floats,
strings and tuples are objects that can not be changed.

Strings are Immutable List is mutable Tuple is immutable

Strings are immutable in Having mutable variables means


Python, which means you that calling the same method with
cannot change an existing the same variables may not
string. The best you can do is guarantee the same output,
create a new string that is a because the variable can be
variation on the original. mutated at any time by another
method or perhaps, another
thread, and that is where you start
to go crazy debugging.
Example Mutable example Immutable example

message = "strings immutable" my_list = [10, 20, 30] my_yuple = (10, 20, 30)

message[0] = 'p' print(my_list) print(my_yuple)

print(message) Output Output

output [10, 20, 30] (10, 20, 30)

Instead of producing the output continue... my_yuple = (10, 20, 30)


"strings immutable", this code my_yuple[0] = 40
produces the runtime error: my_list = [10, 20, 30] print(my_yuple)
output
TypeError: 'str' object does not my_list[0] = 40 Traceback (most recent
support item assignment call last):
print(my_list) File "test.py", line 3, in <
Why are Python strings module >
immutable? my_yuple[0] = 40
Output
TypeError: 'tuple' object
Which means a string alue cannot does not support item
[40, 20, 30]
be updated . Immutability is a assignment
clean and efficient solution to
concurrent access.
Having immutable
variables means that no matter
how many times the method is
called with the same

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.

def fib(n): # return Fibonacci series up to n


result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a + b
return result

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("\nResult from a multi Function")


def multi_func(x, y):
return x * y

print(multi_func(5, 20))
OUTPUT
100

Result from a multiply Function


100

Discuss the methods to manipulate the arrays in Python.

Python Arrays

In programming, an array is a collection of elements of the same type.


Arrays are popular in most programming languages like Java, C/C++, JavaScript and so on.
However, in Python, they are not that common.

Python Lists Vs array Module as Arrays

22
We can treat lists as arrays. However, we cannot constrain the type of elements stored in a list.

How to create arrays?


We need to import array module to create arrays. For example:

1. import array as arr


2. a = arr.array('d', [1.1, 3.5, 4.5])
3. print(a)

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?

We use indices to access elements of an array:

1. import array as arr


2. a = arr.array('i', [2, 4, 6, 8])
3.
4. print("First element:", a[0])
5. print("Second element:", a[1])
6. print("Last element:", a[-1])

Remember, the index starts from 0 (not 1) similar to lists.

How to slice arrays?


We can access a range of items in an array by using the slicing operator :.
1. import array as arr
2.
3. numbers_list = [2, 5, 62, 5, 42, 52, 48, 5]
4. numbers_array = arr.array('i', numbers_list)
5.
6. print(numbers_array[2:5]) # 3rd to 5th
7. print(numbers_array[:-5]) # beginning to 4th
8. print(numbers_array[5:]) # 6th to end
9. print(numbers_array[:]) # beginning to end

When you run the program, the output will be:

array('i', [62, 5, 42])


array('i', [2, 5, 62])
array('i', [52, 48, 5])
array('i', [2, 5, 62, 5, 42, 52, 48, 5])

How to change or add elements?

23
Arrays are mutable; their elements can be changed in a similar way like lists.

1. import array as arr


2.
3. numbers = arr.array('i', [1, 2, 3, 5, 7, 10])
4.
5. # changing first element
6. numbers[0] = 0
7. print(numbers) # Output: array('i', [0, 2, 3, 5, 7, 10])
We can concatenate two arrays using + operator.
1. import array as arr
2.
3. odd = arr.array('i', [1, 3, 5])
4. even = arr.array('i', [2, 4, 6])
5.
6. numbers = arr.array('i') # creating empty array of integer
7. numbers = odd + even
8.
9. print(numbers)

How to remove/delete elements?


We can delete one or more items from an array using Python's del statement.
1. import array as arr
2.
3. number = arr.array('i', [1, 2, 3, 3, 4])
4.
5. del number[2] # removing third element
6. print(number) # Output: array('i', [1, 2, 3, 4])
13. Explain the significance of xrange() function in for loop with a help of a program.

# Python code to demonstrate range() vs xrange() on basis of memory

import sys
from past.builtins import xrange

# initializing a with range()


a = range(1,10000)

# initializing a with xrange()


x = xrange(1,10000)

# testing the size of a


# range() takes more memory

print ("The size allotted using range() is : ")


print (sys.getsizeof(a))

# testing the size of a


# range() takes less memory

print ("The size allotted using xrange() is : ")

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

# check if the number is negative


if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recur_factorial(num))
Illustrate the concept of local and global variables.

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

You might also like