Skip to main content

What are Functions?

A Function is a reusable block of code designed to perform a specific job. Instead of copying and pasting the exact same lines of code over and over again, you package them into a function and call it whenever you need it.

Think of a function like a coffee machine:

  • You give it inputs (water and coffee powder)
  • It performs a job inside (brewing)
  • It hands you back an output (hot coffee)

Defining and Calling a Function (def)

You define a function using the keyword def, followed by the function name, parentheses (), and a colon ::

# 1. Defining the function
def greet_user():
print("Welcome to Python Lab!")
print("Let's write some code.")

# 2. Calling (running) the function
greet_user()

Passing Inputs (Parameters & Arguments)

You can pass information inside parentheses so the function can use it.

  • Parameter: The variable name inside the function definition waiting to receive data.
  • Argument: The actual value you pass when calling the function.
# 'name' is the parameter
def greet(name):
print(f"Hello, {name}!")

# 'Alice' is the argument
greet("Alice")
greet("Bob")

return vs. print()

A very important concept for beginners is the difference between print() and return:

  • print() is only for your eyes: It shows text on the screen, but Python immediately forgets the value. You cannot save it into a variable or use it later in math.
  • return hands data back to Python: It sends the computed output back to your program so you can store it inside a variable and use it downstream.
def add_numbers(a, b):
# Return sends the result back to whoever called the function
return a + b

# Store the returned result inside a variable
total = add_numbers(10, 15)
print(f"The total is: {total}") # Output: The total is: 25
Return stops the function

As soon as Python runs a return statement, it exits the function immediately. Any lines of code written below the return statement will never run!

Common Beginner Mistakes
  • Forgetting Parentheses: Typing greet_user without () only references the function object. You must add () to invoke and run it (greet_user()).
  • print() vs return: print() only displays text in the terminal and returns None. If you want to store or calculate with the function output, you must use return.

Quick Summary

  • def Keyword: Defines a named, reusable block of logic.
  • Parameters & Arguments: Parameters are function inputs; arguments are the values passed at invocation.
  • return Statement: Sends output data back to the caller and exits the function immediately.
  • Reusability (DRY): Eliminates copy-pasted duplicate logic across your project.

What's Next?

Let's learn how to set default values for function inputs and understand how variable scope works in the next lesson!