Cristhian Villegas
Backend10 min read1 views

Python Course #4: Functions — Organize and Reuse Your Code

Python Course #4: Functions — Organize and Reuse Your Code

Introduction: what are functions and why use them

Welcome to Part 4 of 10 of the Python course for beginners. In the previous article you learned how to use conditionals and loops to control the flow of your program. Now we are going to learn something that will change the way you code forever: functions.

Python Logo

Imagine you have a favorite cooking recipe. Every time you want to prepare that dish, you do not reinvent the recipe from scratch — you simply follow it step by step. A function in Python is exactly that: a set of instructions with a name that you can reuse as many times as you want without writing the same code over and over again.

Functions help you:

  • Avoid repeating code: you write the logic once and use it many times
  • Organize your program: you break a big problem into small, manageable parts
  • Make maintenance easier: if you need to change something, you change it in one place only
  • Make your code more readable: a descriptive function name tells you what it does without reading the details

Defining a function with def

To create a function in Python you use the def keyword, followed by the function name, parentheses, and a colon:

python
1# Define the function
2def greet():
3    print("Hello! Welcome to the program")
4    print("I hope you have a great day")
5
6# Call (use) the function
7greet()
8greet()  # You can call it as many times as you want

Output:

bash
1Hello! Welcome to the program
2I hope you have a great day
3Hello! Welcome to the program
4I hope you have a great day
📌 Important: Defining a function does not execute it. It only "registers" it in memory. For it to run, you must call it by writing its name followed by parentheses: greet().

Rules for naming functions:

  • Use descriptive names: calculate_average is better than ca
  • Use lowercase and underscores: my_function (not MyFunction)
  • The name should indicate what the function does: send_email, calculate_area, validate_age

Parameters and arguments

Functions become really useful when you can send them information. That information is called parameters (when you define the function) and arguments (when you call it).

python
1# "name" is a parameter
2def greet_person(name):
3    print(f"Hello, {name}! How are you?")
4
5# "Ana" and "Carlos" are arguments
6greet_person("Ana")
7greet_person("Carlos")

Output:

bash
1Hello, Ana! How are you?
2Hello, Carlos! How are you?

You can have multiple parameters separated by commas:

python
1def introduce(name, age, city):
2    print(f"My name is {name}, I am {age} years old and I live in {city}")
3
4introduce("Laura", 25, "Guadalajara")
5introduce("Miguel", 30, "Monterrey")
💡 Tip: Think of parameters as "blanks" that the function needs you to fill in with information each time you call it. If the function has 3 parameters, you must pass it 3 arguments.

Returning values with return

So far our functions only print text. But many times you need a function to calculate something and give you back the result. For that you use return:

python
1def add(a, b):
2    result = a + b
3    return result
4
5# Save the result in a variable
6total = add(5, 3)
7print(f"The sum is: {total}")  # The sum is: 8
8
9# You can also use it directly
10print(add(10, 20))  # 30

The difference between print and return is very important:

print()return
Shows text on the screenSends a value back to whoever called the function
You cannot save what it prints in a variableYou can save the result in a variable
The function keeps running after printThe function stops immediately after return
python
1def is_adult(age):
2    if age >= 18:
3        return True
4    else:
5        return False
6
7# Use the result in a conditional
8if is_adult(20):
9    print("Can enter")
10else:
11    print("Cannot enter")
⚠️ Watch out: When Python reaches a return, the function ends immediately. Any code after the return will not execute.

Default parameter values

You can give a parameter a default value. If you do not pass that argument when calling the function, it will use the default value:

python
1def greet(name, greeting="Hello"):
2    print(f"{greeting}, {name}!")
3
4greet("Ana")                   # Hello, Ana!
5greet("Carlos", "Good morning")  # Good morning, Carlos!

This is very useful for functions that have "optional" options:

python
1def create_profile(name, age, country="Mexico"):
2    print(f"Name: {name}")
3    print(f"Age: {age}")
4    print(f"Country: {country}")
5    print()
6
7create_profile("Laura", 25)               # Uses "Mexico" by default
8create_profile("John", 30, "United States")  # Uses the country we passed
📌 Important rule: Parameters with default values must always go at the end. This is not valid: def function(country="Mexico", name). The correct way is: def function(name, country="Mexico").

Keyword arguments

When you call a function, you normally pass arguments in order. But you can also use the parameter name to be more explicit:

python
1def create_account(username, email, plan="basic"):
2    print(f"Username: {username}")
3    print(f"Email: {email}")
4    print(f"Plan: {plan}")
5
6# By position (order matters)
7create_account("ana123", "[email protected]", "premium")
8
9# By name (order does not matter)
10create_account(email="[email protected]", username="carlos456", plan="pro")

Keyword arguments make your code more readable, especially when a function has many parameters. It becomes clear what each value means.

Variable scope: local vs global

The scope of a variable determines where you can use it. There are two main types:

Local variables

A variable created inside a function only exists inside that function. When the function ends, the variable disappears:

python
1def my_function():
2    message = "Hello from the function"  # LOCAL variable
3    print(message)
4
5my_function()
6# print(message)  # ERROR: "message" does not exist outside the function

Global variables

A variable created outside any function is global and can be read from anywhere:

python
1app_name = "My Program"  # GLOBAL variable
2
3def show_welcome():
4    print(f"Welcome to {app_name}")  # Can READ the global variable
5
6show_welcome()
⚠️ Best practice: Avoid modifying global variables inside functions. If you need a function to produce a result, use return. Modifying global variables makes your code hard to understand and maintain.

Example showing the difference:

