Functions in Python

Functions allow us to group code into reusable blocks.
They help in reducing repetition, improving readability, and making code modular.

Why use functions?

  • Functions avoid code duplication by reusing the same code multiple times.
  • They make code organized and easier to maintain.
  • Functions can accept inputs and return outputs, enabling dynamic behavior.
  • Widely used in real-world applications for performing repeated tasks or calculations.

Examples of real-time usage:

  • A function to calculate sales tax for different orders
  • A function to validate user input on a form
  • A function to fetch and process data from a database
  • A function to send emails or notifications automatically
  • A function to convert temperature units (Celsius → Fahrenheit)

We will cover:

  1. Defining functions
  2. Function arguments
  3. Return values
  4. Default arguments
  5. Keyword arguments

Example: simple function

# ---- Example: simple function ----
# Define a function using 'def' keyword
# Function groups code we can call multiple times

def greet():
    print("Hello! Welcome to Python learning.")

# Call the function
greet()   # runs the code inside the function

Hello! Welcome to Python learning.

Example: function with arguments

# ---- Example: function with arguments ----
# Functions can accept inputs (parameters) to customize behavior

def greet_user(name):
    print("Hello,", name)

greet_user("Amit")    # pass argument
greet_user("Priya")

Hello, Amit
Hello, Priya

Example: function returning value

# ---- Example: function returning value ----
# Use 'return' to get a value from function

def add_numbers(a, b):
    return a + b

result = add_numbers(5, 7)   # function returns 12
print("Sum is:", result)

Sum is: 12

Example: default arguments

# ---- Example: default arguments ----
# If argument is not provided, default value is used

def greet(name="Guest"):
    print("Hello,", name)

greet("Amit")   # uses provided value
greet()         # uses default value "Guest"

Hello, Amit
Hello, Guest

Example: keyword arguments

# ---- Example: keyword arguments ----
# Allows passing arguments in any order by naming them

def describe_person(name, age):
    print(f"{name} is {age} years old.")

describe_person(age=25, name="Priya")   # order doesn't matter with keywords

Priya is 25 years old.

Summary

We learned about functions in Python:

  • How to define and call a function
  • Passing arguments to a function
  • Returning values from functions
  • Default arguments
  • Keyword arguments

Next notebook: 01_strings.ipynb