1. π Introduction to Python: BasicsΒΆ
π Learning Objectives: - Understand Python fundamentals - Work with lists and dictionaries - Read and process CSV files - Compute basic statistics
[ ]:
# Setup the environment for the tutorial notebook to run on CoLab
# This script will clone the repository and change the working directory to the tutorial notebook directory
if 'google.colab' in str(get_ipython()):
print('Running on CoLab')
!git clone https://github.com/bfortuno/Surgical-Phase-Recognition.git # Clone the repository
%cd Surgical-Phase-Recognition/docs/tutorial_notebooks/tutorial1
else:
print('Not running on CoLab')
Not running on CoLab
1 Python BasicsΒΆ
1.1 Variables & Data TypesΒΆ
In Python, variables store values. Letβs look at some common data types:
[3]:
# Integer
a = 10
# Float
b = 3.14
# String
c = 'Hello, AI!'
# Boolean
d = True
# Print values
print(a, b, c, d)
10 3.14 Hello, AI! True
π Task: Try defining your own variables and print them.
1.2 Conditionals and LoopsΒΆ
If-else statements allow decision-making:
[4]:
x = 5
if x > 0:
print('Positive number')
else:
print('Negative number')
Positive number
π For LoopΒΆ
# For loop
for i in range(5):
print(i)
π Explanation:ΒΆ
range(5)generates numbers from 0 to 4 (not including 5).The loop runs 5 times, each time printing the current value of
i.The loop automatically increments
iin each iteration.
β οΈ Things to Be Careful About:ΒΆ
Indexing Issues:
range(n)starts from 0 and goes up to n-1, notn.Skipping Values: To loop from 1 to 5, use
range(1, 6).for i in range(1, 6): # Generates 1, 2, 3, 4, 5 print(i)
Step Size: Use a third argument for step size.
for i in range(0, 10, 2): # Prints even numbers 0, 2, 4, 6, 8 print(i)
π While LoopΒΆ
# While loop
count = 0
while count < 3:
print('Count:', count)
count += 1
π Explanation:ΒΆ
The loop executes as long as
count < 3.The variable
countstarts at 0 and increases by 1 in each iteration.When
count == 3, the loop condition (count < 3) becomes False, and the loop stops.
β οΈ Things to Be Careful About:ΒΆ
Infinite Loops: If
countis not incremented inside the loop, it will run forever.while True: # β οΈ Infinite loop print("This will run forever!")
Proper Condition: Ensure the loop will eventually stop. A faulty condition may cause the program to hang.
Changing Condition Inside the Loop: If the value of
countis not updated properly, the loop may behave unexpectedly.
[5]:
# For loop
for i in range(5):
print(i)
# While loop
count = 0
while count < 3:
print('Count:', count)
count += 1
0
1
2
3
4
Count: 0
Count: 1
Count: 2
π Task: Modify the loops to print numbers from 1 to 10.
2 Functions in PythonΒΆ
Functions help organize code into reusable blocks:
[6]:
def add_numbers(x, y):
return x + y
print(add_numbers(3, 5))
8
π Task: Write a function that multiplies two numbers.
3 Lists and DictionariesΒΆ
3.1 Lists (Arrays in Python)ΒΆ
[7]:
numbers = [1, 2, 3, 4, 5]
# Access elements
print(numbers[0])
# Loop through list
for num in numbers:
print(num)
1
1
2
3
4
5
3.2 Dictionaries (Key-Value Pairs)ΒΆ
[8]:
student = {'name': 'Alice', 'age': 22, 'grade': 'A'}
print(student['name']) # Output: Alice
Alice
π Task: Create a dictionary storing information about yourself and print it.
4 File Handling & CSV ProcessingΒΆ
Letβs read a CSV file using Python!
[9]:
import csv
# Read a CSV file
with open('data1.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
['Time', 'Temperature (C)']
['08:00', '22.5']
['09:00', '24.1']
['10:00', '25.3']
['11:00', '26.7']
['12:00', '27.8']
Now, letβs compute basic statistics:
[10]:
import pandas as pd
# Load CSV into a DataFrame, considering first row as header and first column as index
df = pd.read_csv('data2.csv', header=0, index_col=0)
# Display DataFrame head
print(df.head())
Math Science English
Student
Alice 85 89 75
Bob 90 85 80
Charlie 78 80 85
David 92 95 90
Eve 88 90 78
[11]:
# Compute statistics
print('Mean:', df.mean())
print('Max:', df.max())
print('Min:', df.min())
Mean: Math 86.6
Science 87.8
English 81.6
dtype: float64
Max: Math 92
Science 95
English 90
dtype: int64
Min: Math 78
Science 80
English 75
dtype: int64
π Task: Load a CSV file and compute its mean, max, and min values.
[ ]:
Final TaskΒΆ
Read a CSV file called
Surgical-deepnet.csvCompute the mean, max, and min of each column.
Print the results.
π‘ Hint: Use Pandas (pd.read_csv()) for easy CSV handling.