What is Computer

Module: M3-R5: Python Programming

Chapter: Ch1 Computer Intro

🔹 What is a Function?

A function in Python is a reusable block of code that performs a specific task. It helps make programs modular, readable, and efficient.

Syntax:

def function_name(parameters):
    # code block
    return value

Example:

def greet():
    print("Welcome to QuiteXams!")

greet()

Output:

Welcome to QuiteXams!
🔹 Why Use Functions?
  • To avoid repetition of code.
  • To make code organized and modular.
  • To improve readability and reusability.
  • To divide complex problems into smaller tasks.
🔹 Types of Functions in Python
1️⃣ Built-in Functions

These are predefined in Python and can be used directly.

print("Hello")
len("Python")
max(5, 10, 3)
sum([10, 20, 30])

Output:

Hello
6
10
60
2️⃣ User-Defined Functions

Created by the user using the def keyword.

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

result = add(5, 3)
print("Sum:", result)

Output:

Sum: 8
3️⃣ Lambda (Anonymous) Functions

Small, one-line functions defined using lambda keyword.

square = lambda x: x * x
print(square(5))

Output:

25
4️⃣ Recursive Functions

A function that calls itself is called a recursive function.

def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n-1)

print(factorial(5))

Output:

120
🔹 Function with Parameters and Return
def multiply(x, y):
    product = x * y
    return product

result = multiply(4, 3)
print("Product:", result)

Output:

Product: 12
✅ Summary
  • Functions help organize and reuse code.
  • Types: Built-in, User-defined, Lambda, Recursive.
  • Syntax: def function_name(parameters):
  • Use return to send data back from a function.
Quick Links