%pip install -q otter-grader
# 1. Download the file using gdown (which handles Google Drive links perfectly)
# We pass the file ID directly to it.
!gdown "1jJO6jdHJwQuOn3hUfj6uCSor4xI5hdSP" -O assignment.zip
# 2. Unzip the file silently into the current Colab directory
!unzip -q -o assignment.zip
# 3. (Optional) Verify the tests folder is there
!ls -l tests/
# Initialize Otter
import otter
grader = otter.Notebook()
Python for Health Sciences: A Beginner's Guide¶
Welcome to your introduction to Python programming! This tutorial is designed for students with no prior programming experience, especially those interested in health sciences. By the end of this session, you'll understand the basics of Python and be able to build a simple calculator program.
How to Use This Notebook¶
You're currently looking at a Jupyter notebook. Think of it as a document where you can mix text explanations (like this) with actual code that you can run.
- Code cells have a gray background and begin with
In [ ]:. You can type code here and run it by pressing Shift+Enter or clicking the "Run" button at the top of the page. - Output appears below the code cell after you run it.
- Text cells (like this one) provide explanations and instructions.
Important for beginners:
- You must run cells in order from top to bottom for the code to work properly
- If you see
In [*], it means the cell is still running - If you make a mistake, you can edit a cell and run it again
- Don't worry about making mistakes - they're part of learning!
Let's start with a simple example. Click on the code cell below and press Shift+Enter to run it:
# Validation: Check Python version and file location
import os
import sys
# Supported Python versions for this course
SUPPORTED_VERSIONS = ["3.12", "3.13"]
current_version = f"{sys.version_info.major}.{sys.version_info.minor}"
if current_version not in SUPPORTED_VERSIONS:
raise EnvironmentError(
f"Python version mismatch!\n"
f"Supported: {', '.join(SUPPORTED_VERSIONS)}\n"
f"Found: {current_version}\n"
f"Please use Python 3.12 or 3.13 for this course."
)
print(f"Python version: {current_version}")
# Expected filename for this assignment
EXPECTED_FILE = "99_CSC118_intro_to_python.ipynb"
# Check file is in the correct directory
current_path = os.path.abspath("")
required_path_segment = os.path.join("Documents", "CSC115", "lecture_notebooks")
allowed_envs = ["submission", "dist", "live", "source"]
in_allowed_env = any(env in current_path for env in allowed_envs)
if required_path_segment not in current_path and not in_allowed_env:
raise EnvironmentError(
f"File location error!\n"
f"This notebook should be in: ~/Documents/CSC115/lecture_notebooks/\n"
f"Current location: {current_path}\n"
f"Please move this file to the correct directory."
)
# Verify directory name and filename (skip in grading/development environments)
if not in_allowed_env:
if not os.path.exists(EXPECTED_FILE):
notebooks = [f for f in os.listdir(".") if f.endswith(".ipynb")]
raise EnvironmentError(
f"Filename mismatch!\n"
f"Expected: {EXPECTED_FILE}\n"
f"Found notebooks: {notebooks}\n"
f"Please rename your notebook to '{EXPECTED_FILE}'."
)
print(f"File location: {os.path.join(current_path, EXPECTED_FILE)}")
Great! You just ran your first Python code. Now, let's dive into the basics.
1. Basic Data Types¶
In Python, we work with different types of data. Here are the main ones we'll use today:
Integers (whole numbers)¶
These are whole numbers without decimal points. For example, in health sciences, you might use integers to count:
- Number of patients
- Heartbeats per minute
- Days in a treatment cycle
- Hello
# This is python
a = 1
b = 2
c = (1**2 + 2**2) ** (1 / 2)
c
# This is a comment - it's ignored by Python but helps humans understand the code
# Everything after the hash-sign "#" is considered a comment
# Comments are VERY important for beginners and experts alike to understand what the code is doing
print("This is not a comment") # But this is! Comments can also appear after code
"we dont have to print"
# Let's create some integers
# A variable is like a labeled container that stores a value
# The format is: variable_name = value
patient_count = 42 # We're storing the number 42 in a container labeled "patient_count"
heart_rate = 72 # We're storing the number 72 in a container labeled "heart_rate"
treatment_days = (
14 # We're storing the number 14 in a container labeled "treatment_days"
)
# Let's see what type these variables are
# You can see a type of a variable named "x" by running "type(x)"
# This helps us understand what kind of data we're working with
print(
type(patient_count)
) # This will show us that patient_count is an integer (whole number)
Floating-Point Numbers (decimals)¶
These are numbers with decimal points. In health sciences, you might use floats for:
- Patient temperature
- Blood pressure readings
- Medication dosages
# Creating some floating-point numbers
body_temperature = 98.6
systolic_pressure = 120.5
medicine_dose = 2.5
print(type(body_temperature))
Strings (text)¶
Strings are sequences of characters (letters, numbers, symbols) enclosed in quotes. The quotes can be single like 'this' or double like "this". Python treats them the same, you just have to be consistent so "this' won't work :(
In health sciences, you might use strings for:
- Patient names
- Blood types
- DNA sequences
patient_name = "Jane Smith"
blood_type = "O+"
dna_fragment = "GATTACA"
print(type(patient_name))
# Your code here
patient_age = ...
patient_weight = ...
patient_complaint = ...
# Now print each variable (uncomment the lines below by removing the # symbol)
print("Patient age:", patient_age)
print("Patient weight:", patient_weight)
print("Patient complaint:", patient_complaint)
grader.check("q1")
2. Variables and Simple Operations¶
Variables are like labeled containers that store data. We've already created some above!
Naming Variables¶
- Must start with a letter or underscore
- Can contain letters, numbers, and underscores
- Cannot use Python keywords (like
if,for,while) - Case-sensitive (so
Weightandweightare different variables)
Good variable names are descriptive and use snake_case (lowercase with underscores):
# Good names
visitor_age = 65
blood_glucose_level = 105.5
doctor_notes = "Patient reports feeling better"
# Not so good names
a = 65
x = 105.5
y = "Patient reports feeling better"
Basic Operations with Numbers¶
You can perform mathematical operations with integers and floats:
# Addition
total_patients = 12 + 15
print("Total patients:", total_patients)
# Subtraction
remaining_doses = 30 - 12
print("Remaining doses:", remaining_doses)
# Multiplication
total_dosage = 2.5 * 3
print("Total dosage (mg):", total_dosage)
# Division
average_heart_rate = 441 / 5
print("Average heart rate:", average_heart_rate)
# Exponents (powers)
cell_count = 2**10 # 2 to the power of 10
print("Cell count after 10 divisions:", cell_count)
# Integer division (drops remainder)
print(100 / 7)
complete_days = 100 // 7
print("Complete weeks:", complete_days)
# Modulo (remainder)
days_remainder = 15 % 7
print("Remaining days:", days_remainder)
String Operations¶
Strings can be combined (concatenated) using the + operator:
first_name = "Maria"
last_name = "Rodriguez"
full_name = first_name + " " + last_name
print(full_name)
f"{first_name} {last_name}"
You can also repeat strings using the * operator:
dna_sequence = "ACGT"
repeated_sequence = dna_sequence * 3
print(repeated_sequence) # Prints ACGTACGTACGT
Your Turn!¶
Calculate the Body Mass Index (BMI) for a patient with:
- Weight: 70.5 kilograms
- Height: 1.75 meters
Remember, BMI = weight (kg) / height² (m²)
Your Turn!¶
Calculate the Body Mass Index (BMI) for a patient with:
- Weight: 70.5 kilograms
- Height: 1.75 meters
Remember, BMI = weight (kg) / height² (m²) The ² symbol means "squared" or "to the power of 2"
Step 1: Create variables for weight and height¶
weight = 70.5 # in kilograms
height = 1.75 # in meters
Step 2: Calculate BMI using the formula¶
In Python, we use ** for exponents (powers)
Step 3: Print the result¶
print("Patient's BMI is:", bmi)
To show fewer decimal places, you can use round():¶
print("Patient's BMI (rounded) is:", round(bmi, 1)) # The 1 means "show 1 decimal place"
# Your code here
weight = 70.5 # in kilograms
height = 1.75 # in meters
bmi = ...
print("Patient's BMI is:", bmi)
print(
"Patient's BMI (rounded) is:", round(bmi, 1)
) # The 1 means "show 1 decimal place"
# bmi
grader.check("q2")
age = 25
print("The patient is", age, "years old")
# You can also format strings more precisely
print(f"The patient is {age} years old") # f-strings (modern way)
User Input¶
The input() function gets information from the user:
# Basic input
name = input("Enter your name: ")
print(f"Hello, {name}!")
print("hello " + name)
# Remember: input() always returns a string
# If you need a number, you must convert it
age_string = input("Enter your age: ")
age = int(age_string) # Convert to integer
print(f"In 5 years, you'll be {age + 5} years old")
# You can also combine these steps
demo_weight = float(input("Enter your weight in kg: "))
print(f"Your weight in pounds is approximately {demo_weight * 2.20462:.2f}")
Your Turn!¶
Create a program that asks a user for their height in meters, then converts it to feet. (1 meter = 100 cm, 1 foot = 30.48 cm)
# Your code here
patient_height_in_m = input("Patient height in meters: ")
patient_height_in_ft = ...
print(f"Patient's height in meters: {patient_height_in_m}")
print(f"Patient's height in feet: {patient_height_in_ft}")
# Visible tests
assert "patient_height_in_m" in globals(), "Variable patient_height_in_m is missing"
assert "patient_height_in_ft" in globals(), "Variable patient_height_in_ft is missing"
# Verify the conversion logic is correct
assert isinstance(patient_height_in_m, float), "patient_height_in_m should be a float"
assert isinstance(patient_height_in_ft, float), "patient_height_in_ft should be a float"
4. Comparison Operators¶
Comparison operators compare values and return Boolean results (True or False).
# Equal to (==)
print(5 == 5) # True
print("A" == "a") # False (case-sensitive)
# Not equal to (!=)
print(10 != 5) # True
# Greater than (>)
print(7 > 3) # True
# Less than (<)
print(4 < 4) # False
# Greater than or equal to (>=)
print(4 >= 4) # True
# Less than or equal to (<=)
print(5 <= 10) # True
Health Science Examples¶
# Normal body temperature is 98.6°F (37°C)
temperature = 99.5
is_fever = temperature > 98.6
print(f"Temperature: {temperature}°F")
print(f"Does the patient have a fever? {is_fever}")
# Normal blood pressure is below 120/80
systolic = 135
diastolic = 85
is_hypertension = systolic >= 130 or diastolic >= 80
print(f"Blood pressure: {systolic}/{diastolic}")
print(f"Does the patient have hypertension? {is_hypertension}")
# Normal blood glucose is 70-100 mg/dL when fasting
glucose = 95
is_normal_glucose = 70 <= glucose <= 100
print(f"Blood glucose: {glucose} mg/dL")
print(f"Is the glucose level normal? {is_normal_glucose}")
Your Turn!¶
Create a program that checks if a patient's vital signs are within normal ranges:
- Heart rate: 60-100 beats per minute is normal
- Respiratory rate: 12-20 breaths per minute is normal
# Your code here
heart_rate = 90
respiratory_rate = 15
is_heart_rate_normal = ...
is_respiratory_rate_normal = ...
print(
f"Heart rate: {heart_rate} beats per minute, is it normal? {is_heart_rate_normal}"
)
print(
f"Respiratory rate: {respiratory_rate} breaths per minute, is it normal? {is_respiratory_rate_normal}"
)
grader.check("q4")
age = 65
if age >= 65:
print("Patient is a senior citizen")
else:
print("Patient is not a senior citizen")
Multiple Conditions¶
You can use elif (short for "else if") for multiple conditions:
demo_bmi = 27.5
if demo_bmi < 18.5:
print("Underweight")
elif demo_bmi < 25:
print("Normal weight")
elif demo_bmi < 30:
print("Overweight")
else:
print("Obese")
Nested If Statements¶
You can put if statements inside other if statements:
temperature = 101.2
coughing = True
if temperature > 100:
print("Patient has a fever")
if coughing:
print("Patient has fever and cough - possible infection")
else:
print("Patient has fever but no cough")
else:
print("Patient does not have a fever")
Your Turn!¶
Create a program that categorizes a patient's blood pressure into:
- Normal: Less than 120/80
- Elevated: 120-129 / Less than 80
- Stage 1 Hypertension: 130-139 / 80-89
- Stage 2 Hypertension: 140+ / 90+
# Your code here
systolic = 135
diastolic = 85
...
...
category = ...
...
category = ...
...
category = ...
...
category = ...
...
...
grader.check("q5")
def greet_patient(name):
"""This function greets a patient by name."""
print(f"Hello, {name}! Welcome to the clinic.")
def add(num_1, num_2):
return num_1 + num_2
a = 1
b = 2
c = add(b, b)
print(c)
Calling a Function¶
greet_patient("Alex")
greet_patient("Taylor")
Functions with Return Values¶
Functions can return values that you can use later:
def calculate_bmi(weight, height):
"""Calculate BMI given weight in kg and height in meters."""
return weight / (height**2)
# Using the function
patient_bmi = calculate_bmi(70.5, 1.75)
print(f"Patient's BMI: {patient_bmi:.1f}")
# Using the result
if patient_bmi < 18.5:
print("Underweight")
elif patient_bmi < 25:
print("Normal weight")
elif patient_bmi < 30:
print("Overweight")
else:
print("Obese")
Functions with Multiple Parameters¶
def calculate_medication_dose(weight, age, is_pediatric=False):
"""Calculate medication dose based on patient factors."""
if is_pediatric:
base_dose = weight * 0.1
else:
base_dose = weight * 0.15
# Adjust for elderly patients
if age > 65:
base_dose = base_dose * 0.8
return base_dose
# Calculate dose for different patients
child_dose = calculate_medication_dose(25, 8, is_pediatric=True)
adult_dose = calculate_medication_dose(70, 45)
elderly_dose = calculate_medication_dose(65, 75)
print(f"Child dose: {child_dose:.1f} mg")
print(f"Adult dose: {adult_dose:.1f} mg")
print(f"Elderly dose: {elderly_dose:.1f} mg")
Your Turn¶
Create a function using the above bmi function using the input variables weight, height and return the string of their BMI result, such as "Underweight"
def calculate_bmi(weight: float, height: float) -> str:
"""Calculate BMI classification (Underweight, Normal, etc.) given weight in kg and height in meters, return BMI classification result string"""
# Calculate the BMI
patient_bmi = ...
# Classify the BMI into Underweight, Normal Weight, over weight, obese
...
...
...
...
...
...
...
...
# Using the function
patient_bmi = calculate_bmi(70.5, 1.75)
print(f"Patient's BMI classification: {patient_bmi}")
grader.check("q6")
To double-check your work, the cell below will rerun all of the autograder tests.
grader.check_all()