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.
- Avoid repeating the same code
- Make your program easier to read
- Fix bugs in one place instead of many
⚙️ Section 2 — Defining a Function
You create a function using the keyword def.
Example:
pythondef greet(): print("Hello!") print("Welcome to the program.")
Calling (using) the function:
pythongreet() # Output: # Hello! # Welcome to the program.
How it works
def greet(): creates a function named greet. The code inside the function only runs when you call the function by writing greet().
🧱 Section 3 — Indentation in Functions
Just like in loops and if statements, everything inside a function must be indented.
✅ Correct
pythondef say_hi(): print("Hi!") print("How are you?")
❌ Incorrect
pythondef say_hi(): print("Hi!") # Missing indentation — this will cause an error!
Remember
Python uses indentation (tabs/spaces) to know which code belongs inside the function.
🧮 Section 4 — Function Parameters (Inputs)
You can send information into a function using parameters.
Example:
pythondef 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:
pythondef add(a, b): result = a + b return result sum = add(3, 5) print("Sum =", sum) # Output: # Sum = 8
Why use return?
When a function returns a value, you can store it in a variable or use it directly in another calculation. This makes functions much more powerful!
🔄 Section 6 — Multiple Parameters
You can pass more than one value into a function.
Example:
pythondef 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:
pythondef 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:
pythondef 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 = CWhy is this better?
If you need to change the grading rules (e.g. add a "D" grade), you only change it in one place — inside the function. All 4 students automatically get the updated logic!
🔄 Even Better: Using with a Loop and Input
Combine functions with a loop to process many students dynamically:
pythondef 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:
pythondef 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 definedRule
Variables inside functions don't affect variables outside. Each function has its own "space" for variables.
⚡ Section 10 — Built-in vs Custom Functions
Python already has many built-in functions:
print()— display outputlen()— get the length of a list or stringint()— convert to an integerrange()— generate a sequence of numbersinput()— read user input
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:
pythonprint(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:
pythongreet("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 + 32Example:
pythonprint(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:
pythonprint(average(80, 90, 70)) # Output: 80.0
🧠 Section 12 — Challenge Project: "Mini Calculator"
Requirements:
- Write four functions:
add(a, b),subtract(a, b),multiply(a, b),divide(a, b) - Ask the user to choose an operation
- Ask for two numbers
- Call the correct function and print the result
Example Output:
Choose operation: add / subtract / multiply / divide
add
Enter first number: 4
Enter second number: 6
Result = 10Hint
Use if statements to pick which function to call based on the user's choice!
Summary
Functions are one of the most important concepts in programming. Practice these concepts regularly!
- Define functions using
defand call them by name - Parameters let you pass inputs into a function
- Return values let a function give outputs back
- Scope — local variables only exist inside their function
- Indentation is required for everything inside a function
- Python has built-in functions (
print,len,int, etc.) and you can write your own