0% found this document useful (0 votes)
7 views24 pages

Python Modules: Functions & Usage Guide

This document provides an overview of functions and modules in Python, detailing how to import and use them effectively. It covers various built-in modules such as math, random, time, and datetime, along with examples of their functionalities. Additionally, it explains how to create and save custom functions as modules for reuse in other programs.

Uploaded by

chuyikai85
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)
7 views24 pages

Python Modules: Functions & Usage Guide

This document provides an overview of functions and modules in Python, detailing how to import and use them effectively. It covers various built-in modules such as math, random, time, and datetime, along with examples of their functionalities. Additionally, it explains how to create and save custom functions as modules for reuse in other programs.

Uploaded by

chuyikai85
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

Introduction to Computer Science (I)

Week-6

Function and Module (II)

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.
Introduction to Computer Science (I) 6. Function and Module (II)

◼ Module
In Python, a Module is a file that contains definitions and statements. It can include functions, classes,
variables, and even executable codes. The purpose of a module is to organize code better, making it easier
to maintain and reuse.
1. Importing a module
(1) Import the entire module, use the syntax: import module_name
Execute the function of the imported module, use the syntax: module_name. function_name( )

(2) Import a specific function from a module, use the syntax: from module_name import function_name
Execute this function : function_name(parameter) e.g.
(3) import a module using an alias, use the syntax: import module as alias import math
result = [Link](16)
2. Install a module
from math import sqrt
Syntax for installing and uninstalling Python modules: pip install module_name result = sqrt(16)

pip uninstall module_name import numpy as np 6-2


Introduction to Computer Science (I) 6. Function and Module (II)

math Module
The math module provides mathematical functions, including basic
operations, trigonometric functions, exponential and logarithmic
operations, and constants such as π for performing complex
calculations.
Introduction to Computer Science (I) 6. Function and Module (II)

 math module import math

function of math module illustration


[Link] The constant π, approximately 3.14159
sqrt(x) Returns the square root of x
pow(x, y) Returns x raised to the power of y
exp(x) Returns e raised to the power of x
sin(x) Returns the sine of x (in radians) In Python's math module,
cos(x) Returns the cosine of x (in radians) trigonometric functions such
as sin(), cos(), and tan()
tan(x) Returns the tangent of x (in radians) primarily use radians rather
than degrees.
degrees(x) Converts radians to degrees So you need to convert the
radians(x) Converts degrees to radians. degrees to radians first and
then use the trigonometric
functions. 6-4
Introduction to Computer Science (I) 6. Function and Module (II)

 math module import math

import math
# Calculate the area of a circle
radius = 5
# Calculate the square root of 16
area = [Link] * [Link](radius, 2)
x = 16
print(area)
sqrt_x = [Link](x)
print(sqrt_x)
# Calculate trigonometric functions
angle_rad = [Link](45) # Convert to radians
# Calculate 3 raised to the 4th power
sin_value = [Link](angle_rad)
x=3
print(sin_value)
y=4
power_xy = [Link](x, y)
print(power_xy)

6-5
Introduction to Computer Science (I) 6. Function and Module (II)

random Module
The random module provides functions for generating random numbers
and performing random operations. It is commonly used for simulations
and randomization tasks.

6-6
Introduction to Computer Science (I) 6. Function and Module (II)

random 模組 import random as r

functions in the random module illustration


random() Returns a random float between 0 and 1
randint(a, b) Returns a random integer between a and b
randrange(a, b, c) Returns a random integer between a and b, stepping by c
choice (string) Returns a random element from a sequence
sample(string, n) Returns a sample of n unique elements from a sequence

shuffle(list) Shuffles the elements in a list

uniform(a, b) Returns a random float between a and b

6-7
Introduction to Computer Science (I) 6. Function and Module (II)

Random module_Example : Simple Lottery System


import random as r

# 1. Participant list :
participants = ['Alice', 'Bob', 'Charlie', 'David', 'Eve', 'Frank', 'Grace']

# 2. Shuffle the participant order :


[Link](participants)
print(f" Shuffled participant list : {participants}")

# 3. Select a random winner :


winner = [Link](participants)
print(f" Lucky winner : {winner}")

