Functions
Learn to write reusable functions. Define functions with parameters, return values, and learn about variable scope.
Learning Objectives:
- β’Define and call functions
- β’Understand function parameters and arguments
- β’Return values from functions
- β’Understand variable scope (local vs. global)
- β’Reuse code with functions
- β’Understand function decomposition
Functions
What is a Function?
A function is a reusable block of code that performs a specific task. Instead of writing the same code multiple times, you write it once in a function and call it whenever you need it.
Benefits:
- Reusability: Write once, use many times
- Readability: Code is easier to understand
- Maintainability: Fix bugs in one place
- Organization: Break large problems into smaller pieces
Function Basics
A function has:
- Name β what you call it
- Parameters β input values (optional)
- Body β the code it executes
- Return value β output (optional)
Python
pythondef greet(name): print(f"Hello, {name}!") # Call the function greet("Alice") # Output: Hello, Alice! greet("Bob") # Output: Hello, Bob!
C
c#include <stdio.h> void greet(char name[]) { printf("Hello, %s!\n", name); } int main() { greet("Alice"); // Output: Hello, Alice! greet("Bob"); // Output: Hello, Bob! return 0; }
Java
javapublic class Main { static void greet(String name) { System.out.println("Hello, " + name + "!"); } public static void main(String[] args) { greet("Alice"); // Output: Hello, Alice! greet("Bob"); // Output: Hello, Bob! } }
Return Values
Functions can return a value that you can use in your code.
Python
pythondef square(x): return x * x result = square(5) print(result) # 25
C
c#include <stdio.h> int square(int x) { return x * x; } int main() { int result = square(5); printf("%d\n", result); // 25 return 0; }
Java
javapublic class Main { static int square(int x) { return x * x; } public static void main(String[] args) { int result = square(5); System.out.println(result); // 25 } }
Multiple Parameters
Functions can take multiple inputs.
Python
pythondef add(a, b): return a + b print(add(3, 5)) # 8 print(add(10, 20)) # 30
C
c#include <stdio.h> int add(int a, int b) { return a + b; } int main() { printf("%d\n", add(3, 5)); // 8 printf("%d\n", add(10, 20)); // 30 return 0; }
Java
javapublic class Main { static int add(int a, int b) { return a + b; } public static void main(String[] args) { System.out.println(add(3, 5)); // 8 System.out.println(add(10, 20)); // 30 } }
Local vs. Global Scope
Local variables exist only within a function. They're created when the function is called and destroyed when it ends.
Python
pythondef calculate(): x = 10 # local variable y = 5 # local variable return x + y print(calculate()) # 15 print(x) # ERROR - x doesn't exist outside the function
C
c#include <stdio.h> int calculate() { int x = 10; // local to this function int y = 5; return x + y; } int main() { printf("%d\n", calculate()); // 15 // printf("%d\n", x); // ERROR - x doesn't exist here return 0; }
Real-World Example: Factorial (Iterative)
Problem: Calculate the factorial of a number.
- Factorial of 5 = 5 Γ 4 Γ 3 Γ 2 Γ 1 = 120
Python:
pythondef factorial(n): result = 1 for i in range(1, n + 1): result = result * i return result print(factorial(5)) # 120 print(factorial(10)) # 3628800
Java:
javapublic class Main { static int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result = result * i; } return result; } public static void main(String[] args) { System.out.println(factorial(5)); // 120 System.out.println(factorial(10)); // 3628800 } }
Example: Check if Prime
Problem: Determine if a number is prime.
Python:
pythondef is_prime(n): if n < 2: return False for i in range(2, n): if n % i == 0: return False return True print(is_prime(17)) # True print(is_prime(20)) # False
Java:
javapublic class Main { static boolean is_prime(int n) { if (n < 2) { return false; } for (int i = 2; i < n; i++) { if (n % i == 0) { return false; } } return true; } public static void main(String[] args) { System.out.println(is_prime(17)); // true System.out.println(is_prime(20)); // false } }
Example: Fibonacci (Recursive)
Problem: Calculate the Nth Fibonacci number.
- Fibonacci: 1, 1, 2, 3, 5, 8, 13, 21...
- Each number is the sum of the two before it
Python:
pythondef fibonacci(n): if n <= 1: return 1 return fibonacci(n - 1) + fibonacci(n - 2) print(fibonacci(5)) # 8 print(fibonacci(6)) # 13
Java:
javapublic class Main { static int fibonacci(int n) { if (n <= 1) { return 1; } return fibonacci(n - 1) + fibonacci(n - 2); } public static void main(String[] args) { System.out.println(fibonacci(5)); // 8 System.out.println(fibonacci(6)); // 13 } }
Finding the GCD (Greatest Common Divisor)
Python:
pythondef gcd(a, b): while b != 0: temp = b b = a % b a = temp return a print(gcd(48, 18)) # 6 print(gcd(100, 75)) # 25
Best Practices
1. Use Meaningful Names
python# Good def calculate_total_price(quantity, price): return quantity * price # Bad def calc(q, p): return q * p
2. Keep Functions Small
Each function should do one thing well.
python# Good - each function has a clear purpose def is_valid_age(age): return age >= 0 and age <= 120 def display_age(age): print(f"Age: {age}") # Bad - does too much def process_age(age): if age >= 0 and age <= 120: print(f"Age: {age}") # ... 20 more lines of code
3. Document Your Functions
pythondef calculate_area(radius): """Calculate the area of a circle. Args: radius: The radius of the circle Returns: The area of the circle """ return 3.14159 * radius * radius
Key Takeaways
- Functions let you write reusable code
- Parameters are inputs to a function
- Return values are outputs from a function
- Local variables exist only within a function
- Recursion is when a function calls itself
- Scope determines where a variable can be used
- Well-named functions make code readable
Summary
Functions are fundamental to programming. They let you organize code, eliminate duplication, and solve complex problems by breaking them into smaller pieces. With functions, loops, conditions, arrays, and strings, you now have powerful tools to write real programs.
You've completed Level 1: Fundamentals β a solid foundation in programming!
Progress: 8/8 chapters complete in Level 1
Exercises
Exercise 1: Function: Square
Write a function that returns the square of a number.
Exercise 2: Function: Factorial
Write a function that calculates the factorial of a number.
Exercise 3: Function: Is Prime
Write a function that determines whether a number is prime.
Exercise 4: Function: Fibonacci
Write a function that returns the requested Fibonacci number.
Exercise 5: Function: Greatest Common Divisor
Write a function that calculates the greatest common divisor of two numbers.
Exercise 6: Function: Power
Write a function that raises a number to the requested power.