0% found this document useful (0 votes)
2 views

lec3_func_module_files

Lecture 3 of GNBF5010 covers functions and modules in programming, emphasizing the importance of structuring programs into smaller, manageable functions for better readability, reusability, and debugging. It explains the concept of local variables and scope, as well as how to create and utilize modules for organizing code. Additionally, the lecture addresses file input/output operations and provides exercises to reinforce the concepts discussed.

Uploaded by

Michael Chu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

lec3_func_module_files

Lecture 3 of GNBF5010 covers functions and modules in programming, emphasizing the importance of structuring programs into smaller, manageable functions for better readability, reusability, and debugging. It explains the concept of local variables and scope, as well as how to create and utilize modules for organizing code. Additionally, the lecture addresses file input/output operations and provides exercises to reinforce the concepts discussed.

Uploaded by

Michael Chu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Lecture 3

Functions and modules


GNBF5010
Instructor: Jessie Y. Huang
Recap …
Control flow:
• if/else/elif
• while-loops and for-loops

2
Today
• structuring programs
• functions
• local variables and scope

• modules

• file I/O

3
Functions

4
5
Functions
A function is a group of statements that exist within
a program for the purpose of performing a specific
task.

Divide and conquer a large task: Instead of writing a


large program as one long sequence of statements, it
can be written as several small functions, each one
performing a specific part of the task.

6
Benefits of modularizing a program with functions

Simpler code: Small functions are easier to read than


long sequences of statements.
Code reuse: You write the code once and call it
multiple times
Better testing and debugging: Each function can be
individually tested and debugged
Easier for the teamwork: Different team members
can write different functions

7
Defining a function
Function names:
• conform to the same rules as to variable names:
• better be descriptive of the task carried out by the
function, e.g. get_input()

General format: Example:

8
Calling a function

9
The main() function
• main() is called when program starts
• It calls other functions when needed
• It defines the mainline logic of the program

10
Passing an argument to the function
• Argument: piece of data that is sent into a function
• It’s placed in parentheses following the function name

11
Passing multiple arguments
• A function can accept multiple arguments
• Arguments are passed by position to corresponding parameters

12
Passing multiple arguments

??? 13
Writing your own value-returning functions

• Format:

• Examples:
def sum(num1, num2):
def sum(num1, num2):
result = num1 + num2
return num1 + num2
return result

14
Writing your own value-returning functions

Example: prompt user for input and return the user’s input

15
Writing your own value-returning functions
Example: Return Boolean values

16
Writing your own value-returning functions
Example: Return Boolean values

17
Returning multiple values
• A function can return multiple values

18
return vs print()
• return only has meaning • print() can be used inside or
inside a function outside a function
• only one return will be • many print() can be
executed inside a function executed inside a function
• code inside a function but
after the return statement • code inside a function can
will not be executed be executed after print()
• return has a value • print has a value associated
associated with it, which with it, which will be output
will be given to the function to the console
caller

19
Exercise 1
• return vs print
How many lines of output will show up if you run
the code below?
def main():
add(1, 2)
print(add(2, 3))
mult(3, 4)

def add(x, y):


return x + y

def mult(x, y):


print(x * y)

main()

20
Exercise
Get a sequence from the user. If there is an A in the sequence, print
the number of times it appears in the sequence. Do the same for T,
C and G. If a base does not exist, don’t print anything.

Enter a sequence: ACCAGGCA


A count: 3
Test input #1: C count: 3
G count: 2

Enter a sequence: TTTTTGGGG


Test input #2: T count: 5
G count: 4
Exercise (continued)
• Modify the following script by turning part of the
program into a function, which counts bases. Then
call this function in main() and output the results.
seq = "ATGCATGATGCATGAAAGGTCG"
counts = {}
for base in seq:
if base not in counts:
counts[base] = 1
else:
counts[base] += + 1

for base in counts:


print(f"{base} count: {counts[base]}")

22
Exercise (Solution)
def main():
input_seq = "ATGCATGATGCATGAAAGGTCG"
results = count_bases(input_seq)
for base in results:
print(f"{base} count: {results[base]}")

def count_bases(seq):
counts = {}
for base in seq:
if base not in counts:
counts[base] = 1
else:
counts[base] = counts[base] + 1
return counts

main()

23
Local variable and scope

24
Local variable and scope
• A local variable is created inside a function
• Cannot be accessed outside the function
def main(): main() scope f() scope
x = 3
z = f(x) x 3 x 4
3
print(“in main(): x =”, x )
z
Returns 4
def f(x):
x = x + 1
print(“in f(x): x =”, x)
return x main() scope

x 3
main()
z 4

25
Local variable and scope
• A local variable is created inside a function
• Cannot be accessed outside the function

26
Local variables and scope

What is printed?
27
Modules

28
Storing functions in a module
• A module is a file that contains Python code
• Contains function definitions but usually does not
contain code that calls those functions
• Rules for module names:
• File name should end in .py
• Cannot be the same as a Python keyword
• Import module in another script using import
statement
• e.g. import my-script.py

29
Storing functions in a module

The module file contains function definitions, but not code that calls the functions.
30
Exercise: Fill in the blanks in geometry-w_blanks.py

31
Exercise: Fill in the blanks in geometry-w_blanks.py

32
File I/O

33
Writing data to a file

34
Alternatively, use the with statement

35
Reading data from a file

36
General logic of reading a file

37
Read a file using while-loop

1000.00
2000.00
3000.00
4000.00
5000.00
38
Alternatively, use for-loop to read a
file

39
Reading Materials
• Chapters 5 & 6, Starting out with Python 4/e.
• good for beginners

• Chapters 4, 6 & 7, Python for Everybody


• Lecture videos by Charles Severance
• https://www.py4e.com/lessons/strings
• https://www.py4e.com/lessons/functions
• https://www.py4e.com/lessons/files

40

You might also like