Day 6: Python Functions – Reusable Blocks of Code
Introduction
In Python, a function is a block of code that performs a specific task and can be reused anytime in your program.
Functions help make your code modular, organized, and easy to debug.
Python provides two types of functions:
-
Built-in functions – e.g.,
len()
,print()
,type()
,max()
-
User-defined functions – created using the
def
keyword
1. Defining a Function
A function is defined using the def
keyword followed by a name and parentheses.
Example:
def display():
print("Hello, welcome to Python learning! Habbit2Code Online Coding Classes")
To call this function:
display()
Output:
Hello, welcome to Python learning! Habbit2Code Online Coding Classes
2. Function with Parameters/Arguments
Functions can take parameters (also called arguments) to pass data.
Example:
def add(a, b):
result = a + b
print("Sum =", result)
add(20, 5)
Output:
Sum = 25
3. Function with Return Value
Sometimes you may want the function to return a value.
Example:
def square(n):
return n * n
result = square(6)
print("Square =", result)
Output:
Square = 36
4. Default Arguments
You can give default values to parameters.
Example:
def greet(name="Guest"):
print("Hello", name)
greet("habbit2code@gmail.com")
greet()
Output:
Hello habbit2code@gmail.com
Hello Guest
5. Keyword and Positional Arguments
You can pass arguments by position or by name.
Example:
def student(name, age):
print(name, "is", age, "years old")
student("Ravi", 20) # positional
student(age=18, name="Manu") # keyword
6. Recursion (Function Calling Itself)
A function can call itself. This is called recursion.
Example:
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
print("Factorial =", factorial(5))
Output:
Factorial = 120
7. Practical Example
Let’s create a function to check whether a number is even or odd.
def check_number(num):
if num % 2 == 0:
print(num, "is Even")
else:
print(num, "is Odd")
check_number(7)
Output:
7 is Odd
8. Why Use Functions?
> Code reusability
> Easy debugging and maintenance
> Clear program structure
> Avoid repetition
Challenge for You
Create a Python program with a function that takes a list of numbers and returns only the even numbers.
Final Thoughts
Functions are like mini programs inside your main program.
They save time, make your code clean, and help you think logically.
In the next lesson, we’ll learn about lambda functions and modules to take this concept further.
Comments
Post a Comment