Bioinfo Lab

Bioinformatics Laboratory at BiUH.

Core Values: Respect, Reflection, Communication, Commitment.

Main Page   |   Util & Src   |   Contact


Loading......

Password


Content:

Section 1. Introduction to Function & Module

Section 2. Function Basic Syntax

Section 3. Advanced Parameters & Return Values

Section 4. Python Modules System

Section 5. Practical Python Examples for Beginners


 

Section 1. Introduction to Function & Module

← Prev | Home | Next →
 


1.1. Functions: Like a Microwave Preset Button

Real-life analogy:

  • Preset buttons = Predefined functions
  • “Popcorn” button = def popcorn_mode()
  • “Beverage” button = def reheat_drink()

Python example:

def start_microwave(preset):
    if preset == "popcorn":
        print('heat for 180 seconds')
    elif preset == "beverage":
        print('heat for 45 seconds')

start_microwave("popcorn")

← Prev | Home | Next →
 


1.2. Why do We Need Functions

Problem without functions:

# Making 3 sandwiches
print("1. Get bread")
print("2. Add filling")
print("3. Close sandwich")
print("------")
print("1. Get bread")
print("2. Add filling")
print("3. Close sandwich")
print("------")
print("1. Get bread")
print("2. Add filling")
print("3. Close sandwich")

← Prev | Home | Next →
 


1.3. Creating Our First Function

Solution with functions:

def make_sandwich():
    print("1. Get bread")
    print("2. Add filling")
    print("3. Close sandwich")
    print("------")

make_sandwich()
make_sandwich()
make_sandwich()

← Prev | Home | Next →
 


1.4. Making Functions Flexible

Adding parameters:

def make_sandwich(filling):
    print("Making " + str(filling) + " sandwich:")
    print("1. Get bread")
    print("2. Add " + str(filling))
    print("3. Close sandwich")
    print("------")

make_sandwich("ham")
make_sandwich("cheese")

← Prev | Home | Next →
 


1.5. Modules: Like Game Sound Library

Real-life example:

  • Game sound module = import sound_effects
  • Ready-to-use sounds = jump_sound(), explosion_sound()

Simple Python example:

# sound_module.py
def play_jingle():
    print("🎵 Happy tune playing! 🎵")

# main.py
import sound_module
sound_module.play_jingle()

← Prev | Home | Next →
 


1.6. Building Our Own Module

Create kitchen.py:

def microwave_beep():
    print("BEEP! BEEP! BEEP!")

def oven_timer():
    print("DING! Food is ready!")

Use it:

import kitchen
kitchen.microwave_beep()
kitchen.oven_timer()

← Prev | Home | Next →
 


1.7. Example: Cooking Module

Complete example:

# In cooking_module.py
def prepare_dish(dish_name):
    print("Preparing " + str(dish_name) + "...")
    print("1. Gather ingredients")
    print("2. Follow recipe steps")

# In main program
import cooking_module
cooking_module.prepare_dish("pasta")
cooking_module.prepare_dish("salad")

← Prev | Home | Next →
 


1.8. Example: Game Sounds

# sound_effects.py
def laser_blast():
    print("PEW! PEW! ")

def power_up():
    print(" ENERGY RESTORED!")

# game.py
import sound_effects
sound_effects.laser_blast()
sound_effects.power_up()

← Prev | Home | Next →
 


1.9. Key Takeaways

  1. Functions are like preset shortcuts
  2. Parameters make functions flexible
  3. Modules help organize code
  4. Import lets reuse code
  5. Combine functions/modules for complex programs

← Prev | Home | Next →
 

Section 2. Function Basic Syntax

← Prev | Home | Next →
 


2.1. What is a Function?

Like a recipe:

  1. Receive ingredients (parameters)
  2. Follow steps (code block)
  3. Give result (return value)

← Prev | Home | Next →
 


2.2. Function Structure

def magic_oven(ingredient):  # Function header
    output = str(ingredient) + " cookie" # Function body
    return(output)

Three essential parts:

  1. def statement with function name
  2. Action-performing code block
  3. return the result (optional)

← Prev | Home | Next →
 


2.3. Demo 1: Greeting

def greet(name):
    print("Hello, " + str(name))

greet("Alice")  # Output: Hello, Alice!
greet("Bob")    # Output: Hello, Bob!

← Prev | Home | Next →
 


2.4. Shape-Shifting Greetings (Multiple Parameters)

def flexible_greet(name, greeting):
    print(str(greeting) + ' ' + str(name) + '!')

flexible_greet("Charlie", "Good morning")
flexible_greet("Diana", "Ni hao")
flexible_greet("Eric", "Guten Tag")

