[go: up one dir, main page]

0% found this document useful (0 votes)
11 views37 pages

Computer Basic Knowledge

This document covers user-defined functions in Python, detailing their syntax, variable scope, and return values. It includes practical tasks for creating functions, such as drawing circles and controlling a servo motor based on light intensity. The document also discusses local and global variables, providing exercises and enrichment activities for further learning.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views37 pages

Computer Basic Knowledge

This document covers user-defined functions in Python, detailing their syntax, variable scope, and return values. It includes practical tasks for creating functions, such as drawing circles and controlling a servo motor based on light intensity. The document also discusses local and global variables, providing exercises and enrichment activities for further learning.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

(Teacher’s Version)

PA05 Unit3
User-Defined Functions
3.1 User-Defined Functions

3.2 Scope of Variables

3.3 User-Defined Functions with Return Values


Contents
Learning Objectives
3.1 1. User-Defined Functions

3.2 2. Scope of Variables

3.3 3 . User-Defined Functions with Return Values

Practice Zone 1. Consolidation 2. Practical exercise 3. Enrichment


Is there any technique Functions can help, as
that can help us develop they can break down a
programs as they turn huge program into smaller
out to be more and more subprograms that allow
complex? easier maintenance and
repeated use.
3.1 User-Defined Functions
Functions have been introduced in Unit 1. In simple terms, they are
subprograms that execute a predefined set of tasks and called by
their names. As program code can be reused more easily with
functions, the latter can make a program more organised and
readable, and easier to upgrade and maintain.

Python offers many built-in functions such as print() that can be


called directly. We may also define custom functions known as
user-defined functions by the syntax below:
自訂函式

A function without parameters has a single execution result only, whereas a


function with parameter(s) can have different execution results according to the
data passed to it.
1. The first syntax line is the function header. The naming rule for
functions is the same as that for variables (1.3.2). If the function has no
parameter, the first line is written as “define function name():”.

2. The function body is the program block of actions to be done by the


function.

3. A parameter is a variable used in the function body. When functions


with parameters are called, the program will pass to the parameters data
(like numbers) which determine the execution results.

4. A function may include multiple parameters in its brackets separated by


commas(,).
 Task 1: Drawing a circle of a specific radius with a user-defined
function

Complete the following program for drawing a circle of a specific


radius and save it as “u3_task1.py”. Then run and test it.

3.1 Execution result of


Task 1 program

In Python, modules such as the turtle module in Unit 2 are used to group related functions.
They are imported with an import statement. We may then access a particular function in it
with t h e module name a n d a dot(.). In task 1, for example, functions in the turtle module are
called, such as Screen(), pen-size(), pencolor() and circle().

To group modules, libraries are created. Examples include Python Standard Library and
pyfirmata module.
1. Modify the program of “u3_task1.py” so that it can output the
execution result as shown in Figure 3.2.
Program

3.2

Reference answer 2
Hint:
1. Note the four circles share the same starting and ending point of drawing, with adjacent
circles differing from each other by 90 degrees radially.
2. Use the function left() or right() to turn the pen by a certain leftward or rightward angle
respectively.
3. Use a user-defined function repeatedly or place it in a loop.
 Task 2: Drawing a circle of a user-input radius with a user-
defined function

Complete the following program for drawing a circle of a user-input


radius and save it as “u3_task2.py”. Then run and test it.

The function in Task 1 has no parameter, but that in Task has one which passes data (user-input
radius) to the function. The data will determine the execution result of the function body.

The program prompts the user to enter the radius value, which is converted into a string by the
input() function. The int() function is needed to convert it to an integer value.
2. Modify the program of “u3_task2.py” so that the user-defined function for
drawing a circle includes two parameters, namely circle_size and pen_color,
and prompts the user to enter the radius value and the pen colour.
3.2 Scope of Variables 局部變量
執行期間錯誤
Variables created in user-defined functions are known as local variables,
which are valid only in the function body. Any use of it beyond this scope will
lead to a runtime error. As for variables created in the main program, known
as global variables, their scope covers the whole program (including the body
of any user-defined function). 全程變量

 Task 3: Testing a program which involves the use of a local variable


