#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
6 min read

Functions Basics

Learn to create reusable code blocks with functions

What You'll Learn

  • What functions are
  • Creating functions
  • Using parameters
  • Returning values

What is a Function?

A function is a reusable block of code. Write it once, use it many times!

Like a recipe:

  • Give it a name
  • List the steps
  • Use it whenever needed

Creating a Simple Function

code.py
def greet():
    print("Hello!")

# Use the function
greet()
# Shows: Hello!

Format:

code.py
def function_name():
    # code here

Functions with Parameters

Give the function information:

code.py
def greet(name):
    print(f"Hello {name}!")

greet("John")
# Shows: Hello John!

greet("Sarah")
# Shows: Hello Sarah!

Multiple Parameters

code.py
def introduce(name, age):
    print(f"My name is {name}")
    print(f"I am {age} years old")

introduce("John", 25)

Output:

My name is John I am 25 years old

Returning Values

Send back a result:

code.py
def add(a, b):
    result = a + b
    return result

total = add(5, 3)
print(total)
# Shows: 8

Shorter way:

code.py
def add(a, b):
    return a + b

Practice Examples

Example 1: Calculate area

code.py
def calculate_area(length, width):
    area = length * width
    return area

room_area = calculate_area(10, 12)
print(f"Room area: {room_area}")
# Shows: Room area: 120

Example 2: Check even/odd

code.py
def is_even(number):
    if number % 2 == 0:
        return True
    else:
        return False

print(is_even(4))   # True
print(is_even(7))   # False

Example 3: Greet with time

code.py
def greet_time(name, time):
    if time < 12:
        print(f"Good morning, {name}!")
    elif time < 18:
        print(f"Good afternoon, {name}!")
    else:
        print(f"Good evening, {name}!")

greet_time("John", 9)   # Good morning, John!
greet_time("Sarah", 15) # Good afternoon, Sarah!

Default Parameters

Set default values:

code.py
def greet(name="Guest"):
    print(f"Hello {name}!")

greet("John")  # Hello John!
greet()        # Hello Guest!
code.py
def calculate_price(price, tax=0.08):
    total = price + (price * tax)
    return total

# With tax
print(calculate_price(100))        # 108.0

# Custom tax
print(calculate_price(100, 0.10))  # 110.0

Multiple Return Values

Return more than one thing:

code.py
def get_stats(numbers):
    total = sum(numbers)
    count = len(numbers)
    average = total / count
    return total, average

my_total, my_avg = get_stats([10, 20, 30])
print(f"Total: {my_total}")
print(f"Average: {my_avg}")

Real-World Examples

Example 1: Temperature converter

code.py
def celsius_to_fahrenheit(celsius):
    fahrenheit = (celsius * 9/5) + 32
    return fahrenheit

temp_f = celsius_to_fahrenheit(25)
print(f"25°C = {temp_f}°F")
# Shows: 25°C = 77.0°F

Example 2: Calculate discount

code.py
def apply_discount(price, discount_percent):
    discount = price * (discount_percent / 100)
    final_price = price - discount
    return final_price

original = 100
sale_price = apply_discount(100, 20)
print("Original: $" + str(original))
print("Sale: $" + str(sale_price))

Example 3: Validate email

code.py
def is_valid_email(email):
    if "@" in email and "." in email:
        return True
    else:
        return False

print(is_valid_email("john@gmail.com"))  # True
print(is_valid_email("invalid"))         # False

Functions Calling Functions

code.py
def add(a, b):
    return a + b

def multiply(a, b):
    return a * b

def calculate(x, y):
    sum_result = add(x, y)
    product = multiply(x, y)
    return sum_result, product

s, p = calculate(5, 3)
print(f"Sum: {s}, Product: {p}")
# Shows: Sum: 8, Product: 15

Common Mistakes

Mistake 1: Forgetting parentheses

code.py
# Wrong
def greet:
    print("Hello")

# Correct
def greet():
    print("Hello")

Mistake 2: Forgetting to call function

code.py
def greet():
    print("Hello")

# This doesn't run the function
greet

# This runs it
greet()

Mistake 3: Using return value without return

code.py
# Wrong - no return
def add(a, b):
    result = a + b

total = add(5, 3)
print(total)  # None

# Correct
def add(a, b):
    return a + b

Mistake 4: Code after return

code.py
def greet():
    return "Hello"
    print("Hi")  # Never runs!

Quick Reference

Basic function:

code.py
def function_name():
    # code

With parameters:

code.py
def function_name(param1, param2):
    # code

Return value:

code.py
def function_name():
    return value

Default parameters:

code.py
def function_name(param="default"):
    # code

Why Use Functions?

1. Reusability: Write once, use many times

2. Organization: Break big problems into small pieces

3. Easier to fix: Fix in one place

4. Easier to read: Names explain what code does

Summary

  • Functions are reusable code blocks
  • Use def to create functions
  • Parameters give input to functions
  • return sends back output
  • Default parameters are optional
  • Functions make code cleaner and reusable

What's Next?

Now let's learn advanced function concepts!

SkillsetMaster - AI, Web Development & Data Analytics Courses