1. 🐍 Introduction to Python: Basics¢

Status

Filled notebook: View filled on Github Open filled In Collab
Author: Benjamin I. Fortuno

πŸ“Œ 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
Loops allow us to execute a block of code multiple times. Python has two main types of loops:
1. ``for`` loop – Used when the number of iterations is known. 2. ``while`` loop – Used when the number of iterations depends on a condition.

πŸŒ€ 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 i in each iteration.

⚠️ Things to Be Careful About:¢

  • Indexing Issues: range(n) starts from 0 and goes up to n-1, not n.

  • 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 count starts 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 count is 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 count is 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ΒΆ

  1. Read a CSV file called Surgical-deepnet.csv

  2. Compute the mean, max, and min of each column.

  3. Print the results.

πŸ’‘ Hint: Use Pandas (pd.read_csv()) for easy CSV handling.