Bioinformatics Laboratory at BiUH.
Core Values: Respect, Reflection, Communication, Commitment.
Section 1. Understanding Libraries, Packages, and Modules
Section 2. Python Standard Library
Section 3. Third-Party Libraries and pip
Section 4. Practical Application - Weather Reporter
Section 5. Practical Application - File Backup Helper
.py filemath, random, datetime, osimport math
print("Pi is approximately " + str(math.pi))
print("Square root of 16: " + str(math.sqrt(16)))
help('modules')
Get the whole toolbox:
import math
print("2^5 = " + str(math.pow(2, 5)))
Grab just what you need:
from random import randint
print("Random dice roll: " + str(randint(1, 6)))
Make it short:
import pandas as pd
data = {'Birds': ['Eagle', 'Penguin'], 'Speed': [320, 8]}
df = pd.DataFrame(data)
print(df)
| Method | Advantage | Use Case |
|---|---|---|
| Full Import | Prevents name conflicts | Large libraries, avoid namespace pollution |
| Specific Import | Cleaner code, less typing | Only need 1-2 functions from module |
| Alias Import | Saves typing long names | Frequently used libraries like pandas/numpy |
Combine different approaches:
from math import sqrt as sq
print("Square root of 121: " + str(sq(121)))
math - Mathematical functionstime - Time-related functionsrandom - Random number generationos - Operating system interfacedatetime - Date and time manipulationshutil - High-level file operationsimport datetime
now = datetime.datetime.now()
print("Current time: " + str(now))
Output format: Year/Month/Day Hour:Minute:Second.Microsecond
future_date = now + datetime.timedelta(days=3)
print("Date after 3 days: " + str(future_date.date()))
dayshoursminutessecondsweekspandas - Data manipulation and analysisrequests - HTTP library for web communicationnumpy - Numerical computing$ pip3 --version
pip 24.0 from ... (python 3.7)
$ pip3 install requests
Collecting requests...
Successfully installed requests-2.31.0
$ pip3 list
Package Version
---------- -------
pip 21.2.4
requests 2.31.0
setuptools 57.4.0
$ pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple pandas
$ pip3 config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
Creates ~/.config/pip/pip.conf file
import requests
response = requests.get("https://www.baidu.com")
print("Status Code: " + str(response.status_code))
print("Response Text: " + response.text[:100] + "...")
import requests
city = "Beijing"
url = "http://wttr.in/" + city + "?format=3"
response = requests.get(url)
print("Weather in " + city + ": " + response.text)
$ pip3 install --upgrade requests
$ pip3 install requests==2.31.0
Combine web data fetching and time handling to create a weather reporting tool.
requests - Fetch weather data from websitesdatetime - Handle current time displayimport datetime
current_time = datetime.datetime.now()
formatted_time = current_time.strftime("%H:%M")
print("Hello! It's " + formatted_time + " now!")
When using datetime, be aware of your system’s time zone settings. The example uses local system time.
import requests
def get_weather(city):
url = "http://wttr.in/" + city + "?format=%t+%C"
response = requests.get(url)
return response.text
print(get_weather("London"))
%t - Temperature%C - Weather condition%h - Humidity%w - Wind speedimport datetime
import requests
def get_weather(city):
url = "http://wttr.in/" + city + "?format=%t+%C"
response = requests.get(url)
return response.text
def weather_report(city):
time_now = datetime.datetime.now().strftime("%H:%M")
weather = get_weather(city)
return "[" + time_now + "] Weather in " + city + ": " + weather
print(weather_report("NewYork"))
If you are in Beijing but checking New York weather, the time displayed will be Beijing Time, not local New York time.
Automate file copying operations for backup purposes.
os - Handle file paths and directory operationsshutil - High-level file operations (copy, move, etc.)import os
my_folder = "documents"
if not os.path.exists(my_folder):
os.makedirs(my_folder)
print("Created " + my_folder + "!")
# Join path components
full_path = os.path.join("backup", "file.txt")
print(full_path)
import os
import shutil
def backup_files(src_folder, dst_folder):
# Create destination if it doesn't exist
if not os.path.exists(dst_folder):
os.makedirs(dst_folder)
# Copy all .txt files
for file in os.listdir(src_folder):
if file.endswith(".txt"):
src_path = os.path.join(src_folder, file)
dst_path = os.path.join(dst_folder, file)
shutil.copy2(src_path, dst_path)
print("Copied " + file + "!")
# Usage example
backup_files("notes", "backup")
copy2() - Preserves metadata (timestamps, permissions)copy() - Only copies file contentEnd