Skip to main content
Editor

Python Functions: Define, Call, and Return Values

Beginner25 min7 exercises110 XP

Leer en españolЧитать на русскомLer em portuguêsอ่านภาษาไทย

0/7 exercises

Imagine you have a favorite recipe for pancakes. Every Sunday morning, you follow the same steps: mix flour, crack eggs, pour batter, flip. You don't reinvent the recipe each time - you just follow the one you already know.

Functions in Python work exactly like recipes. You write the instructions once, give them a name, and then call that name whenever you need those instructions to run again. Write once, use anywhere.

In this tutorial, you'll learn how to create your own functions, pass data into them, and get results back. By the end, you'll be writing clean, reusable code like a real developer.

How to Define Your First Function

To create a function in Python, you use the def keyword, followed by a name, parentheses, and a colon. Everything indented underneath belongs to that function.

Defining a function
def greet():
print('Hello there!')
print('Welcome to Python.')
Output
(no output)

If you run the code above, nothing happens. That's because defining a function is like writing down a recipe. It doesn't cook anything until you actually follow the steps.

To actually run the function, you call it by writing its name followed by parentheses:

Calling a function
def greet():
print('Hello there!')
print('Welcome to Python.')
greet()
Output
Hello there!
Welcome to Python.

Now you see the output. The parentheses () after greet are what tell Python to actually run the function. Without them, Python just looks at the recipe without cooking.

You can call a function as many times as you want. Each call runs all the code inside the function from top to bottom.

Calling a function multiple times
def greet():
print('Hello there!')
greet()
greet()
greet()
Output
Hello there!
Hello there!
Hello there!

What Are Parameters and Arguments?

Our greet() function always says the same thing. That's like a recipe that only makes plain pancakes. What if you want blueberry pancakes? You need a way to pass in ingredients.

In Python, you pass data into a function using parameters. A parameter is a variable name listed inside the parentheses of the function definition. When you call the function, the actual value you send in is called an argument.

A function with one parameter
def greet(name):
print('Hello, ' + name + '!')
greet('Alice')
greet('Bob')
Output
Hello, Alice!
Hello, Bob!

Here, name is the parameter - a placeholder. When we call greet('Alice'), the string 'Alice' is the argument - the actual value that fills the placeholder.

How Do Return Values Work?

So far, our functions just print things. But most of the time, you want a function to calculate something and hand the result back to you. That's what return does.

Think of it this way: print() is like shouting the answer out loud. return is like writing the answer on a piece of paper and handing it to whoever asked.

Returning a value
def add(a, b):
return a + b
result = add(3, 5)
print(result)
Output
8

The return statement does two things: it sends a value back to wherever the function was called, and it immediately exits the function. Any code after return inside the same function will not run.

Code after return is unreachable
def add(a, b):
return a + b
print('This line never runs!')
print(add(3, 5))
Output
8
Printing (side effect)
def add(a, b):
    print(a + b)

# Can't reuse the result
add(3, 5)
Returning (gives back a value)
def add(a, b):
    return a + b

# Can store, reuse, combine
result = add(3, 5)
print(result * 2)

Using Multiple Parameters

Functions can accept as many parameters as you need. Just separate them with commas. When calling, the arguments are matched to parameters in order - the first argument goes to the first parameter, and so on.

A function with three parameters
def introduce(name, age, city):
print(name + ' is ' + str(age) + ' years old and lives in ' + city + '.')
introduce('Alice', 25, 'New York')
introduce('Bob', 30, 'London')
Output
Alice is 25 years old and lives in New York.
Bob is 30 years old and lives in London.

The order matters. If you swap the arguments around, you'll get nonsense results or an error. introduce(25, 'Alice', 'London') would try to use 25 as a name.

What Are Default Parameter Values?

Sometimes you want a parameter to have a fallback value - a sensible default that's used when the caller doesn't provide one. You set this with an = sign in the definition.