python
1x = 10  # Global variable
2
3def change_x():
4    x = 20  # This creates a LOCAL variable called "x"
5    print(f"Inside the function: x = {x}")
6
7change_x()
8print(f"Outside the function: x = {x}")  # Still 10

Output:

bash
1Inside the function: x = 20
2Outside the function: x = 10

Lambda functions

A lambda function is a small, anonymous function written in a single line. It is useful for simple operations that do not need a name:

python
1# Normal function
2def double(x):
3    return x * 2
4
5# Same function as a lambda
6double_lambda = lambda x: x * 2
7
8print(double(5))         # 10
9print(double_lambda(5))  # 10

Lambdas are especially useful when you need to pass a small function as an argument to another function:

python
1# Sort a list of tuples by the second element
2students = [("Ana", 85), ("Carlos", 92), ("Maria", 78)]
3sorted_students = sorted(students, key=lambda x: x[1])
4print(sorted_students)
5# [('Maria', 78), ('Ana', 85), ('Carlos', 92)]
6
7# Filter even numbers from a list
8numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
9evens = list(filter(lambda x: x % 2 == 0, numbers))
10print(evens)  # [2, 4, 6, 8, 10]
💡 Tip: Use lambda only for very simple functions (one expression). If the logic is complex, it is better to use a regular function with def because it will be easier to read and maintain.

Useful built-in Python functions

Python comes with many ready-made functions you can use without importing anything. Here are the most useful ones for beginners:

python
1# len() - Length of a sequence
2print(len("Python"))         # 6
3print(len([1, 2, 3, 4, 5]))  # 5
4
5# max() and min() - Maximum and minimum value
6print(max(10, 25, 3, 47))     # 47
7print(min(10, 25, 3, 47))     # 3
8print(max([85, 92, 78, 95]))  # 95
9
10# sum() - Sum of a sequence
11grades = [85, 92, 78, 95, 88]
12print(sum(grades))  # 438
13
14# sorted() - Sort a sequence
15numbers = [5, 2, 8, 1, 9, 3]
16print(sorted(numbers))              # [1, 2, 3, 5, 8, 9]
17print(sorted(numbers, reverse=True))  # [9, 8, 5, 3, 2, 1]
18
19# abs() - Absolute value
20print(abs(-15))   # 15
21print(abs(7))     # 7
22
23# round() - Round a number
24print(round(3.14159, 2))  # 3.14
25print(round(7.5))         # 8

Example combining several functions to calculate statistics:

python
1grades = [85, 92, 78, 95, 88, 70, 100]
2
3print(f"Total grades: {len(grades)}")
4print(f"Highest grade: {max(grades)}")
5print(f"Lowest grade: {min(grades)}")
6print(f"Total sum: {sum(grades)}")
7print(f"Average: {round(sum(grades) / len(grades), 2)}")
8print(f"Sorted grades: {sorted(grades)}")

Practical example: complete calculator

Let's create a calculator that uses functions for each operation. This example combines everything you learned in this article:

python
1def add(a, b):
2    return a + b
3
4def subtract(a, b):
5    return a - b
6
7def multiply(a, b):
8    return a * b
9
10def divide(a, b):
11    if b == 0:
12        return "Error: cannot divide by zero"
13    return a / b
14
15def show_menu():
16    print("
17=== Python Calculator ===")
18    print("1. Add")
19    print("2. Subtract")
20    print("3. Multiply")
21    print("4. Divide")
22    print("5. Exit")
23
24def get_numbers():
25    num1 = float(input("First number: "))
26    num2 = float(input("Second number: "))
27    return num1, num2
28
29# Main program
30while True:
31    show_menu()
32    choice = input("
33Choose an option (1-5): ")
34
35    if choice == "5":
36        print("Goodbye!")
37        break
38
39    if choice not in ["1", "2", "3", "4"]:
40        print("Invalid option. Try again.")
41        continue
42
43    num1, num2 = get_numbers()
44
45    if choice == "1":
46        result = add(num1, num2)
47        print(f"{num1} + {num2} = {result}")
48    elif choice == "2":
49        result = subtract(num1, num2)
50        print(f"{num1} - {num2} = {result}")
51    elif choice == "3":
52        result = multiply(num1, num2)
53        print(f"{num1} * {num2} = {result}")
54    elif choice == "4":
55        result = divide(num1, num2)
56        print(f"{num1} / {num2} = {result}")
📌 What does this program do?
  • Defines a function for each math operation (add, subtract, multiply, divide)
  • Uses show_menu() to keep the interface organized
  • Uses get_numbers() to avoid repeating the number input code
  • The divide function handles the special case of division by zero
  • Uses a while True loop with break so the user can perform multiple operations

Summary and next article

In this article you learned how to organize your code with functions:

  • def: defines a function with a reusable name
  • Parameters and arguments: allow you to send information to the function
  • return: sends a result back to the code that called the function
  • Default values: optional parameters with a predefined value
  • Keyword arguments: named arguments for greater clarity
  • Scope: local variables live inside the function, global variables live outside
  • Lambda: anonymous one-line functions for simple operations
  • Built-in functions: len(), max(), min(), sum(), sorted(), abs()

Functions are one of the most important tools in any programming language. From now on, every time you see repeated code, think: "this should be a function". In the next article (Part 5 of 10) we will learn about lists, tuples, and dictionaries: the data structures that will allow you to store and organize collections of information.

Share:
CV

Cristhian Villegas

Software Engineer specializing in Java, Spring Boot, Angular & AWS. Building scalable distributed systems with clean architecture.

Comments

Sign in to leave a comment

No comments yet. Be the first!

Related Articles