Parameters order matters!

(greeting, name) vs (name, greeting)


← Prev | Home | Next →
 


2.5. Calculator Function (Return Value)

def circle_area(radius):
    area = 3.14 * radius ** 2
    return(area)

print(circle_area(5))
print("Pizza area: " + str(circle_area(30)))

pizza_price = circle_area(30) * 0.02

← Prev | Home | Next →
 


2.6. Common Mistakes

Case 1: Missing Colon

# Wrong
def bad_function()
    print("Oops")

# Right
def good_function():
    print("Yay!")

Case 2: Wrong Indentation

# Wrong
def messy_function():
print("No indent!")

# Right
def clean_function():
    print("Perfect!")

← Prev | Home | Next →
 


2.7. Parameter-Free Functions

import datetime

def show_time():
    now = datetime.datetime.now()
    print("Current time: " + str(now.hour) + ':' + str(now.minute))

show_time()

← Prev | Home | Next →
 


2.8. Multi-Parameter Function (BMI)

def calculate_bmi(weight, height):
    """Calculate Body Mass Index"""
    bmi = weight / (height ** 2)
    return(bmi)

print("BMI:", calculate_bmi(70, 1.75))
print("BMI:", calculate_bmi(65, 1.68))

Health tip:

Normal BMI range: 18.5 - 24.9

Question: BMI and weight => height

Question: “x^1/2” vs. “x^(1/2)”

Question: How can we check the correctness of “BMI and weight => height”?


← Prev | Home | Next →
 


2.9. Function Superpowers

  1. Reusable code blocks
  2. Clear program structure
  3. Easy error tracking
  4. Team collaboration

← Prev | Home | Next →
 

Section 3. Advanced Parameters & Return Values

← Prev | Home | Next →
 


3.1. Positional vs Keyword Arguments

Pizza Ordering System Example

def make_pizza(size, toppings):
    print("Making " + str(size) + "cm pizza with:")
    for topping in toppings:
        print(topping)

# Positional arguments
make_pizza(30, ["mushrooms", "olives"])

# Keyword arguments
make_pizza(toppings=["cheese"], size=20)

← Prev | Home | Next →
 


3.2. When to Use Keyword Arguments?

  1. When passing many parameters
  2. When parameters have default values
  3. To improve code readability

Try this bad example:

# Confusing positional arguments
make_pizza(["pepperoni"], 25)

← Prev | Home | Next →
 


3.3. Default Parameters

Shipping Cost Calculator

def calculate_shipping(weight, base_fee=5.0):
    price = weight * 1.2 + base_fee
    return(price)

print(calculate_shipping(3.5))       # Uses default base_fee
print(calculate_shipping(2.0, 4.0))

← Prev | Home | Next →
 


3.4. Multiple Return Values

Box Dimension Calculator

def box_calculator(length, width, height):
    volume = length * width * height
    surface = 2 * (length*width + length*height + width*height)
    return(volume, surface)  # Returns a tuple!

dimensions = box_calculator(5, 3, 2)
print("Volume: " + str(dimensions[0]) + ", Surface: " + str(dimensions[1]))

← Prev | Home | Next →
 


3.5. Unpacking Return Values

# Direct unpacking
vol, surf = box_calculator(2, 2, 2)
print("Perfect cube: " + str(vol) + " cubic units")

# Works with different variable names
v, s = box_calculator(1, 3, 5)

← Prev | Home | Next →
 


3.6. Variable Scope Experiment

temperature = 25  # Global variable

def adjust_temp():
    temperature = 18  # Local variable
    print("Inside: " + str(temperature) + "°C")

adjust_temp()
print("Outside: " + str(temperature) + "°C")  # Still 25

← Prev | Home | Next →
 


3.7. Global Keyword Demo

score = 0

def update_points():
    global score
    score = score + 10
    print("New score: " + str(score))

update_points()  # Now modifies the global variable

print(score)

← Prev | Home | Next →
 


3.8. Good Function Names

# Good examples
def calculate_tax(income):
def get_user_profile(id):
def convert_to_fahrenheit(celsius):

# Bad examples
def tax(inc):          # Too vague
def user(id):          # Verb missing
def temp_conv(c):      # Unclear abbreviation

← Prev | Home | Next →
 


3.9. Function Name Checklist

  1. Use underscore separation
  2. Be specific but concise
  3. Keep under 3 words when possible

← Prev | Home | Next →
 


3.10. Summary

Key concepts covered:

  1. Argument types (positional/keyword)
  2. Default parameter values
  3. Returning multiple values
  4. Variable scope
  5. Naming best practices

← Prev | Home | Next →
 

