Functions in Python

A function is a reusable block of code that performs a specific task. Functions help make programs modular, readable, and easier to maintain.

💡 Python functions are defined using the def keyword.

Defining a Function

You can define a function using def, followed by the function name and parentheses.

def greet():
    print("Hello, welcome to Python!")

greet()

Function with Parameters

Parameters allow you to pass data into a function.

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

greet("Khushi")
greet("Python")

Function with Return Value

A function can return a value using the return keyword.

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

result = add(5, 3)
print(result)

Default Parameters

You can assign default values to parameters.

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

greet()
greet("Khushi")

Common Mistakes

❌ Forgetting to call the function
❌ Not using return when a value is needed
❌ Indentation errors inside functions

Practice Exercises

  1. Create a function that prints your name
  2. Create a function that adds two numbers
  3. Create a function that checks if a number is even