Introduction to Computer Science (I)
Week-5
Function and Module
Yen-Ru Lai
yrlai@[Link]
Department of Civil Engineering, National Chung Hsing University
Copyright © 2024 Yen-Ru Lai, Tzu-Ching Chang, Ching-Mei Tseng, An-ting Chang. All rights reserved. 5-1
Introduction to Computer Science (I) 5. Function and Module
◼ Function
It is a small independent unit of reusable code with specific functions. You can specify its function, as well as the
required input and output. It can encapsulate repetitive logic in a unit, enabling code reuse and improving readability
and maintainability.
1. Internal Scope(內部作用域):
Variables within the function are not visible outside, preventing confusion from global variables. Functions
ensure that internal variables and logic do not affect the external environment.
2. Encapsulation (封裝) :
A function encapsulates specific logic into a block of code, hiding internal details. External users
only need to use the function name to get results.
5-2
Introduction to Computer Science (I) 5. Function and Module
◼ Function
Functions are independent, reusable code units with specific functionality. They allow for customizable inputs
(parameters) and outputs, encapsulating repetitive logic for reuse, improving readability and maintainability.
3. Accepting Parameters:
Functions can accept input parameters to handle different computations or operations based on different circumstances.
4. Returning Results:
Functions can return results of any Python data type, such as numbers, strings, lists, etc. The results can be used for
further processing or display.
5. Recursion:
A function can call itself, a concept known as recursion, which is useful for tasks that can be broken down into similar
sub-tasks.
5-3
Introduction to Computer Science (I) 5. Function and Module
◼ def
In Python, def is the keyword used to define functions. Functions are used to encapsulate reusable code
fragments to avoid writing the same logic repeatedly and improve the readability and maintainability of
the program.
• Functions are used for structured programming.
• By separating programs with the same function, pass in data and return processed results through
function calls.
• As long as a function is written, it can continue to be used to perform the same action without duplicating
the code. If modifications are needed, only the function itself requires changes.
5-4
Introduction to Computer Science (I) 5. Function and Module
1. Definition of Function
A custom function needs to contain two parts, namely 「Function Definition」 and 「Function Call」.
「Function Definition」This is where the function’s functionality is implemented, including input parameters and return results.
「Function Call」 This refers to calling the function in the main program to execute it.
• def : the keyword that defines the function
def function_name(parameter1, • function name: the name of the function , it could be a meaningful
parameter2, ...): name customized by you.
# Function body • parameter : It is the variable passed into the function. The number is
return variable_or_value variable. It can have no parameters or multiple parameters. When
there are multiple parameters, they should be separated by
commas. The right parenthesis must be followed by 「:」
• return : It’s optional and used to return results. If return is not used, the function returns None.
• indentation : Code with the same indentation is the scope of the function. 5-5
Introduction to Computer Science (I) 5. Function and Module
2. Return Values in Functions
When a function needs to return a value, the return directive is used.
Functions without return values don’t need the return statement.
The definition of the function and the format of the return value are as shown in the following table.
Classification Syntax of Function Definition Example
Functions that do not return def function_name (parameter1, parameter2, ...): def hi():
a value print('hi')
Function body
def function_name (parameter1, parameter2, ...): def min(a,b):
if a > b:
Functions that return values Function body return b
return variable_or_value else:
return a
5-6
Introduction to Computer Science (I) 5. Function and Module
3. Function Call
• Functions do not execute upon creation. They must be called in the main program to execute.
• The program passes data into the function through function calls, and the function returns
the results to the calling program after processing. e.g.
First one:
def hi(name="World"):
First one: Syntax for function call that do not return a value
print(f'hi, {name}!')
function_name(parameter1, parameter2 , …) hi("Alice")
Second one :
Second one: Syntax for function call that return values
def min(a,b):
variable = function_name(parameter1 1, parameter1 2 , …) if a > b:
return b
else:
return a
ans = min(5,10)
5-7
Introduction to Computer Science (I) 5. Function and Module
◼ Scope of Functions and Variables
In Python, the scope of variables can be divided into local variables and global variables.
The distinction between these variables mainly depends on the scope in which they are defined, that is,
their scope in the program.
1. Local Variable
• Definition: Local variables define variables inside a function and cannot be accessed outside of the function.
• Scope: The locale variable will be removed once the function executes.
e.g.
def my_function():
x = 10 # x is local variable
print(x)
my_function() # output:10
print(x) # Error because x does not exist outside
the function 5-8
Introduction to Computer Science (I) 5. Function and Module
◼ Scope of Functions and Variables
In Python, the scope of variables can be divided into local variables and global variables.
The distinction between these variables mainly depends on the scope in which they are defined, that is,
their scope in the program.
2. Global Variable
• Definition: Global variables are variables defined outside a function, which apply to the entire program and
can be accessed by all functions.
• Scope : Global variables exist throughout the execution of the program until the end of the program.
e.g. x = 20 # x is global variable
def my_function():
print(x) # Global variables can be accessed within a function
my_function() # output:20
print(x) # output:20 5-9
Introduction to Computer Science (I) 5. Function and Module
◼ Scope of Functions and Variables
• Variable Shadowing:When local and global variables have the same name, the function will
prioritize the local variable.
• Within the function, local variables are used; outside the function, because the local variables do
not exist, global variables are used.
3. Check through where the variable is defined
Use the globals() keyword to declare a variable, which is a global variable.
Otherwise, it will be treated as a local variable even if the name is the same.
5 - 10
Introduction to Computer Science (I) 5. Function and Module
◼ Example【Shopping Cart System】
# Global variable
cart = [] # shopping cart (blank list)
total_price = 0 # total price(global variable)
def add_to_cart(item, price):
"""Add the product to the shopping cart and update the total price of the global variable"""
global total_price # Use the global keyword to modify global variables
[Link](item) # Add items to shopping cart (cart is a global variable in this scope)
total_price += price # Update total price
print(f“Added{item} to the cart,price:{price} dollars")
def remove_from_cart(item, price):
"""Remove item from the shopping cart and update the total price of the global variable """
global total_price
if item in cart:
[Link](item) # Remove items
total_price -= price # Reduce total price
print(f" Removed{item} ,price:{price} dollars")
else:
print(f"{item} not in cart")
5 - 11
Introduction to Computer Science (I) 5. Function and Module
◼ Example【Shopping Cart System】
def show_cart():
"""Show items in shopping cart and the total price"""
print(" items in shopping cart:")
for item in cart:
print(f"- {item}")
print(f“total price:{total_price} dollars")
def apply_discount(discount):
"""Apply discount, calculated only within the function, without
modifying global variables"""
discounted_price = total_price * (1 - discount / 100) # local variable
print(f"Price after applying discount:{discounted_price} dollars")
return discounted_price
5 - 12
Introduction to Computer Science (I) 5. Function and Module
◼ Example【Shopping cart system】
# Test program functionality
print("Add product to cart:")
add_to_cart("phone", 10000) # add phone
add_to_cart("laptop", 50000) # add loptop
print("\nshow_cart:")
show_cart()
print("\nremove product:")
remove_from_cart("phone", 10000) # remove phone
print("\n show_cart :")
show_cart()
print("\n apply_discount ( Does not affect the total price ):")
apply_discount(10) # Apply 10% discount, only calculate global variables without modifying them
print("\nShow final status of cart :")
show_cart()
5 - 13
Introduction to Computer Science (I) 5. Function and Module
◼ Example【Multi-point Bearing Calculation】
Question : Define a function to calculate the bearing angle between two points.
import math
def bearing(x1, y1, x2, y2):
delta_x = x2 - x1
delta_y = y2 - y1
angle_radians = math.atan2(delta_y, delta_x)
angle_degrees = [Link](angle_radians)
return angle_degrees if angle_degrees >= 0 else angle_degrees + 360
def calculate_bearings(points):
bearings_list = []
for i in range(len(points) - 1): points = [(-4, 16), (4, 7), (18, 6), (12, 10)] # List of point coordinates
x1, y1 = points[i] bearings = calculate_bearings(points)
x2, y2 = points[i + 1]
bearing_angle = bearing(x1, y1, x2, y2) # Output the bearings
bearings_list.append(bearing_angle) for i, bearing_angle in enumerate(bearings):
return bearings_list print(f"Bearing from Point {i+1} to Point {i+2}: {bearing_angle:.2f} degrees")
5 - 14
Introduction to Computer Science (I) 5. Function and Module
◼ Example Illustration【Multi-point Bearing Calculation】
Question : Define a function to calculate the bearing angle between two points.
import math
def bearing(x1, y1, x2, y2):
delta_x = x2 - x1
delta_y = y2 - y1
angle_radians = math.atan2(delta_y, delta_x)
angle_degrees = [Link](angle_radians)
return angle_degrees if angle_degrees >= 0 else angle_degrees + 360
def calculate_bearings(points):
bearings_list = [] #Initialize an empty list to store calculation results
for i in range(len(points) - 1): #This loop will traverse each pair of adjacent points, and ensure that the loop
x1, y1 = points[i] only traverses adjacent points to avoid exceeding the boundary
x2, y2 = points[i + 1]
bearing_angle = bearing(x1, y1, x2, y2)
bearings_list.append(bearing_angle) #Store each calculated azimuth into bearings_list
return bearings_list
5 - 15
Introduction to Computer Science (I) 5. Function and Module
◼ Example Illustration【Multi-point Bearing Calculation】
Question : Define a function to calculate the bearing angle between two points.
points = [(-4, 16), (4, 7), (18, 6), (12, 10)] # List of point coordinates
bearings = calculate_bearings(points)
# Output the bearings
for i, bearing_angle in enumerate(bearings):
print(f"Bearing from Point {i+1} to Point {i+2}: {bearing_angle:.2f} degrees")
# The for loop outputs the results.
This program will output the azimuth angle between each pair of adjacent points in turn,
and use enumerate(bearings) to obtain the azimuth angle and its corresponding index.
5 - 16
Introduction to Computer Science (I) 5. Function and Module
◼ Python Built-in Functions
Function Action Example Result
str(x) Convert x to string str(78) "78"
float(x) Convert x to float float(“42") 42.0
int(x) Convert x to integer int(49.77) 49
hex(x) Convert x to hexadecimal hex(34) 0x22
abs(x) Get the absolute value of x abs(-23) 23
len(x) Get the number of elements len([1,3,5,7]) 4
max(list) Get the maximum value in a list of numbers max(1,3,5,7) 7
min(list) Get the minimum value in a list of numbers min(1,3,5,7) 1
pow(x, y) Get x raised to the power of y pow(2,3) 8
round(x) Get an approximate value of x by rounding round(45.8) 46
sorted(list) Sort from small to large sorted([3,1,7,5]) [1,3,5,7]
sum(list) Calculate the sum of the elements of a list sum([1,3,5,7]) 16
5 - 17
Introduction to Computer Science (I) 5. Function and Module
◼ Python Built-in Functions
* Please note the syntax *
1. power : pow(x, y)
• The syntax for computing x raised to the power of y is: pow(x, y)
• The syntax for calculating the remainder of x raised to the yth power divided by z is:pow(x, y, z)
(Restrictions x, z must be integers, y must be non-negative integers)
2. approximation : round(x, n)
• The syntax for approximating x to n decimal places is : approximation = round(x, n)
5 - 18
Introduction to Computer Science (I) 5. Function and Module
◼ Python Built-in Functions
* Note the syntax *
3. maximum : max()
• The max() function can get the maximum value of a group of values. The brackets can be multiple parameters or a
list (or a tuple).
• The syntax is: max(parameter1, parameter2,...) or max(list)
4. minimum: min()
• The syntax is the same as the max() function. The syntax is: min(parameter1, parameter2,...) or min(list)
5. summarize sum()
• The sum() function obtains the sum of a group of values. Inside the brackets is a list (or tuple).
• The syntax is: sum (list)
5 - 19