Function in python

 


Here is a clear and easy explanation of Functions in Python with examples 👇


What is a Function in Python?

A function is a block of code that performs a specific task.

✔️ Why use functions?

  • To avoid repeating code
  • To make programs cleaner
  • To make code reusable
  • To make debugging easier

🧩 Types of Functions

Python has two types of functions:

1️⃣ Built-in Functions

These come with Python.
Examples:

  • print()
  • len()
  • type()
  • input()
  • sum()

2️⃣ User-defined Functions

Functions you create using the def keyword.


✏️ How to Create a Function

Syntax:

def function_name():
    # code

Example:

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

Call the function:

greet()

📥 Function with Parameters

Parameters = data you pass into a function.

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

add(5, 3)

📤 Function with Return Value

return sends a value back from the function.

def multiply(x, y):
    return x * y

result = multiply(4, 5)
print(result)

🎯 Default Parameters

If no value is passed, default is used.

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

greet()
greet("Meenu")

🔄 Function with Variable Number of Arguments

*1. args → multiple positional args

def total(*numbers):
    print(sum(numbers))

total(1, 2, 3, 4)

**2. kwargs → keyword arguments

def info(**data):
    print(data)

info(name="Meenu", age=21)

🧱 Anonymous Function (Lambda)

Small one-line function.

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

🧠 Example Program

Write a function to check if a number is even or odd:

def check(num):
    if num % 2 == 0:
        return "Even"
    else:
        return "Odd"

print(check(11)


Sure! Here is MORE detailed explanation of Functions in Python with advanced concepts, diagrams (text form), examples, and practice questions 👇


🔥 More About Functions in Python

⭐ 1. Function Structure (Diagram)

        +---------------------+
        |   def keyword       |
        +---------------------+
                |
                v
        +---------------------+
        | function_name()     |
        +---------------------+
                |
                v
        +---------------------+
        |  parameters (optional)
        +---------------------+
                |
                v
        +---------------------+
        |   Function body     |
        +---------------------+
                |
                v
        +---------------------+
        |  return (optional)  |
        +---------------------+

⭐ 2. Function Naming Rules

A function name:

  • must start with a letter or underscore
  • cannot start with a number
  • can only contain letters, digits, and underscores
  • should be descriptive

Example: ✔️ calculate_total()
123total()


⭐ 3. Function with Multiple Returns

def calculator(a, b):
    sum_ = a + b
    diff = a - b
    return sum_, diff

result = calculator(10, 5)
print(result)

Output:

(15, 5)

⭐ 4. Function Calling Another Function

def greet():
    print("Hello")

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

welcome()

⭐ 5. Scope of Variables → Local & Global

✔️ Local Variable

Declared inside a function.

def test():
    x = 10   # local variable
    print(x)

✔️ Global Variable

Declared outside functions.

x = 50

def show():
    print(x)

show()

⭐ 6. Using global Keyword

x = 10

def change():
    global x
    x = 20

change()
print(x)

⭐ 7. Function Documentation (Docstring)

Used to explain what a function does.

def add(a, b):
    """This function returns the sum of two numbers"""
    return a + b

print(add.__doc__)

⭐ 8. Recursive Function

A function calling itself.

Example: factorial

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

print(factorial(5))

⭐ 9. Function Inside Function (Nested Function)

def outer():
    def inner():
        print("Inside inner")
    inner()

outer()

⭐ 10. Higher-Order Functions

A function that accepts or returns another function.

✔️ Passing a function as argument:

def add(x):
    return x + 5

def apply(func, value):
    return func(value)

print(apply(add, 10))

⭐ 11. map(), filter(), reduce()

✔️ map() → apply function to each element

nums = [1, 2, 3, 4]
square = list(map(lambda x: x*x, nums))
print(square)

✔️ filter() → filter values

nums = [1, 2, 3, 4, 5]
even = list(filter(lambda x: x % 2 == 0, nums))
print(even)

✔️ reduce()

from functools import reduce
nums = [1, 2, 3]

total = reduce(lambda a, b: a + b, nums)
print(total)

⭐ 12. Function Annotations (Type Hinting)

def add(a: int, b: int) -> int:
    return a + b

⭐ 13. Lambda in map/filter

nums = [2, 4, 6]
result = list(map(lambda x: x*10, nums))
print(result)

⭐ 14. Anonymous Functions in Sorting

students = [(1, "Ram"), (3, "Asha"), (2, "Meenu")]
students.sort(key=lambda x: x[0])
print(students)

⭐ 15. Modules & Functions

If a function is in another file:

math_functions.py

def square(x):
    return x*x

Use it in another file:

from math_functions import square
print(square(5))

🎯 Practice Questions

✔️ Easy

  1. Write a function to find the largest of two numbers.
  2. Write a function to check prime number.
  3. Write a function to reverse a string.

✔️ Medium

  1. Write a recursive function to find Fibonacci series.
  2. Write a function to count vowels in a string.
  3. Write a function that returns both min & max of a list.

✔️ Hard

  1. Write a higher-order function that accepts a function and list.
  2. Write a function to implement your own map() function.
  3. Write a function that takes other functions as arguments and applies all one by one.

If you want, I can also provide: 📌 Diagrams for all concepts
📌 50+ Python function practice questions
📌 Notes in PDF
📌 Interview questions on functions

Just tell me!


Post a Comment

0 Comments