Section 4. Python Modules System

← Prev | Home | Next →
 


4.1. Today’s Learning Goals

  • Understanding different import methods
  • Working with Python standard libraries
  • Creating and using custom modules
  • Namespace concept

← Prev | Home | Next →
 


4.2. Basic Module Import Methods

Full Module Import

import math

print(math.sqrt(25))  # 5.0
print(math.pi)        # 3.141592653589793

![Down Arrow] Key points:

  • Access elements with dot notation
  • Avoids naming conflicts

Specific Function Import

from random import randint

lottery = [randint(1, 50) for _ in range(6)]
print("Winning numbers: " + str(lottery))

Example output:

Winning numbers: [14, 37, 5, 23, 42, 19]

![Warning] Be careful with name collisions!


← Prev | Home | Next →
 


4.3. Math Library in Action

import math

a = 3
b = 4
c = math.sqrt(a**2 + b**2)
print("The hypotenuse is: " + str(c))

Output:

The hypotenuse is: 5.0

Question: change f-string (f”The hypotenuse is: {c}”) into “+” format.


← Prev | Home | Next →
 


4.4. Random Library Fun

from random import choice

participants = ["Alice", "Bob", "Charlie", "Diana"]
winner = choice(participants)
print("Congratulations " + winner + "!")

Possible output:

Congratulations Charlie!

← Prev | Home | Next →
 


4.5. Time Library Demo

import time

print("Starting countdown:")
for i in range(5, 0, -1):
    print(i)
    time.sleep(1)

print("Blast off! ")

← Prev | Home | Next →
 


4.6. Creating Your First Module

  1. Create mymodule.py:
def greet(name):
    return "Hello " + name + ", from my module!"
  1. In main program:
import mymodule

print(mymodule.greet("Sarah"))

← Prev | Home | Next →
 


4.7. Understanding Namespaces

import math
import mymath  # Hypothetical custom math module

print(math.sqrt(16))  # 4.0
print(mymath.sqrt(16)) # Maybe different implementation

![Toolbox Analogy] Each module is like a separate toolbox


← Prev | Home | Next →
 


4.8. Exploring Third-Party Libraries

# requests example
import requests

response = requests.get("https://www.bioinfo-lab.com/")
print("Status code: " + str(response.status_code))
print("Response time: " + str(response.elapsed.total_seconds()) + "s")

← Prev | Home | Next →
 


4.9. Module Search Path

import sys

print("Python looks in these locations:")
for path in sys.path:
    print("- " + str(path))

← Prev | Home | Next →
 


4.10. Import Best Practices

  1. Keep imports at top of file
  2. Use aliases for long names:
import numpy as np
import pandas as pd

← Prev | Home | Next →
 

Section 5. Practical Python Examples for Beginners

← Prev | Home | Next →
 


5.1. Roadmap

  1. Auto-generated Password Program
  2. Simple Calculator
  3. Temperature Conversion System

← Prev | Home | Next →
 


5.2. Example 1: Password Generator (1/2)

Problem: Create random secure passwords

import random

def generate_password(length=8):
    chars = "abcdefghijkmnpqrstuvwxyz23456789"
    this_password = ''
    i = 1
    while(i <= length):
        this_password = this_password + random.choice(chars)
        i = i + 1
    return(this_password)

← Prev | Home | Next →
 


5.3. Example 1: Password Generator (2/2)

Usage:

print(generate_password())   # Example: 'a3x7bk9m'
print(generate_password(12)) # Example: 'wxn58k2q9yr7'

Question: how can we add random uppercase and lowercase characters?

Hint: random.random(), lower(), upper()


← Prev | Home | Next →
 


5.4. Example 2: Simple Calculator (1/2)

Core logic:

def calculator(a, b, operator="+"):
    if operator == "+":
        return a + b
    elif operator == "-":
        return a - b

Question: how can we add “*” and “/”?


← Prev | Home | Next →
 


5.5. Example 2: Simple Calculator (2/2)

Using our calculator:

print(calculator(5, 3))           # 8 (uses default +)
print(calculator(5, 3, "-"))      # 2
print(calculator(2.5, 4, "+"))    # 6.5

← Prev | Home | Next →
 


5.6. Example 3: Temperature Converter (1/2)

Conversion formulas:

Celsius to Fahrenheit: (C × 9/5) + 32
def c_to_f(c):
    return (c * 9/5) + 32

← Prev | Home | Next →
 


5.7. Example 3: Temperature Converter (2/2)

Test conversions:

print(c_to_f(0))
print(c_to_f(100))

Question: write the function “f_to_c”

Question: How can we check the correctness of “f_to_c”


← Prev | Home


End