Skip to main content

User-Defined Functions

User-Defined Functions

In the previous lesson, we used built-in Python functions such as print(), type(), int(), float(), str(), len(), round(), and abs().

Now we will create our own functions.

A user-defined function is a reusable block of code that performs a specific task.

We use functions to:

  • avoid repeating code
  • give names to useful actions
  • organize programs into smaller parts
  • reuse the same logic with different inputs

Creating a Function

In Python, functions are created using the def keyword.

def <function_name>(<argument>):
    <code_of_the_function>

The def keyword marks the beginning of a function definition.

The function name comes after def.

The code inside the function must be indented.


Defining and Calling a Function

This code defines a function:

def greet(name):
    print(f"Hello, {name}!")

This cell does not print anything.

Python has learned that the function greet() exists, but we have not used it yet.

To use a function, we call it.

greet("Jorge")
Hello, Jorge!

We can call the same function many times.

greet("Ana")
greet("Luis")
greet("Marta")
Hello, Ana!
Hello, Luis!
Hello, Marta!

The value inside the parentheses is called an argument.

NoteExercise

Write a function called say_goodbye(name).

It should print a goodbye message using the name.

Example:

say_goodbye("Ana")

Expected output:

Goodbye, Ana!
def say_goodbye(name):
    print(f"Goodbye, {name}!")

say_goodbye("Ana")
Goodbye, Ana!

Functions Help Us Avoid Repetition

Imagine we want to print multiplication tables.

Without a function, we would repeat the same structure many times.

With a function, we write the logic once.

def multiplication_table(x):
    for n in range(1, 11):
        print(f"{x} x {n} = {x * n}")

Now we can reuse it with different numbers.

multiplication_table(3)
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15
3 x 6 = 18
3 x 7 = 21
3 x 8 = 24
3 x 9 = 27
3 x 10 = 30
multiplication_table(8)
8 x 1 = 8
8 x 2 = 16
8 x 3 = 24
8 x 4 = 32
8 x 5 = 40
8 x 6 = 48
8 x 7 = 56
8 x 8 = 64
8 x 9 = 72
8 x 10 = 80
NoteExercise

Write a function called countdown(number).

It should print the numbers from number down to 1.

Example:

countdown(5)

Expected output:

5
4
3
2
1
def countdown(number):
    for n in range(number, 0, -1):
        print(n)

countdown(5)
5
4
3
2
1

Positional Arguments

A function can receive more than one argument.

def <function_name>(<argument_1>, <argument_2>):
    <code_of_the_function>

For example, this function takes a student’s name and grade, then says if the student passed.

def check_pass(name, grade):
    if grade >= 5:
        print(f"{name} has passed!")
    else:
        print(f"{name} has failed")
check_pass("Luke", 8)
Luke has passed!
check_pass("Yoda", 2)
Yoda has failed

The arguments above are positional arguments.

That means Python uses their position to decide what each value means.

check_pass("Leia", 6)
Leia has passed!

Here:

  • "Leia" goes into name
  • 6 goes into grade

The order matters.

check_pass(6, "Leia")
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[13], line 1
----> 1 check_pass(6, "Leia")

Cell In[9], line 2, in check_pass(name, grade)
      1 def check_pass(name, grade):
----> 2     if grade >= 5:
      3         print(f"{name} has passed!")
      4     else:
      5         print(f"{name} has failed")

TypeError: '>=' not supported between instances of 'str' and 'int'

This fails because Python tries to compare "Leia" with 5.

NoteExercise

Without running the code, guess the output.

def describe_pet(name, animal):
    print(f"{name} is a {animal}")

describe_pet("Nina", "cat")
describe_pet("dog", "Rex")
Nina is a cat
dog is a Rex

The second call works, but the order is wrong. Python does not know that "dog" is probably the animal and "Rex" is probably the name.


Checking Input Types

Sometimes a function receives arguments with the wrong type.

We can check the type before continuing.

def check_pass(name, grade):
    if type(name) != str:
        print("Name must be a string")
        return

    if type(grade) != int and type(grade) != float:
        print("Grade must be a number")
        return

    if grade >= 5:
        print(f"{name} has passed!")
    else:
        print(f"{name} has failed")
check_pass("Luke", 8)
check_pass("Yoda", 2)
check_pass(6, "Leia")
Luke has passed!
Yoda has failed
Name must be a string

The return statements stop the function early.

NoteExercise

Improve the function below so that it checks whether x and y are numbers.

def addition(x, y):
    print(x + y)
def addition(x, y):
    if type(x) != int and type(x) != float:
        print("x must be a number")
        return

    if type(y) != int and type(y) != float:
        print("y must be a number")
        return

    print(x + y)