Computer Programming
-- Python
Lecture 5
Module
Dr. I-Fan Lin
Copyright © 2018 Pearson Education, Ltd.
Introduction to Value-Returning
Functions: Generating Random Numbers
• Void function: group of statements within
a program for performing a specific task
– Call function when you need to perform the
task
• Value-returning function: similar to void
function, returns a value
– Value returned to part of program that called
the function when function finishes
executing
2
Standard Library Functions
and the import Statement
• Standard library: library of pre-written
functions that comes with Python
– Library functions perform tasks that
programmers commonly need
• Example: print, input, range
• Viewed by programmers as a “black box”
• Some library functions built into Python
interpreter
– To use, just call the function
2024/3/20 3
Standard Library Functions
and the import Statement
• Modules: files that stores functions of the standard
library
– Help organize library functions not built into the
interpreter
– Copied to computer when you install Python
• To call a function stored in a module, need to write
an import statement
– Written at the top of the program
– Format: import module_name
4
Generating Random Numbers
• Random number are useful in a lot of
programming tasks
• random module: includes library functions
for working with random numbers
• Dot notation: notation for calling a function
belonging to a module
– Format: module_name.function_name()
5
Generating Random Numbers
• randint function: generates a random
number in the range provided by the
arguments
– Returns the random number to part of program
that called the function
– Returned integer can be used anywhere that an
integer would be used
– You can experiment with the function in
interactive mode
6
Generating Random Numbers
7
Generating Random Numbers
8
Generating Random Numbers
Please write a program that should randomly generate two
numbers in the range of 1 through 6 and display them. Use
the program to simulate several rolls of the dice, one after the
other.
1.Display a random number in the range of 1 through 6.
2.Display another random number in the range of 1 through 6
3.Ask the user if he or she wants to roll the dice again.
You need to write a while loop that simulates one roll of the dice and
then ask the user if another roll should be performed.
9
Generating Random Numbers
10
Generating Random Numbers
Please write another program to simulate ten coin tosses, one
after the other. Each time the program simulates a coin toss, if
should randomly display either “Heads” or “Tails”.
You will simulate the tossing of a coin by randomly generating
a number in the range of 1 through 2. You will write an if
statement that display “Heads” if the random number is 1, of
“Tails” otherwise.
Repeat 10 times:
If a random number in the range of 1 through 2 equals 1 then:
Display “Heads”
Else:
Display “Tails”
11
Generating Random Numbers
12
Generating Random Numbers
• randrange function: similar to range
function, but returns randomly selected
integer from the resulting sequence
– Same arguments as for the range function
• random function: returns a random float in
the range of 0.0 and 1.0
– Does not receive arguments
• uniform function: returns a random float but
allows user to specify range
13
Random Number Seeds
• Random number created by functions in random
module are actually pseudo-random numbers
• Seed value: initializes the formula that generates
random numbers
– Need to use different seeds in order to get different series
of random numbers
• By default uses system time for seed
• Can use random.seed() function to specify desired seed value
14
Writing Your Own Value-
Returning Functions
• To write a value-returning function, you
write a simple function and add one or
more return statements
– Format: return expression
• The value for expression will be returned to the
part of the program that called the function
– The expression in the return statement can
be a complex expression, such as a sum of
two variables or the result of another value-
returning function
15
Writing Your Own Value-
Returning Functions
16
Example
17
How to Use Value-Returning
Functions
• Value-returning function can be useful in
specific situations
– Example: have function prompt user for input
and return the user’s input
– Simplify mathematical expressions
– Complex calculations that need to be repeated
throughout the program
• Use the returned value
– Assign it to a variable or use as an argument in
another function
18
How to Use Value-Returning
Functions (example)
19
Returning Strings
• You can write functions that return strings
• For example:
20
Returning Boolean Values
• Boolean function: returns either True or
False
– Use to test a condition such as for decision
and repetition structures
• Common calculations, such as whether a number
is even, can be easily repeated by calling a
function
– Use to simplify complex input validation code
21
Returning Boolean Values
22
Returning Multiple Values
• In Python, a function can return multiple values
– Specified after the return statement separated by
commas
• Format: return expression1,
expression2, etc.
– When you call such a function in an assignment
statement, you need a separate variable on the left
side of the = operator to receive each returned value
23
Returning None From a
Function
• The special value None means “no value”
• Sometimes it is useful to return None from
a function to indicate that an error has
occurred
def divide(num1, num2):
if num2 == 0:
result = None
else:
result = num1 / num2
return result
24
The math Module
• math module: part of standard library that
contains functions that are useful for
performing mathematical calculations
– Typically accept one or more values as
arguments, perform mathematical operation,
and return the result
– Use of module requires an import math
statement
25
The math Module
26
The math Module
27
The math Module
• The math module defines variables pi
and e, which are assigned the
mathematical values for pi and e
– Can be used in equations that require these
values, to get more accurate results
• Variables must also be called using the dot
notation
– Example:
circle_area = math.pi * radius**2
28
Storing Functions in Modules
• In large, complex programs, it is
important to keep code organized
• Modularization: grouping related
functions in modules
– Makes program easier to understand, test,
and maintain
– Make it easier to reuse code for multiple
different programs
• Import the module containing the required
function to each program that needs it
29
Storing Functions in Modules
• Module is a file that contains Python code
– Contains function definition but does not
contain calls to the functions
• Importing programs will call the functions
• Rules for module names:
– File name should end in .py
– Cannot be the same as a Python keyword
• Import module using import statement
30
Storing Functions in Modules
circle module with two functions: area
and circumference
31
Storing Functions in Modules
• Procedure
Right click Create the .py file
32
Storing Functions in Modules
• Procedure
edit your code
double click the file
33
Storing Functions in Modules
• Procedure
import the module
34
Storing Functions in Modules
• How to execute the .py file
run the circle.py
35
Conditionally Executing the
main Function
• It is possible to create a module that can be run as
a standalone program or imported into another
program
• Suppose Program A defines several functions that
you want to use in Program B
• So, you import Program A into Program B
• However, you do not want Program A to execute its
main function when you import it
36
Conditionally Executing the
main Function
• In the aforementioned scenario, you write
each module so it executes its main function
only when the module is being run as the
main program
– When a source code file is loaded into the Python
interpreter, a special variable called __name__ is created
– If the source code file has been imported as a module, the
__name__ variable will be set to the name of the module.
– If the source code file is being executed as the main
program, the __name__ variable will be set to the value
'__main__'.
37
Conditionally Executing the
main Function
• To prevent the main function from being
executed when the file is imported as a
module, you can conditionally execute main
def main():
statement
statement
def my_function():
statement
statement
if __name__ == '__main__':
main()
38
Conditionally Executing the
main Function
!!!!!!
39
Conditionally Executing the
main Function
40
Conditionally Executing the
main Function
41
Exercise I
• Write a program that asks the user to enter five test scores.
The program should display a letter grade for each score
and the average test score. Write the following functions in
the program:
– calc_average. This function should accept five test scores as
arguments and return the average of the scores.
– determine_grade. This function should accept a test score as an
argument and return a letter grade for the score based on the
following grading scale:
42
Exercise II
• Write a program that generates 100 random numbers and
keeps a count of how many of those random numbers are
even, and how many of them are odd.
43