Programming · StudentHub Lesson
Functions
Learn how to organize code into reusable blocks called functions with parameters and return values.
What you will learn
- Define a function using def in Python
- Pass parameters into a function
- Return values from a function
- Understand variable scope inside functions
- Explain why functions make code reusable
Watch the lesson
Python for Beginners – Full Course [Programming Tutorial] · freeCodeCamp.org
Watch on YouTubeTopic notes
Main Idea
Functions are reusable blocks of code that perform a specific task, making programs organized and avoiding repetition.
Key Concepts
- Functions are defined with the
defkeyword - Parameters let you pass data into a function
- The
returnstatement sends a value back to the caller - Variables defined inside a function have local scope
Definitions
- Function: a named, reusable block of code that performs a task
- Parameter: a variable listed in a function's definition
- Return value: the output a function sends back
Syntax
```python
def greet(name):
return "Hello, " + name
message = greet("Sam")
print(message)
```
Examples
- A function
add(a, b)that returns a + b - A function
is_even(num)that returns True or False
Common Mistakes
- Forgetting to call the function with ()
- Forgetting the return statement, causing None to be returned
- Confusing parameters with arguments
Key concepts
Important terms
- Function
- A reusable, named block of code that performs a specific task
- Parameter
- A variable used to pass data into a function
- Return value
- The result a function sends back to the code that called it
Worked examples
Problem
Write a function that adds two numbers
- 1. def add(a, b):
- 2. return a + b
- 3. print(add(2, 3))
Answer: 5
Quick revision
- Functions are defined with def
- Parameters pass data into functions
- return sends a value back
- Functions avoid repeating code
- Local variables only exist inside their function
Check your understanding
Question 1 · Multiple choice
Which keyword defines a function in Python?
Question 2 · Multiple choice
What does the return statement do?
Question 3 · True or false
A function must always return a value.
Question 4 · Short answer
What is a parameter?
Question 5 · Short answer
Write a function call for a function named square that takes 4.
Done with Functions?
Sign in to save your progress across the library.