Python Functions

🧩 Section 1 — Why We Use Functions

Imagine you have to print the same greeting message in 10 different parts of your program. You could copy-paste the same lines — but if you later want to change it, you'll have to fix it in 10 places!

Functions solve this problem. They let you group code into reusable blocks that can be called anytime.

⚙️ Section 2 — Defining a Function

You create a function using the keyword def.

Example:

python
def greet(): print("Hello!") print("Welcome to the program.")

Calling (using) the function:

python
greet() # Output: # Hello! # Welcome to the program.

🧱 Section 3 — Indentation in Functions

Just like in loops and if statements, everything inside a function must be indented.

✅ Correct

python
def say_hi(): print("Hi!") print("How are you?")

❌ Incorrect

python
def say_hi(): print("Hi!") # Missing indentation — this will cause an error!

🧮 Section 4 — Function Parameters (Inputs)

You can send information into a function using parameters.

Example:

python
def greet(name): print(f"Hello, {name}!") greet("Alice") greet("Bob") # Output: # Hello, Alice! # Hello, Bob!

Here, name is a parameter — it acts like a temporary variable that exists only inside the function.

🔙 Section 5 — Return Values (Outputs)

Some functions give something back using the return keyword.

Example:

python
def add(a, b): result = a + b return result sum = add(3, 5) print("Sum =", sum) # Output: # Sum = 8

🔄 Section 6 — Multiple Parameters

You can pass more than one value into a function.

Example:

python
def area(width, height): return width * height print(area(5, 10)) # Output: # 50

🧩 Section 7 — Combining Everything

Let's see how multiple functions can work together in one program:

python
def greet(name, age): print(f"Hello {name}, you are {age} years old.") def next_year_age(age): return age + 1 name = input("Enter your name: ") age = int(input("Enter your age: ")) greet(name, age) print("Next year, you'll be", next_year_age(age))

Example Output:

Enter your name: Linh
Enter your age: 14
Hello Linh, you are 14 years old.
Next year, you'll be 15

🚀 Section 8 — Practical Use Case: Student Grade Report

Here's why functions are so powerful — you can write a function once and call it many times with different data. Let's build a student grade report!

Without Functions (Bad ❌)

Imagine calculating the grade for 3 students without a function:

python
# Student 1 total1 = 80 + 90 + 70 avg1 = total1 / 3 if avg1 >= 80: grade1 = "A" elif avg1 >= 60: grade1 = "B" else: grade1 = "C" print(f"Alice: average = {avg1}, grade = {grade1}") # Student 2 — same logic copy-pasted! total2 = 50 + 65 + 70 avg2 = total2 / 3 if avg2 >= 80: grade2 = "A" elif avg2 >= 60: grade2 = "B" else: grade2 = "C" print(f"Bob: average = {avg2}, grade = {grade2}") # Student 3 — copy-pasted AGAIN! # ... imagine doing this for 30 students 😩

With Functions (Good ✅)

Write the logic once, then call it for each student:

python
def calculate_grade(name, score1, score2, score3): avg = (score1 + score2 + score3) / 3 if avg >= 80: grade = "A" elif avg >= 60: grade = "B" else: grade = "C" print(f"{name}: average = {avg:.1f}, grade = {grade}") # Now call it for each student — clean and simple! calculate_grade("Alice", 80, 90, 70) calculate_grade("Bob", 50, 65, 70) calculate_grade("Charlie", 95, 88, 92) calculate_grade("Diana", 40, 55, 30)

Output:

Alice: average = 80.0, grade = A
Bob: average = 61.7, grade = B
Charlie: average = 91.7, grade = A
Diana: average = 41.7, grade = C

🔄 Even Better: Using with a Loop and Input

Combine functions with a loop to process many students dynamically:

python
def calculate_grade(name, score1, score2, score3): avg = (score1 + score2 + score3) / 3 if avg >= 80: grade = "A" elif avg >= 60: grade = "B" else: grade = "C" print(f"{name}: average = {avg:.1f}, grade = {grade}") n = int(input("How many students? ")) for i in range(n): name = input("Enter student name: ") s1 = int(input("Score 1: ")) s2 = int(input("Score 2: ")) s3 = int(input("Score 3: ")) calculate_grade(name, s1, s2, s3)

🧠 Section 9 — Scope — Where Variables "Live"

Variables inside a function only exist inside it. They are called local variables.

Example:

python
def show_number(): x = 10 print(x) show_number() # Output: 10 print(x) # ❌ Error! x is not defined here

Output:

10
NameError: name 'x' is not defined

⚡ Section 10 — Built-in vs Custom Functions

Python already has many built-in functions:

You can write your own custom functions using def to make your program easier to understand and reuse.

🧩 Section 11 — Practice Exercises

🔢 Exercise 1: Square Number Function

Write a function square(x) that returns x * x.

Example:

python
print(square(4)) # Output: 16 print(square(7)) # Output: 49

🔢 Exercise 2: Greeting Function

Write a function that takes name and prints:

Hello, <name>! Welcome back.

Example:

python
greet("Alice") # Output: Hello, Alice! Welcome back.

🔢 Exercise 3: Temperature Converter

Write a function to_fahrenheit(celsius) that returns the Fahrenheit temperature using:

F = C * 9/5 + 32

Example:

python
print(to_fahrenheit(0)) # Output: 32.0 print(to_fahrenheit(100)) # Output: 212.0

🔢 Exercise 4: Average Score

Create a function average(a, b, c) that returns the average of three scores.

Example:

python
print(average(80, 90, 70)) # Output: 80.0

🧠 Section 12 — Challenge Project: "Mini Calculator"

Requirements:

Example Output:

Choose operation: add / subtract / multiply / divide
add
Enter first number: 4
Enter second number: 6
Result = 10

Summary

Functions are one of the most important concepts in programming. Practice these concepts regularly!