0% found this document useful (0 votes)
46 views31 pages

Functions II: Monday, September 20, 2021 Cs4051 Fundamentals of Computing 1

The document discusses functions and working with text files in Python. It covers defining functions, using functions as modules, reading from and writing to text files, and testing and debugging code. The key topics are modularity through breaking programs into well-defined functions, and processing text data by reading from and writing to files.

Uploaded by

jpjpj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views31 pages

Functions II: Monday, September 20, 2021 Cs4051 Fundamentals of Computing 1

The document discusses functions and working with text files in Python. It covers defining functions, using functions as modules, reading from and writing to text files, and testing and debugging code. The key topics are modularity through breaking programs into well-defined functions, and processing text data by reading from and writing to files.

Uploaded by

jpjpj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Lecture 8:

Functions II

Sukrit Shakya
[email protected]

Monday, September CS4051 FUNDAMENTALS OF COMPUTING 1


Today
• Modularity via functions
• Working with text files
• Testing and debugging

Monday, September CS4051 FUNDAMENTALS OF COMPUTING 2


Defining functions
keyword name parameters
docstring, specifications of the
def add_two(a,b): function
”””takes 2 numbers and returns sum”””
sum_ = a + b body of the function
return sum_ the functions adds the two numbers
and returns the sum

Monday, September CS4051 FUNDAMENTALS OF COMPUTING 3


Defining functions
def add_two(a,b):
”””takes 2 numbers and returns sum”””
sum_ = a + b
return sum_
print(add_two(1,4)) #prints out 5
print(add_two(10,2)) #prints out 12

Monday, September CS4051 FUNDAMENTALS OF COMPUTING 4


Using functions as modules
 
def add(a,b):
return a+b

def subtract(a,b):
return a-b calculate the value for x

def multiply(a,b):
return a*b

def divide(a,b):
return a/b

Monday, September CS4051 FUNDAMENTALS OF COMPUTING 5


Using functions as modules
 
def add(a,b):
return a+b

def subtract(a,b):
return a-b calculate the value for x
first = add(5,9)
def multiply(a,b):
second = subtract(5,9)
return a*b
x = multiply(first,second)
def divide(a,b): print(x) #prints out -56
return a/b

Monday, September CS4051 FUNDAMENTALS OF COMPUTING 6


Using functions as modules
 
def add(a,b):
return a+b

def subtract(a,b):
return a-b calculate the value for x
x = multiply(add(5,9),subtract(5,9))
def multiply(a,b):
print(x) #prints out -56
return a*b

def divide(a,b):
return a/b

Monday, September CS4051 FUNDAMENTALS OF COMPUTING 7


Using functions as modules
 
def add(a,b):
return a+b

def subtract(a,b):
return a-b calculate the value for x
first = add(5,9)
def multiply(a,b):
second = subtract(5,9)
return a*b
third = multiply(first,second)
def divide(a,b): x = divide(third,2)
return a/b
print(x) #prints out -28

Monday, September CS4051 FUNDAMENTALS OF COMPUTING 8


Working with text files
• Python lets you read data from plain text files (.txt) and also write
data to them
• Data read from files are by default strings and only strings can be
written back to files
• While working with files, the file must be in the same folder as the
python script/if not the full path to the file must be specified

Monday, September CS4051 FUNDAMENTALS OF COMPUTING 9


Reading from a file
file = open(“file1.txt”,“r”) file1.txt

hello python
open function to open file filename mode in which the file
this is a file
in being opened, “r”
print(file.read()) means reading mode

the read function reads the


content of the file as a single
file.close() string/ then the print function
prints the content
>>>
need to close the file at the end hello python
this is a file

Monday, September CS4051 FUNDAMENTALS OF COMPUTING 10


Reading from a file
file = open(“file1.txt”,“r”) file1.txt

lines = file.readlines() hello python


this is a file

reads each line and puts it in a


print(lines) list

file.close()

>>>
['hello python\n',
'this is a file']

Monday, September CS4051 FUNDAMENTALS OF COMPUTING 11


Reading from a file
file = open(“file1.txt”,“r”) file1.txt

lines = file.readlines() hello python


this is a file

reads each line and puts it in a


for line in lines: list

print(line)
file.close()
>>>
hello python
this is a file

Monday, September CS4051 FUNDAMENTALS OF COMPUTING 12


Writing to a file
file = open(“file2.txt”,“w”) file2.txt

mode is set to “w”, 012


will create a new file, if file is already
meaning writing mode
present will overwrite the file

for i in range(3):
write the current value of i to file
file.write(str(i)) using the write function, i is of int
type so need to convert to str before
writing to file
file.close()

Monday, September CS4051 FUNDAMENTALS OF COMPUTING 13


Writing to a file
file = open(“file2.txt”,“w”) file2.txt

mode is set to “w”, 0


will create a new file, if file is already 1
meaning writing mode
present will overwrite the file 2

for i in range(3):
write the current value of i to file
file.write(str(i)) using the write function, i is of int
file.write(“\n”) type so need to convert to str before
writing to file

insert a line break which moves


file.close() the cursor to the next line