Default parameter value
def greet(name, greeting='Hello'):
print(greeting + ', ' + name + '!')
greet('Alice')
greet('Bob', 'Hey')
Output
Hello, Alice!
Hey, Bob!

When we call greet('Alice'), the greeting parameter uses its default value 'Hello'. When we call greet('Bob', 'Hey'), we override the default with 'Hey'.

Can Functions Call Other Functions?

Yes. In fact, this is one of the most powerful ideas in programming. You can build small, focused functions and then combine them like building blocks.

Functions calling functions
def square(n):
return n * n
def sum_of_squares(a, b):
return square(a) + square(b)
result = sum_of_squares(3, 4)
print(result)
Output
25

Here, sum_of_squares calls square twice. Each small function does one simple job. Together, they solve a bigger problem. This approach makes your code easier to read, test, and fix.

Using a helper function
def is_even(n):
return n % 2 == 0
def describe_number(n):
if is_even(n):
return str(n) + ' is even'
else:
return str(n) + ' is odd'
print(describe_number(7))
print(describe_number(10))
Output
7 is odd
10 is even

Practice Exercises

Say Hello
Write Code

Write a function called say_hello that takes a name parameter and prints Hello, <name>! (with the exclamation mark). For example, say_hello('World') should print Hello, World!.

# Define your function here
# Test it
say_hello('World')
say_hello('Python')
Predict the Output
Predict Output

Read the code below carefully. What will it print? Type the exact output.

def double(x):
    return x * 2

result = double(7)
print(result)
print(double(3))
def double(x):
return x * 2
result = double(7)
print(result)
print(double(3))
Area of a Rectangle
Write Code

Write a function called area that takes width and height as parameters and returns their product (the area of a rectangle). Do not print - just return the value.

# Define your function here
# Test it
print(area(5, 3))
print(area(10, 7))
Fix the Broken Function
Fix the Bug

This function is supposed to return the larger of two numbers, but running it prints numbers and then None instead. Fix it so bigger(3, 7) returns 7 and bigger(10, 5) returns 10.

def bigger(a, b):
if a > b:
print(a)
print(b)
print(bigger(3, 7))
print(bigger(10, 5))
Temperature Converter
Write Code

Write a function called celsius_to_fahrenheit that takes a temperature in Celsius and returns it converted to Fahrenheit. The formula is: F = C * 9/5 + 32. Return the result as a float (the formula naturally produces one).

# Define your function here
# Test it
print(celsius_to_fahrenheit(0))
print(celsius_to_fahrenheit(100))
print(celsius_to_fahrenheit(37))
Build a Grade Calculator
Write Code

Write a function called get_grade that takes a numeric score (0-100) and returns a letter grade as a string:

  • 90 and above: 'A'
  • 80-89: 'B'
  • 70-79: 'C'
  • 60-69: 'D'
  • Below 60: 'F'
  • # Define your function here
    # Test it
    print(get_grade(95))
    print(get_grade(83))
    print(get_grade(72))
    print(get_grade(65))
    print(get_grade(45))
    Readable Durations
    Stretch

    Write a function describe_duration(seconds) that turns a whole number of seconds into text a person can read:

    describe_duration(3725)   # '1 hour, 2 minutes and 5 seconds'
    describe_duration(120)    # '2 minutes'

    The rules:

  • Use hours, minutes and seconds (no days: 90,000 seconds is 25 hours). Leave out any unit that is zero.
  • Write 1 hour, 1 minute, 1 second for one, and add an s for any other number.
  • Join the last two parts with " and " and any others with ", ".
  • 0 seconds is "now".
  • A small helper function for the singular and plural will keep your main function short. Some of the tests are hidden.

    def describe_duration(seconds):
    pass
    Solution unlocks after your first Check

    Harder problems

    More problems on this topic: Functions

    Related Tutorials

    Was this tutorial helpful?