Mathew K Analytics

Lesson 9 · Pandas

Understanding Map, Replace, and Apply Functions for Effective Data Transformation in Pandas

Functions let us group code so we can reuse it. This helps keep programs organized and avoids repetition. We will explore creating, using, and understanding…

⬇ Download notebookOpen in Colab ↗

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb

Welcome to Python Functions!#

Functions let us group code so we can reuse it. This helps keep programs organized and avoids repetition.

We will explore creating, using, and understanding Python functions from the ground up.

import warnings
import numpy as np
np.random.seed(42)
warnings.filterwarnings("ignore")

# We will use variables in our function examples
name = 'Mathew'
age = 35
is_student = False
print(name, age, is_student)
Mathew 35 False

What is a Function?#

A function is a block of code designed to perform a specific task. You give it a name and run it when needed.

Instead of repeating yourself, you write the code once and call the function wherever required.

# Defining a simple function
def greet():
    print('Hello, welcome to Python functions!')

# Call the function
greet()
Hello, welcome to Python functions!
# Function with input parameter
def greet_user(username):
    print('Hello,', username, 'nice to meet you!')

greet_user('Ava')
Hello, Ava nice to meet you!
# Function with multiple parameters
def describe_person(name, age):
    print(name, 'is', age, 'years old.')

describe_person('Mathew', 35)
Mathew is 35 years old.
# Function that returns a value
def add(a, b):
    return a + b

result = add(3, 5)
print('The sum is:', result)
The sum is: 8

Function Syntax#

To make a function, use the keyword def, then the function name, and a set of parentheses. Add a colon and indent your code.

You can add input values, called parameters, inside the parentheses.

Functions can print messages, do math, or return results.

# Example: greet a user by name
def greet_by_name(name):
    print('Hello there,', name)

greet_by_name('Zoe')
Hello there, Zoe
# Function with no parameters
def say_hello():
    print('Hi there!')

say_hello()
Hi there!
# Function with default parameter values
def power(number, exponent=2):
    return number ** exponent

print(power(4))
print(power(2, 3))
16
8

Why Use Functions?#

  • You avoid copy-pasting the same code.
  • You make your program tidy and easier to fix.
  • Functions help split a big problem into smaller jobs.

When your code is short and clear, bugs are easier to spot and fix!

# Function to check if a number is even
def is_even(n):
    return n % 2 == 0

print(is_even(4))
print(is_even(7))
True
False
# Function with user input
def personalized_greeting():
    user = input("What is your name? ")
    print("Nice to meet you,", user)

personalized_greeting()
Nice to meet you, Oliver
# Function returning multiple values
def get_name_and_age():
    name = input("Enter your name: ")
    age = int(input("Enter your age: "))
    return name, age

user_name, user_age = get_name_and_age()
print('User:', user_name, '| Age:', user_age)
User: Sam | Age: 29
# Nested function usage
def square(n):
    return n * n

def sum_of_squares(x, y):
    return square(x) + square(y)

print(sum_of_squares(3, 4))
25

Quick Recap: Parameters vs Arguments#

  • Parameters are names you put in your function definition.
  • Arguments are values you give when calling the function.

This difference helps you talk about what goes in versus what is sent in.

# Using keyword arguments
def show_pet(animal, name):
    print('Your', animal, "is called", name)

show_pet(animal='cat', name='Felix')
Your cat is called Felix
# Function with arbitrary number of arguments
def print_numbers(*args):
    for number in args:
        print(number)

print_numbers(1, 2, 3, 4, 5)
1
2
3
4
5
# Function with arbitrary keyword arguments
def show_info(**kwargs):
    for key, value in kwargs.items():
        print(key, ':', value)

show_info(name='Max', age=23, city='Dublin')
name : Max
age : 23
city : Dublin

Lambda Functions (Anonymous Functions)#

A lambda is a quick way to make simple functions. Useful when you need a tiny, throwaway function.

Write: lambda argument: expression

# Lambda function example
square = lambda x: x * x
print(square(6))
36
# Use lambda with map
nums = [1, 2, 3, 4]
doubled = list(map(lambda n: n * 2, nums))
print(doubled)
[2, 4, 6, 8]
# Avoid code repetition by using functions
def print_stars(n):
    for i in range(n):
        print('*', end='')
    print()

# Instead of repeating the loop, use the function
print_stars(10)
print_stars(5)
**********
*****
# Returning early with return
def search_for(x, items):
    for item in items:
        if item == x:
            return True
    return False

numbers = [2, 4, 7, 10]
print(search_for(7, numbers))
print(search_for(1, numbers))
True
False

Real-World Example: Temperature Converter#

Let us make a function to switch Celsius to Fahrenheit degrees. This is handy for travel and science projects!

# Celsius to Fahrenheit
def celsius_to_fahrenheit(c):
    return (c * 9/5) + 32

temp_c = 25
temp_f = celsius_to_fahrenheit(temp_c)
print(temp_c, 'Celsius is', temp_f, 'Fahrenheit')
25 Celsius is 77.0 Fahrenheit
# Mini project: build a simple calculator
def calculator():
    print("Simple Calculator")
    x = float(input("Enter first number: "))
    y = float(input("Enter second number: "))
    operation = input("Choose: +, -, *, / : ")
    if operation == '+':
        return x + y
    elif operation == '-':
        return x - y
    elif operation == '*':
        return x * y
    elif operation == '/':
        if y != 0:
            return x / y
        else:
            return 'Cannot divide by zero.'
    else:
        return 'Unknown operation.'

calc_result = calculator()
print('Result:', calc_result)
Simple Calculator
Result: 7.0

Best Practices for Functions#

  1. Give your functions clear, simple names.
  2. Keep each function focused on one job.
  3. Write short, well-commented functions.
  4. Use parameters and return values to avoid using global variables.

When in doubt, break long code into small, readable pieces.

# Common mistake: forgetting return
def multiply(a, b):
    product = a * b
# No return! The function returns None by default.

result = multiply(2, 4)
print(result)
None
# Common mistake: not using parentheses
def say_hi():
    print('Hi!')

func_reference = say_hi
func_reference()
Hi!
# Good practice: document your function
def double(x):
    """This function returns twice the value given."""
    return x * 2

print(double(8))
16

Your Turn! Short Function Challenges#

  1. Write a function that takes a number and prints "Odd" or "Even".
  2. Make a function that returns the square of a number.
  3. Write a function that adds three numbers.

Try these before peeking at the answers.

# Challenge: Odd or Even
def odd_or_even(num):
    if num % 2 == 0:
        print('Even')
    else:
        print('Odd')

odd_or_even(13)
odd_or_even(8)
Odd
Even
# Challenge: Square of a number
def my_square(x):
    return x * x

print(my_square(11))
121
# Challenge: Add three numbers
def add_three(a, b, c):
    return a + b + c

print(add_three(2, 4, 8))
14

Recap: What You Learned about Functions#

  • Functions help you write reusable, readable code.
  • You can make your own functions with def.
  • Functions take inputs and can give outputs with return.
  • Parameters and arguments are important for working with information.

With practice, you will build bigger and better programs!

Thanks for Learning with Us!#

If you enjoyed this lesson, please subscribe and like the video.

Keep practicing and come back for more Python skills!

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.