Programming · StudentHub Lesson

Functions

Learn how to organize code into reusable blocks called functions with parameters and return values.

17 minBeginner
01

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
02

Watch the lesson

Python for Beginners – Full Course [Programming Tutorial] · freeCodeCamp.org

Watch on YouTube
03

Topic 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 def keyword
  • Parameters let you pass data into a function
  • The return statement 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
04

Key concepts

Function definition with defParameters and argumentsReturn statementVariable scope
05

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
06

Worked examples

Problem

Write a function that adds two numbers

  1. 1. def add(a, b):
  2. 2. return a + b
  3. 3. print(add(2, 3))

Answer: 5

07

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
08

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.