outside the function body

Create the following program and save it as “u3_task3.py”. What would be its
execution result?

3.3

After entering a number (5) as prompted, an error message is shown.


____________________________________________________________
(Reference answer)
____________________________________________________________
• In the program, area is a local variable and input_len is a global one. So the scope of area is valid only
within the body of the user-defined function square_area. It is invalid in other parts of the program.
 Task 4: Testing a program which involves the use of a global
variable within the body of a user-defined function

Create the following program and save it as “u3_task4.py”. What


would be its execution result?

3.4

After entering the number 5 as prompted, the message “Area of


______________________________________________________
square is 25” is shown without error message. (Reference answer)
______________________________________________________

• As input_len is defined in the main program, it is a global variable and can be used and
assigned new values anywhere the program.
3.3 Functions with a Return Value
Apart from passing the main program’s data to user-defined functions to
process through parameters, we may pass data (return value) back to the 返回值
main program from user-defined functions. To create a function with a return
value, add a return statement to the function body, which is usually made up
of the Python keyword return and an expression containing variables and/or
values. The return value is the value of the expression.

Note: Any code in a function body after the final return statement will not be executed. So the
return statement is normally placed in the last line of the function body.

 Task 5: Finding the maximum of two values with a user-defined function

Complete the following program for finding the maximum of two values and
save it as “u3_task5.py”. Then run and test it.
• The function maximum() takes
two values corresponding to its
two parameters and determines
which value is greater. If the
value of the parameter x is
greater, that value is the return
value passed from the function,
Otherwise, the value of the
parameter y is greater is the
return value.
3. Complete the following program for finding the highest common factor of
two input integers by the Euclidean algorithm and save it as “u3_q3.py”. Then
run and test it.

• The Euclidean algorithm is one for finding the highest common factor (HCF) of two integers. Algorithm: Divide the
larger integer by smaller one. Then divide the previous divisor by the remainder. Repeat the above step until the
remainder is zero. The last divisor is the HCF of the two integers.

• If the integer value of variable Num1 is smaller than that of variable Num2, Num1%Num2 would return the value
of Num1. Then the values of the two variables will be swapped. In the second iteration, the value of Num1 will be
larger than that of Num2 and the program will start executing the Euclidean algorithm.
 Task 6: Using a user-defined function in programming
a light-controlled servo motor
Set up the circuit as below in which the Arduino board is connected to a servo
motor and a light-dependent resistor (LDR) through the pins D10 and A0
respectively.

• An Arduino UNO board has 6 pins for


analog input, namely A0 to A5, which
are normally used for reading data of
sensor components (e.g. LDR)

• Suggested components:
1. SG90 180° servo motor
2. LDR
3. 10kΩ resistor

3.5

In this task, we will use a Python user-defined function in designing a program to


control the rotation angle of the servo arm of a servo motor based on the light
intensity detected by an LDR.
This program will keep reading the LDR-detected light intensity data. If a certain
intensity value is exceeded, the servo arm will turn by 90°. Otherwise, it remains at
or returns to the 0° position.
 Create the following program, save it as “u3_task6.py” and run it.
Observe the response of the servo motor in different light intensities.

Code Description (numbers in brackets are line numbers)

(1) Import util module for reading analog input data.