# 4. Select three random second prize winners from the participants (no duplicates):
second_prize_winners = [Link](participants, 3)
print(f" second prize winners : {second_prize_winners}")
6-8
Introduction to Computer Science (I) 6. Function and Module (II)

random模組_範例 : 簡單的抽獎系統

# 5. Generate a random prize number between 1 and 100:


prize_number = [Link](1, 100)
print(f"Prize number: {prize_number}")

# 6. Generate a random discount value between 10 and 50 (float):


discount_value = [Link](10, 50)
print(f" Discount value: {discount_value:.2f}")

# 7. Simulate a dice roll (1 to 6) :


dice_roll = [Link](1, 6)
print(f" Dice roll result : {dice_roll}")

6-9
Introduction to Computer Science (I) 6. Function and Module(II)

time Module
The time module provides functions for handling operations
related to time, such as getting the current time, calculating
time intervals, and formatting time.

6 - 10
Introduction to Computer Science (I) 6. Function and Module (II)

time module import time

functions in the time module illustration

sleep(n) Pauses the program for n seconds

time() Returns the current time as a timestamp

ctime([timestamp]) Converts a time stamp to a human-readable string

localtime([timestamp]) Returns a time structure based on the passed timestamp

6 - 11
Introduction to Computer Science (I) 6. Function and Module (II)

time module import time

◆ time() ◆ sleep(n) ◆ ctime([timestamp])


import time
import time import time
# Record the start time
start_time1 = [Link]() current_time = [Link]()
start_time1 = [Link]()
for i in range(1000): readable_time = [Link](current_time)
for i in range(1000):
for j in range(1000): print(readable_time)
for j in range(1000):
n=i*j
n=i*j
# Pause the program for 2
# Record the end time
seconds
end_time1 = [Link]()
[Link](2)
# Calculate the total
end_time1 = [Link]()
execution time
print(end_time1 - start_time1)
print(end_time1 - start_time1)

6 - 12
Introduction to Computer Science (I) 6. Function and Module (II)

 localtime() Time information returned by the function

