Lesson 34 of 70 – Python Functions
49%

Python Functions

A function is a reusable block of code that performs a specific task. Functions help us organize code, avoid repetition, and make programs easier to understand and maintain.

Note: A function runs when it is called. In Python, functions are created using the def keyword.
1. What is a Function?

A function is a named block of code that can be executed whenever it is needed.

def greet():
    print("Hello!")

greet()
Output:
Hello!
2. Why Use Functions?

Functions provide several benefits:

  • They reduce code repetition.
  • They make programs easier to understand.
  • They make code easier to maintain.
  • They allow code to be reused.
  • They divide a large program into smaller tasks.
3. Creating a Function

Use the def keyword followed by the function name and parentheses.

def welcome():
    print("Welcome to Python")

The indented code below the function definition is called the function body.

4. Function Syntax
def function_name():
    # function body
    statement

Example:

def hello():
    print("Hello Python")
5. Calling a Function

Defining a function does not execute it. You need to call the function.

def greet():
    print("Good Morning")

greet()
Output:
Good Morning
6. Calling a Function Multiple Times

A function can be called multiple times.

def greet():
    print("Hello!")

greet()
greet()
greet()
Output:
Hello!
Hello!
Hello!
7. Function Without Parameters

A function does not always need parameters.

def show_message():
    print("Learn Python")

show_message()
Output:
Learn Python
8. Function with One Parameter

A parameter allows a function to receive data.

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

greet("Amit")
Output:
Hello Amit

Here, name is the parameter and "Amit" is the argument passed to the function.

9. Function with Multiple Parameters

A function can have more than one parameter.

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

add(10, 20)
Output:
30
10. Parameters and Arguments

A parameter is a variable defined inside the function definition. An argument is the actual value passed when calling the function.

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

greet("Rahul")
  • name → Parameter
  • "Rahul" → Argument
11. Returning a Value

A function can send a result back to the calling code using the return statement.

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

result = add(10, 20)

print(result)
Output:
30
12. Difference Between print() and return

print() displays a value on the screen, while return sends a value back from the function.

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

result = add(5, 10)

print(result)
Output:
15
13. Function Returning Multiple Values

A Python function can return multiple values. Python packages these values into a tuple.

def calculate(a, b):
    return a + b, a - b

result = calculate(20, 5)

print(result)
Output:
(25, 15)
14. Storing Returned Values in Variables
def calculate(a, b):
    return a + b, a * b

sum_value, product = calculate(5, 4)

print("Sum:", sum_value)
print("Product:", product)
Output:
Sum: 9
Product: 20
15. Default Parameter Value

A parameter can have a default value. The default value is used when no argument is supplied for that parameter.

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

greet()
greet("Amit")
Output:
Hello Student
Hello Amit
16. Keyword Arguments

You can pass arguments using parameter names.

def student(name, age):
    print("Name:", name)
    print("Age:", age)

student(age=20, name="Rahul")
Output:
Name: Rahul
Age: 20
17. Positional Arguments

When arguments are passed according to their position, they are called positional arguments.

def student(name, age):
    print(name)
    print(age)

student("Amit", 21)
Output:
Amit
21
18. Function with a Calculation
def square(number):
    return number * number

print(square(5))
print(square(8))
Output:
25
64
19. Function for Checking Even or Odd
def check_number(number):

    if number % 2 == 0:
        return "Even"
    else:
        return "Odd"

print(check_number(10))
print(check_number(7))
Output:
Even
Odd
20. Function with Conditional Logic
def check_age(age):

    if age >= 18:
        return "Eligible"
    else:
        return "Not Eligible"

print(check_age(20))
print(check_age(15))
Output:
Eligible
Not Eligible
21. Function with a List

A list can be passed to a function as an argument.

def display_items(items):

    for item in items:
        print(item)

fruits = ["Apple", "Banana", "Mango"]

display_items(fruits)
Output:
Apple
Banana
Mango
22. Function with a Dictionary
def show_student(student):

    for key, value in student.items():
        print(key, ":", value)

data = {
    "name": "Amit",
    "course": "Python"
}

show_student(data)
Output:
name : Amit
course : Python
23. Function Without return

If a function does not explicitly return a value, Python returns None.

def greet():
    print("Hello")

result = greet()

print(result)
Output:
Hello
None
24. Local Variables

A variable created inside a function is generally a local variable. It can normally be accessed only inside that function.

def show():

    message = "Hello Python"

    print(message)

show()
Output:
Hello Python
25. Function Scope

Variables created inside a function have local scope unless they refer to variables from an outer scope.

def calculate():

    number = 100

    print(number)

calculate()

The variable number is local to the function.

26. Calling One Function from Another

One function can call another function.

def message():
    print("Welcome to Python")

def start():
    message()
    print("Let's learn programming")

start()
Output:
Welcome to Python
Let's learn programming
27. Reusable Function Example

A function can be reused with different arguments.

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

print(multiply(2, 5))
print(multiply(4, 10))
print(multiply(7, 3))
Output:
10
40
21
28. Function Naming Rules

Function names should follow Python's naming rules:

  • A function name can contain letters, numbers, and underscores.
  • A function name cannot start with a number.
  • Spaces are not allowed in function names.
  • Python keywords cannot be used as function names.
  • Using descriptive names makes code easier to understand.

Example:

def calculate_total():
    print("Calculating total")
29. Function Documentation

A function can contain a docstring that describes what the function does.

def add(a, b):
    """Return the sum of two numbers."""
    return a + b

print(add(10, 20))
Output:
30
30. Practical Example – Student Result
def calculate_result(marks):

    total = sum(marks)
    average = total / len(marks)

    return total, average

marks = [80, 75, 90, 85]

total, average = calculate_result(marks)

print("Total:", total)
print("Average:", average)
Output:
Total: 330
Average: 82.5
31. Key Points
  • A function is a reusable block of code.
  • Functions are created using the def keyword.
  • A function runs when it is called.
  • Functions can accept parameters.
  • Arguments are values passed to functions.
  • The return statement sends a result back to the caller.
  • Functions can have default parameter values.
  • Arguments can be positional or keyword arguments.
  • Functions help reduce code repetition.
  • Functions make large programs easier to organize.
  • A function without an explicit return value returns None.
  • Python also supports advanced function concepts such as arbitrary arguments, lambda functions, recursion, and decorators.

🧠 Quick Quiz

Question: Which keyword is used to define a function in Python?