(6) Define Pin D10 to control the servo motor, s denoting
servo mode. (Note: use a PWM pin for servo control given
its analog output)
(7) Define Pin A0 as analog (a) input (i).
(8-9) Iterator() of util avoids overflow errors as the board
keeps sending LDR data to the serial port.
(10) Wait 5s for pyfirmata and the Arduino board to
synchronise.
(12-14) Create a user-defined function with a parameter
(move_servo) to control servo arm’s rotation angle.
(16) Repeat running the following code in an infinite loop.
(17-18) The data values, lying between 0 to 1, are
multiplied by 1,000 for integer output.
(19-22) As the light intensity exceeds 100, the servo arm is
instructed to remain at or rotate to the 90° position;
otherwise, the 0° position. Note 1
(23-26) The user is prompted to input the letter n for
program termination. Upon its input, the servo arm returns
or remains at the 0° position and the loop is terminated
instantly, thus ending the program.
3.6
4. Modify Task 6 by adding a servo
Program
motor and connecting it to Pin D9
of the Arduino board, and modify
the program “u3_task6.py” as
follows: As the light intensity value
is below 100, one servo arm
remains at or rotates to the 90°
position, another 0° position. As
the light intensity value exceeds
100, vice versa.

Hint: In the program, define Pin D9 to


control the added servo motor. Modify
the function move_servo so that it can
simultaneously control the servo arms
of both servo motors to move to
different positions as designated by the
value of the parameter.
User-Defined Functions
1. Python offers many built-in functions such as print() that can be called
directly. We may also define custom functions known as user-defined
functions

2. The syntax of self-defined function is as follows:


def function name(parameter):
function body

3. A parameter is a variable used in the function body. When functions


with parameters are called, the program will pass to the parameters
data (like numbers) which determine the execution results.

4. A function may include no parameter or multiple parameters.


Scope of Variables
5. Variables created in user-defined functions are known as local
variables which are valid only in the function body. Any use of it beyond
this scope will lead to a runtime error.

6. Any variable created in the main program is known as a global variable


with its scope covering the whole program.

User-Defined Functions with Return Values


7. We may pass data (return value) back to the main program from
user-defined functions.

8. To create a function with a return value, add a return statement to the


function body, which is usually made up of the Python keyword return
and an expression containing variables and/or values. The return value
is the value of the expression.
A. Consolidation
1. Which of the following will NOT make a program more concise and
organised?
A. Variable
B. Function
C. Module D
D. Fewer blank characters

2. Which of the following must be included in defining a function?


A. Parameter(s)
B. Return value(s)
C. r e t u r n statement D
D. function name
3. Refer to Task 6 of this Unit. What is the meaning of the letter a in the
command board.get_pin('a:0:i')?
A. analog
B. active
C. Arduino
A
D. automatic

4. Refer to Task 6 of this Unit. What is the meaning of the letter i in the
command board.get_pin('a:0:i')?
A. identifier
B. import
C. I
D. import B
B. Practical Exercise
1. Which two types of variables in terms of scope?
____________________________________________________________
Local variables and global variables.

2. Name any THREE built-in Python functions.


print (), input(), int()
____________________________________________________________
3. Write down the output result upon execution of the program below.

3.7

False
__________________________
C. Enrichment
1. Design a Python program that contains a self-defined function for
outputting a random integer between 0 and 100 inclusive. The program
will prompt the user to enter a positive integer as the number of random
integers to be generated. If the user enters 5, the program will generate 5
random numbers.
(Hint: There is a module in Python Standard Library, namely random,
which includes a function randint(a,b) that generates a random integer
between a and b inclusive.)

2. Design a Python program that contains a user-defined function. The


program will prompt the user to input an odd number n. Upon its input,
the sum of the arithmetic sequence 1, 3, 5, …, n will be computed.
Program file: u3_task1-e.py
Program file: u3_q1.py
Reference answer 2:

import turtle as t
def draw_circle():
t.Screen().bgcolor('black')
t.pensize(2)
t.pencolor('yellow')
t.circle(40)
for i in range(4):
draw_circle()
t.right(90)
Program file: u3_task2.py
Program file: u3_q2.py
Program file: u3_task3.py
Program file: u3_task4.py
Program file: u3_task5.py
Program file: u3_q3.py
Program file: u3_task6.py
Note 1:

The threshold value of 100 may be adjusted as needed. It is


suggested that a low intensity value be obtained by shielding the
LDR with a hand, and a high one by shining a torch at it.
Program file: u3_q4.py
Program file: u3_ex1.py
Program file: u3_ex2.py

You might also like