Monday, September CS4051 FUNDAMENTALS OF COMPUTING 14


Testing & Debugging
Testing Debugging
• Compare input/output, check if • Study events leading up to an
desired output is achieved for error
some input value • Process of finding out
• Tells us if the program is “Why is it not working?”
working or not • “How can I fix my program”
• “How can I break my program?”

Monday, September CS4051 FUNDAMENTALS OF COMPUTING 15


Testing & Debugging
• set yourself up for easy testing and debugging
• design your code in such a way that eases this part
• break the program up into modules that can be tested and
debugged individually, using functions we can achieve modularity
• document each module/function
 what do you expect the input to be?
 what do you expect the output to be?
• document your intensions/assumptions behind the code

Monday, September CS4051 FUNDAMENTALS OF COMPUTING 16


Modularity via functions
• Suppose you have to write a program that analyzes data stored in a
text file
name, math, science, physics
john, 88, 76, 77
sam, 76, 88, 65
anna, 76, 56, 79
• The program should calculate the average marks of each student
and the topper of each subject

Monday, September CS4051 FUNDAMENTALS OF COMPUTING 17


Modularity via functions
• The task can be divided into the following sub tasks

store that data


efficiently using perform analysis on
read data from file
python’s collection that data
data types

• you could write the whole program as a sequence of commands which


executes one task after another
• but it would be very messy and hard to keep track of
• and testing/debugging the program would be very hard

Monday, September CS4051 FUNDAMENTALS OF COMPUTING 18


Modularity via functions
• you can decompose your program into modules by using functions
store that data efficiently
perform analysis on that
read data from file using python’s collection
data
write code to read data data types
write code to perform
only write code to store data
analysis only
only

• this would be easier to manage and debug


• for instance, if the analysis part is not giving proper results, you know exactly
where to look for bugs/errors
• notice that each module is self-contained but they work together towards the
same goal
CS4051 FUNDAMENTALS OF
Monday, September 19
Good programming
• more code is not necessarily a good thing
• measure good programmers by the amount of functionality in their
code
• messy code is hard to understand for other fellow programmers
• and sometimes the programmer who wrote the program might
find it hard to understand his/her code in the future

Monday, September CS4051 FUNDAMENTALS OF COMPUTING 20


When are you ready to test?
• ensure your code runs
 remove syntax errors, python interpreter can easily find this for
you
• have a set of expected results
 an input set
 for each input, the expected output

Monday, September CS4051 FUNDAMENTALS OF COMPUTING 21


Black box testing
• belongs to a class of testing called unit testing where each piece of
program is validated, each function/module is tested separately
• check if for a set of inputs you get the desired output without
knowledge of the actual internal composition of the program
• usually done by someone other than the implementer to avoid
implementer bias

CS4051 FUNDAMENTALS OF
Monday, September 22
Testing example
• Suppose you are testing a function created for adding 2 numbers

Test no. 1
Action Pass two numbers 2 and 3 as
parameters to function add_two
Expected output 5
Actual output 5
Test result Pass

Monday, September CS4051 FUNDAMENTALS OF COMPUTING 23


Testing example
Test no. 2
Action Pass two numbers 2 and “s” as
parameters to function add_two
Expected output Error
Actual output Error
Test result Pass

Test no. 3
Action Pass two numbers 2 and 1 as parameters
to function add_two
Expected output 3
Actual output 1
Test result Fail

Monday, September CS4051 FUNDAMENTALS OF COMPUTING 24


Debugging
• goal is to have a bug-free program/fix the failed test cases
• tools
 built in debugger in IDLE
 pythontutor.com
 print statement
 your brain

Monday, September CS4051 FUNDAMENTALS OF COMPUTING 25


Print statements
• you can put multiple print statements throughout your code to see
what’s going on and how the variable values are changing
l = [2,55,43,1]
s = 0
for i in range(len(l)):
print(l[i]) #print current element
s = s + l[i]
print(s) #print the updated sum
print(s) #print the final sum

Monday, September CS4051 FUNDAMENTALS OF COMPUTING 26


Error messages
• trying to access beyond the limits of a list
test = [1,2,3] then test[4] -> IndexError
• trying to convert an inappropriate type
int(“hello”) -> TypeError
• referencing a non-existent variable
a -> NameError

Monday, September CS4051 FUNDAMENTALS OF COMPUTING 27


Error messages
• mixing datatypes without proper type conversion
‘3’/4 -> TypeError
• forgetting to close parenthesis, quotation, etc
a = int(input(“enter a num: ”)
print(a) -> SyntaxError

Monday, September CS4051 FUNDAMENTALS OF COMPUTING 28


Testing & Debugging
DON’T DO
• Write entire program • Write a function
• Test entire program • Test the function
• Debug entire program • Debug the function
• Integrate the functions together &
test if the overall program works
(remember how we calculated the
value of the complex
mathematical expression)

Monday, September CS4051 FUNDAMENTALS OF COMPUTING 29


End of Lecture 8

Monday, September CS4051 FUNDAMENTALS OF COMPUTING 30


Thank you !
Any questions ?

Monday, September CS4051 FUNDAMENTALS OF COMPUTING 31

You might also like