[Week 4] Bringing Data to Life: Control Flow and Functions π¨βπ»
English translation
Hello! Welcome to Week 4.
Last time, we learned to store data using Python variables and data structures.
Today, we will go a step further and learn how to 'process' and 'manipulate' stored data.
Use if statements to select data meeting particular conditions,
Process hundreds or tens of thousands of data items using for loops,
Learn how to turn this entire process into a reusable component called a function (def).
π¦ Module 1: Code That Follows Conditions β if Statements
What is a conditional statement?
- Syntax that executes a block of code only when a specified condition is True.
Basic structure
if 쑰건μ: # Code to run when the condition is True elif λ€λ₯Έ_쑰건μ: # Code to run when the other condition is True else: # Code to run when all conditions above are FalseApplications in machine learning
- ex1) "If the rating is at least 9.0, classify it as a recommended movie."
- ex2) "If the data contain missing values, fill them with a specified value."
- Essential for data preprocessing and defining model rules.
# Example: Decide whether to recommend a movie based on its rating
movie_rating = 9.1
# 'If' movie_rating is greater than or equal to 9.0
if movie_rating >= 9.0:
print("β¨ κ°λ ₯ μΆμ²νλ μνμ
λλ€!")
# 'Otherwise'
else:
print("λ³Όλ§ν μνμ
λλ€.")β¨ κ°λ ₯ μΆμ²νλ μνμ λλ€!
# Example: Decide whether to recommend a movie based on its rating
movie_rating = 8.5
# 'If' movie_rating is greater than or equal to 9.0
if movie_rating >= 9.0:
print("β¨ κ°λ ₯ μΆμ²νλ μνμ
λλ€!")
# 'Otherwise'
else:
print("λ³Όλ§ν μνμ
λλ€.")
# Change movie_rating to 8.5 and run again!λ³Όλ§ν μνμ λλ€.
# A more detailed recommendation system
movie_rating = 8.8
if movie_rating >= 9.0:
print("β¨ κ°λ ₯ μΆμ²! (9.0μ μ΄μ)")
# 'Else if' the rating is 8.5 or higher
elif movie_rating >= 8.5:
print("π μΆμ²! (8.5μ μ΄μ)")
# 'In all other cases'
else:
print("π€ 보ν΅. (8.5μ λ―Έλ§)")π μΆμ²! (8.5μ μ΄μ)
π Module 2: All the Data at Once! for Loops
What Is a Loop?
- For all data in a structure such as a list or dictionary,
- it repeats the same task in sequence.
Basic structure
for μμ΄ν μ_λ΄μ_λ³μ in λ°μ΄ν°_리μ€νΈ: # Code to run for each list itemUses in Machine Learning
- Essential for large-scale data processing, such as loading and processing millions of images individually,
- or calculating the mean or sum of an entire dataset.
# The movie dataset created in Week 3
my_movie_dataset = [
{ "title": "μΈμ
μ
",
"director": "ν¬λ¦¬μ€ν νΌ λλ",
"rating": 9.29 },
{ "title": "κΈ°μμΆ©",
"director": "λ΄μ€νΈ",
"rating": 9.07 },
{ "title": "μ΄λ°μ νμ",
"director": "리차λ 컀ν°μ€",
"rating": 9.27 }
]
# Iterate through the dataset (list), placing each movie's information (dictionary) in movie
print("--- λͺ¨λ μν μ λͺ© μΆλ ₯ ---")
for movie in my_movie_dataset:
# Retrieve and print the value of the 'title' key from each movie (dictionary)
print(movie['title'])--- λͺ¨λ μν μ λͺ© μΆλ ₯ --- μΈμ μ κΈ°μμΆ© μ΄λ°μ νμ
# Combine loops and conditionals to select only 'movies rated 9.2 or higher'
print("\n--- νμ 9.2 μ΄μμΈ μΆμ² μν ---")
for movie in my_movie_dataset:
# 'If' the current movie's rating is greater than or equal to 9.2
if movie['rating'] >= 9.2:
# Print that movie's title and rating
print(f"μ λͺ©: {movie['title']}, νμ : {movie['rating']}")--- νμ 9.2 μ΄μμΈ μΆμ² μν --- μ λͺ©: μΈμ μ , νμ : 9.29 μ λͺ©: μ΄λ°μ νμ, νμ : 9.27
βοΈ Module 3: Reusable Code Components β Functions (def)
What is a function?
- A block of code that performs a specific task
- and can be named and reused.
Basic structure
def ν¨μμ΄λ¦(μ λ ₯κ°1, μ λ ₯κ°2, ...): # Code to run return κ²°κ³Όκ°Applications in machine learning
Implement data preprocessing as a function to apply the same process to multiple datasets.
A model itself can be viewed as a function.
[Input (data) β Processing (prediction) β Output (result)]
Organize complex code by functionality to make it easier to maintain.
# A simple function that adds two numbers
def add_numbers(x, y):
"""
μ΄ ν¨μλ λ κ°μ μ«μ xμ yλ₯Ό μ
λ ₯λ°μ,
κ·Έ ν©μ κ³μ°νμ¬ κ²°κ³Όκ°μΌλ‘ λλ €μ€λλ€.
"""
result = x + y
return result
# Call (use) the function
sum_result = add_numbers(5, 3)
print(f"5μ 3μ ν©μ? {sum_result}")
another_sum = add_numbers(100, 200)
print(f"100κ³Ό 200μ ν©μ? {another_sum}")5μ 3μ ν©μ? 8 100κ³Ό 200μ ν©μ? 300
# Turn Module 2's 'rating-based movie recommendation' logic into a function.
def recommend_movies(dataset, min_rating):
"""
μν λ°μ΄ν°μ
κ³Ό μ΅μ νμ μ μ
λ ₯λ°μ,
쑰건μ λ§λ μν μ λͺ© 리μ€νΈλ₯Ό κ²°κ³Όλ‘ λλ €μ€λλ€.
"""
recommended_list = [] # An empty list for recommended movies
for movie in dataset:
if movie['rating'] >= min_rating:
recommended_list.append(movie['title']) # Append to the list
return recommended_list
# Use the function to recommend movies rated 9.0 or higher
my_best_movies = recommend_movies(my_movie_dataset, 9.0)
print(f"νμ 9.0 μ΄μ μΆμ² μν: {my_best_movies}")
# Reuse the same function to recommend movies rated 9.1 or higher
my_good_movies = recommend_movies(my_movie_dataset, 9.1)
print(f"νμ 9.1 μ΄μ μΆμ² μν: {my_good_movies}")νμ 9.0 μ΄μ μΆμ² μν: ['μΈμ μ ', 'κΈ°μμΆ©', 'μ΄λ°μ νμ'] νμ 9.1 μ΄μ μΆμ² μν: ['μΈμ μ ', 'μ΄λ°μ νμ']