name illustration
tm_year Year (AD) import time
tm_mon Month (1 ~ 12) current_timestamp = [Link]()
tm_mday Day (1 ~ 31) print(f "Current time (number of seconds since January 1st, 1970):
tm_hour Hour (0 ~ 23) {current_timestamp}")

tm_min Minute (0 ~ 59) # 3. Convert time to local time(localtime)


tm_sec Second (0 ~ 60) local_time = [Link](current_timestamp)
Day of the week local_time.tm_year
tm_wday local_time.tm_mon
(Monday=0, Sunday=6)
local_time.tm_mday
tm_yday Day of the year (1–366)
print(f"current local time (localtime): {local_time.tm_year}-
Daylight savings (1 for daylight savings, {local_time.tm_mon}-{local_time.tm_mday}
tm_isdst {local_time.tm_hour}:{local_time.tm_min}:{local_time.tm_sec}")
0 for no daylight savings)

6 - 13
Introduction to Computer Science (I) 6. Function and Module (II)

datetime Module
The datetime module provides tools for working with dates and times,
supporting tasks like getting the current date and time, performing time
arithmetic, formatting output, and converting between strings and date objects.

6 - 14
Introduction to Computer Science (I) 6. Function and Module (II)

datetime module import datetime

date()
datetime time() now()
datetime() strptime()
timedelta() strftime()

functions in the datetime module illustration

date(y, m, d) Represents a date (year, month, day)

time(hr, min, sec) Represents a time (hour, minute, second)

datetime(y, m, d, hr, min, sec) Represents both a date and time

[Link]() Returns the current date and time

6 - 15
Introduction to Computer Science (I) 6. Function and Module (II)

datetime module import datetime


【parameter setting】
days
function of datetime module 說明
seconds
microseconds
milliseconds (Automatically converted to
corresponding microseconds)
Represents a time difference for
timedelta(parameter setting) minutes (Automatically converted to the
performing date arithmetic
corresponding number of seconds)
hours (Automatically converted to the corresponding
number of seconds)
weeks (Automatically converted to the corresponding
[Link] Formats a date/time object into number of days)
(variable, parameter setting) a string
%Y - Year (4 digits)
You need to use %m - Month (2 digits)
[Link]() to %d - Day (2 digits)
Strptime %H - Hour (24-hour format)
obtain the time before you can
(variable, parameter setting) %M - Minute
use strptime() to parse the
string into a date/time object. %S - Second
6 - 16
Introduction to Computer Science (I) 6. Function and Module (II)

datetime module import datetime

import datetime import datetime

# Create a date object # Create a datetime object


d = [Link](2024, 10, 20) dt = [Link](2024, 10, 20, 15, 30, 45)
print(d) # 2024-10-20 print(dt) # 2024-10-20 15:30:45

# Create a time object # Get the current date and time


t = [Link](15, 30, 45) now = [Link]()
print(t) # 15:30:45 print(now)

6 - 17
Introduction to Computer Science (I) 6. Function and Module (II)

timedelta is used to represent the time difference and can be established by setting time parameters.
The following is its parameter format:

[Link](days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

import datetime

# Indicates the time difference between 2 days, 3 hours and 30 minutes


delta = [Link](days=2, hours=3, minutes=30)
Select the required
print(delta) # 2 days, 3:30:00
parameters to use, the
# Create a time difference object rest default to 0!!
delta = [Link](days=5)
# Calculate the date 5 days later
new_date = [Link](2024, 10, 20) + delta
print(new_date) # 2024-10-25
6 - 18
Introduction to Computer Science (I) 6. Function and Module (II)

 strftime()
import datetime

# Get current time


now = [Link]()
# Format the current date and time as "Year-Month-Day Hour:Minute:Second"
formatted = [Link]("%Y-%m-%d %H:%M:%S")
print(formatted) # 2024-10-20 15:30:45

 strptime()
import datetime

# Parse a string "2024-10-20 15:30:45" into a datetime object


date_string = "2024-10-20 15:30:45"
parsed_date = [Link](date_string, "%Y-%m-%d %H:%M:%S")
print(parsed_date) # 2024-10-20 15:30:45
6 - 19
Introduction to Computer Science (I) 6. Function and Module (II)

Custom Functions ( def ) Saved as a Module

6 - 20
Introduction to Computer Science (I) 6. Function and Module (II)

◼ custom functions ( def ) saved as a module

To save a custom function as a module. This allows the function to be reused in other Python programs.

Step 1:Custom functions need to be saved in .py format.

Example : Custom lotto function ([Link])


import random
def lotto(n, m):
'''Define the function of "lotto" lottery, randomly selecting m unique numbers from n numbers.'''
prize = list()
nums = [i for i in range(1, n+1)]
for i in range(m):
n = [Link](nums)
[Link](n)
[Link](n)
return prize
6 - 21
Introduction to Computer Science (I) 6. Function and Module (II)

◼ custom functions ( def ) saved as a module

To save a custom function as a module. This allows the function to be reused in other Python programs.

Step2:Import modules in other Python programs

The module (file) must be in the path specified


by the system.
The system will sequentially search for the
module (file) in the specified path.
You can also put the module and the program
that imports the module in the same folder, it
will definitely be able to be imported.

6 - 22
Introduction to Computer Science (I) 6. Function and Module (II)

◼ custom functions ( def ) saved as a module

To save a custom function as a module. This allows the function to be reused in other Python programs.

Step2:Import modules in other Python programs

import exlotto
nums = [Link](48, 6) #Note here!!!
(1) Import the entire module snums = sorted(nums)
print(snums)

from exlotto import lotto


nums = lotto(48, 6) #Note here!!!
(2) Import a function in the module snums = sorted(nums)
print(snums)

6 - 23
Introduction to Computer Science (I) 6. Function and Module (II)

◼ Import module that includes multiple functions ( def )

Import exlotto, exreciept function in the


prize module.

from prize import exlotto, exreciept


import random import random nums = [Link](48, 6)
def reciept(): def lotto(n, m): snums = sorted(nums)
prize = '' prize = list() print(snums)
nums = [i for i in range(10)] nums = [i for i in range(1, n+1)] s = [Link]()
for i in range(8): for i in range(m): print(s)
n = [Link](nums) n = [Link](nums)
prize += str(n) [Link](n)
return prize [Link](n)
return prize
6 - 24

You might also like