๐น 1. What is a Function?
A function is a block of reusable code that performs a specific task.
๐ Instead of writing the same code again and again, we define it once and reuse it.
๐น 2. Why Use Functions?
โ Avoid repetition
โ Make code reusable
โ Improve readability
โ Easy debugging
๐น 3. Defining a Function
Syntax
def function_name():
# code block
Example 1: Simple Function
def greet():
print("Hello, welcome to Python")
๐น Calling the function:
greet()
Output
Hello, welcome to Python
๐ Explanation
defkeyword defines a functiongreetis the function name- Function runs only when called
๐น 4. Function with Parameters
Parameters allow us to pass data into a function.
Example 2: Greeting with Name
def greet(name):
print("Hello", name)
๐น Calling the function:
greet("Sameer")
greet("Ayesha")
Output
Hello Sameer
Hello Ayesha
๐ Explanation
nameis a parameter- Values passed are called arguments
๐น 5. Function with Multiple Parameters
Example 3: Student Details
def student_info(name, age):
print("Name:", name)
print("Age:", age)
๐น Function call:
student_info("Saddam", 24)
Output
Name: Saddam
Age: 24
๐น 6. Function with Return Value
Functions can return a value using return.
Example 4: Add Two Numbers
def add(a, b):
return a + b
๐น Function call:
result = add(10, 5)
print(result)
Output
15
๐ Explanation
returnsends value back to caller- Code after
returndoes not execute
๐น 7. Return vs Print
Example 5
def show_sum(a, b):
print(a + b)
def get_sum(a, b):
return a + b
show_sum(5, 5)
print(get_sum(5, 5))
Output
10
10
๐ Explanation
print()โ displays valuereturnโ gives value for further use
๐น 8. Function with User Input
Example 6
def square_number():
num = int(input("Enter a number: "))
print("Square:", num * num)
๐น Function call:
square_number()
Sample Output
Enter a number: 4
Square: 16
๐น 9. Default Parameter Value
Example 7
def greet(name="Guest"):
print("Hello", name)
greet()
greet("Chandini")
Output
Hello Guest
Hello Chandini
๐ Explanation
- Default value is used if argument not provided
๐น 10. Keyword Arguments
Example 8
def employee(name, salary):
print("Name:", name)
print("Salary:", salary)
employee(salary=30000, name="Gousya")
Output
Name: Gousya
Salary: 30000
๐น 11. Function Calling Another Function
Example 9
def add(a, b):
return a + b
def calculate():
result = add(3, 4)
print("Result:", result)
calculate()
Output
Result: 7
๐น 12. Real-Life Example: Salary Calculator
Example 10
def total_salary(basic, bonus):
return basic + bonus
salary = total_salary(25000, 5000)
print("Total Salary:", salary)
Output
Total Salary: 30000
๐น 13. Common Mistakes (IMPORTANT)
โ Forgetting to call function
โ Wrong indentation
โ Missing return value
โ Confusing print with return
๐ง Final Summary
โ def is used to define a function
โ Functions must be called to execute
โ Parameters receive values
โ return sends data back
โ Functions make code reusable

Leave a Reply