Server Info & Course Info
def popcorn_mode()
def reheat_drink()
def start_microwave(preset):
if preset == "popcorn":
print('heat for 180 seconds')
elif preset == "beverage":
print('heat for 45 seconds')
start_microwave("popcorn")
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")
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()
Adding parameters:
def make_sandwich(filling):
print(f"Making {filling} sandwich:")
print("1. Get bread")
print("2. Add "+ str(filling))
print("3. Close sandwich")
print("------")
make_sandwich("ham")
make_sandwich("cheese")
import sound_effects
jump_sound()
, explosion_sound()
def play_jingle(): print(“🎵 Happy tune playing! 🎵”)
import sound_module sound_module.play_jingle()
---
# Building Our Own Module
1. Create `kitchen.py`:
```python
def microwave_beep():
print("BEEP! BEEP! BEEP!")
def oven_timer():
print("DING! Food is ready!")
import kitchen
kitchen.microwave_beep()
kitchen.oven_timer()
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")
# 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()
Like a recipe:
def magic_oven(ingredient): # Function header
output=str(ingredient) +" cookie" # Function body
return(output)
Three essential parts:
def
statement with function namedef greet(name):
print("Hello, "+str(name))
greet("Alice") # Output: Hello, Alice!
greet("Bob") # Output: Hello, Bob!
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") #
(greeting, name)
vs (name, greeting)
def circle_area(radius):
area = 3.14 * radius ** 2
return(area)
print(circle_area(5)) # 78.5
print("Pizza area:", circle_area(30)) #
pizza_price = circle_area(30) * 0.02
# Wrong
def bad_function()
print("Oops")
# Right
def good_function():
print("Yay!")
# Wrong
def messy_function():
print("No indent!")
# Right
def clean_function():
print("Perfect!")
import datetime
def show_time():
now = datetime.datetime.now()
print("Current time: "+str(now.hour)+':'+str(now.minute))
show_time()
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
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)
Try this bad example:
# Confusing positional arguments
make_pizza(["pepperoni"], 25)
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))
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]))
# 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)
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
score = 0
def update_points():
global score
score = score+10
print("New score: "+str(score))
update_points() # Now modifies the global variable
print(score)
# 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
Key concepts covered:
import math
print(math.sqrt(25)) # 5.0
print(math.pi) # 3.141592653589793
![Down Arrow] Key points:
from random import randint
lottery = [randint(1, 50) for _ in range(6)]
print("Winning numbers:", lottery)
Example output:
Winning numbers: [14, 37, 5, 23, 42, 19]
![Warning] Be careful with name collisions!
import math
a = 3
b = 4
c = math.sqrt(a**2 + b**2)
print(f"The hypotenuse is: {c}")
Output:
The hypotenuse is: 5.00
from random import choice
participants = ["Alice", "Bob", "Charlie", "Diana"]
winner = choice(participants)
print(f"Congratulations {winner}!")
Possible output:
Congratulations Charlie!
import time
print("Starting countdown:")
for i in range(5, 0, -1):
print(i)
time.sleep(1)
print("Blast off! ")
mymodule.py
:
def greet(name):
return f"Hello {name}, from my module!"
print(mymodule.greet(“Sarah”))
---
### Understanding Namespaces
```python
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
# requests example
import requests
response = requests.get("https://www.bioinfo-lab.com/")
print(f"Status code: {response.status_code}")
print(f"Response time: {response.elapsed.total_seconds()}s")
import sys
print("Python looks in these locations:")
for path in sys.path:
print("- "+str(path))
import numpy as np
import pandas as pd
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)
Usage:
print(generate_password()) # Example: 'a3x7bk9m'
print(generate_password(12)) # Example: 'wxn58k2q9yr7'
Core logic:
def calculator(a, b, operator="+"):
if operator == "+":
return a + b
elif operator == "-":
return a - b
Using our calculator:
print(calculator(5, 3)) # 8 (uses default +)
print(calculator(5, 3, "-")) # 2
print(calculator(2.5, 4, "+")) # 6.5
Conversion formulas:
Celsius to Fahrenheit: (C × 9/5) + 32
def c_to_f(c):
return (c * 9/5) + 32
Test conversions:
print(c_to_f(0))
print(c_to_f(100))