Lab Manual 3
Lab Manual 3
Lab manual 3
NOTE:
Functions:
Functions are a convenient way to divide your code into useful blocks, allowing us to order your code, make it
more readable, reuse it and save some time.
Here
1. Keyword def marks the start of function header.
2. A function_name is used to uniquely identify function. It is case sensitive and should start with an alphabet.
Name should only have alphabets, digits and underscore.
3. parameters (also known as arguments) are used to pass values to a function. They are optional.
4. A colon (:) to mark the end of function header.
5. Optional documentation string (docstring) to describe what the function does.
6. One or more valid python statements that make up the function body.
7. An optional return statement to return a value from the function.
For example, the absolute value function returns the absolute value of a number
def absolute_value(num):
if num >= 0:
return num Function
else:
return -num
Variable Scope:
Variable referring to an entity in a certain part of a program, may refer to something different in another part of
the program. That is what called the scope of variable. Lifetime of a variable is the period throughout which the
variable exits in the memory. The lifetime of variables inside a function is as long as the function executes.
Here is an example to illustrate the scope of a variable inside a function. Here ‘x’ variable is a local variable
(more information is provided later)
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
Local variables
Local variables can only be reached in their scope. The example below has two local variables:
x and y.
def sum(x,y):
sum = x + y
return sum
print(sum(8,6))
Global variables
The global variable z can be used all throughout the program, inside functions or outside. A
global variable can be modified inside a function and gets changed for the entire program:
z = 10
def afunction():
global z
z = 9
afunction()
print(z)
Example:
Look at the example below and try to think of the output, then run the code to verify your
findings.
z = 10
def func1():
global z
z = 3
def func2(x,y):
global z
return x+y+z
func1()
total = func2(4,5)
print(total)
Function Arguments
Arguments in the function can be in the form of values or functions as well.
For example, in following example func_b takes value as arguments while func_c takes function as argument.
def func_a():
print ('inside func_a')
def func_b(y):
print ('inside func_b')
return y*y
def func_c(z):
print ('inside func_c')
return z(3)
func_a()
print (1 + func_b(2))
print(func_c(func_b))
Recursion function
In Python, a function can call other functions. It is even possible for the function to call itself. If a function call
itself it is known as recursive functions.
Following is an example of recursive function to find the factorial of an integer.
def factorial(n):
print("factorial has been called with n = " + str(n))
if n == 1:
return 1
else:
res = n * factorial(n-1)
print("intermediate result for ", n, " * factorial(" ,n-1, "): ",res)
return res
print(factorial(5))
Run this code and observe how the function works by calling itself again and again.
def cube(n):
return n*n*n
def sumcubes(a,b):
return cube(a)+cube(b)
print(sumcubes(2,3))
Example problem:
Write a function that prints what two strings have in common
def common(s1,s2):
for char1 in s1:
for char2 in s2:
if char1 == char2:
print("Common letter =", char1) #exiting loop
break
"filename" holds the name of the file to be opened, it should be in the current directory. If not,
complete path to that file should be written. "mode" defines the way the file is opened. Mode can
take following values
• 'r' -Read mode which is used when the file is only being read
• 'w' -Write mode which is used to edit and write new information to the file
• 'a' -Appending mode, which is used to add new data to the end of the file
• 'r+' -Special read and write mode, which is used to handle both actions when working
with a file
For example, the following code opens the testfile.txt in read mode.
file = open(“testfile.txt”,”r”)
Read file
To extract a string that contains all characters in the file, use the read function of the file_object.
For example, following code will read the data from the txtfile.txt which was opened earlier as
file.
print file.read()
There is also a readline function which reads the data line by line from the file and is used as
print file.readline()
readline() can take number of lines to read as its arguments i.e. readline(3) will read the
first 3 lines of the file.
Write file
This method is used to add information or content to an existing file. For example the following
code writes two lines in a testfile.
file = open("testfile.txt", 'w')
file.write("This is a test")
file.write("To add more lines.")
Close file
When you’re done working, you can use close() function to end things. What this does is close
the file completely, terminating resources in use, in turn freeing them up for the system to
deploy elsewhere.
For example, the following code closes the opened file.
file = open("testfile.txt", 'w')
file.close()
Buggy Codes
Try to find the errors in the codes below and test it after correcting the errors.
Code 1:
names = ["Sarah", "Rakesh", "Markus", "Eli"]
def print_name(string):
for index in names:
print(string[index])
print_name(names)
Find the error in the code and correct it so that the function may print all the names present in the string.
Code 2:
def replace_a(string):
for char in string:
if char = 'a':
s[char] = 'y'
print(s)
s = "a1a2a3a4a5"
replace_a(s)
The code is expected to change all the ‘a’ characters present in the string with the ‘y’. Find the bugs and run the
corrected version.
Code 3:
def func_b(y):
return y*y
def func_c(z):
return z(3)+z(4)
print(func_b(func_c))
The above code was expected to give the sum or squares of 3 and 4 but unfortunately is giving errors. Identify
and correct the bugs in the code.
Code 4:
def string_pos(string):
i = 0
while i < len(string):
char = string[i] + i
print (char)
word = "Elect"
string_pos(word)
This code was expected to print every character with its position in the word. Find and correct the bug so that the
output may look like below
Output:
E0
l1
e2
c3
t4
Lab Exercise
The following tasks are to be completed in the lab. Follow the think-code-test-debug procedure. Write the algorithm of
each task on a separate page.
1. Write a program that takes an integer x from the user and prints the integer(x), x number of times. The output
should be like:
2. Write a program that asks the user to input names separated by a single space. Your program should print a
greeting ‘hi’ for every name entered, separated by a newline. The output should be like:
3. Use debugger of SPYDER software to debug and correct the following code so that required output is achieved.
The first step will be to use variable explorer window to understand step by step execution of the code in
debugging mode. Do not add or remove any line of the code given below to get the required output. The second
step will be to modify the code. Debugger is explained in a video uploaded on piazza.
4. Write a program that asks the user to enter his/her name and displays “Hi” before the name. Create a function
that takes the name as a formal parameter and the printing task should be performed by that function. The output
should be like
5. The following program calculates and displays the value 𝑎2 − 𝑏 2 . Fill in the blanks to make the code work
properly and then verify it using the computer.
The output should look like
6. Write a program that adds, subtracts, multiplies, divides two numbers and prints the result. Create four functions
to perform these operations. The functions should take the two numbers as formal parameters and return the
result. The printing task should be performed outside the function, in the main program.
7. Write a program to display the output shown below. Create two functions to perform this task. The functions
should neither take any formal parameter nor return anything. The output is
8. Write a program that asks user to enter ‘x’ number of rows and prints the pyramid and its inverted version with
‘x’ number of rows as shown below.
Weekly Exercise
Day 1
Write the function letter_guess (string_array, letter_variable). This function will return
True if a character present in the letter_variable is present in the string named string_array,
and False otherwise.
Day 2
Write a function that takes two strings as input and find how many letters are common
among those strings.
Day 3
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. Write a python function that prints this Fibonacci sequence.
Day 4
Change day 2 exercise so that letter_guess function now takes two arrays as input i.e.
letter_guess (string_array, letter_array). This function should check all the characters
present in the letter_array whether they are present in the string_array and return a string
of all the letters which are present in the string_array.
Day 5
Write a function that takes a string as input and find all the distinct letters present in
the string and finds the frequency of each distinct letter.
Day 6
Given a string, write a python function to check if it is palindrome or not. A string is
said to be palindrome if reverse of the string is same as string. For example, “radar” is
palindrome, but “radix” is not palindrome.