What is a Function?
A function is a reusable block of code that performs a specific task. Instead of writing the same code multiple times, you can write it once inside a function and call it whenever needed.
Example
def greet():
print("Hello, Welcome to Python!")
greet()
Output
Hello, Welcome to Python!
In this example:
-
defis the keyword used to define a function. -
greetis the function name. - Parentheses
()hold parameters if needed. - The indented block contains the function body.
-
greet()calls the function.
Why Use Functions?
Functions provide several advantages:
- Reduce code duplication.
- Improve code readability.
- Make programs easier to maintain.
- Allow code reuse.
- Simplify debugging and testing.
Syntax of a Function
def function_name(parameters):
# Function body
return value
Function Without Parameters
A function can work without taking any input.
def say_hello():
print("Hello World!")
say_hello()
Output
Hello World!
Function With Parameters
Parameters allow you to pass information into a function.
def greet(name):
print("Hello", name)
greet("Adhi")
Output
Hello Adhi
Function With Multiple Parameters
def add(a, b):
print(a + b)
add(10, 20)
Output
30
Returning Values
The return statement sends a value back to the caller.
def square(number):
return number * number
result = square(5)
print(result)
Output
25
Difference Between print() and return
Using print()
def add(a, b):
print(a + b)
add(5, 3)
Output
8
The value is displayed but cannot be reused.
Using return
def add(a, b):
return a + b
result = add(5, 3)
print(result * 2)
Output
16
The returned value can be stored and used later.
Default Parameters
You can assign default values to parameters.
def greet(name="Guest"):
print("Hello", name)
greet()
greet("Adhi")
Output
Hello Guest
Hello Adhi
Keyword Arguments
You can pass arguments using parameter names.
def student(name, age):
print(name, age)
student(age=21, name="Adhi")
Output
Adhi 21
Arbitrary Arguments (*args)
Use *args when you don't know how many arguments will be passed.
def numbers(*values):
print(values)
numbers(10, 20, 30, 40)
Output
(10, 20, 30, 40)
Arbitrary Keyword Arguments (**kwargs)
Use **kwargs to accept multiple keyword arguments.
def student(**details):
print(details)
student(name="Adhi", age=21, city="Chennai")
Output
{'name': 'Adhi', 'age': 21, 'city': 'Chennai'}
Local Variables
Variables declared inside a function exist only within that function.
def demo():
message = "Python"
print(message)
demo()
Global Variables
Variables declared outside a function can be accessed inside it.
language = "Python"
def display():
print(language)
display()
Output
Python
Lambda Functions
A lambda function is a small anonymous function written in a single line.
square = lambda x: x * x
print(square(6))
Output
36
Recursive Functions
A recursive function calls itself.
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5))
Output
120
Built-in Functions
Python provides many built-in functions.
Examples include:
print(len("Python"))
print(max(5, 10, 15))
print(min(5, 10, 15))
print(sum([1, 2, 3, 4]))
Output
6
15
5
10
Best Practices
- Use meaningful function names.
- Keep functions short and focused.
- Avoid repeating code.
- Use comments when necessary.
- Return values instead of printing when possible.
Common Mistakes
Forgetting Parentheses
greet
Correct:
greet()
Missing Return Statement
def add(a, b):
a + b
Correct:
def add(a, b):
return a + b
Incorrect Indentation
def hello():
print("Hello")
Correct:
def hello():
print("Hello")
Real-World Example
def calculate_total(price, quantity):
return price * quantity
product_price = 250
quantity = 4
total = calculate_total(product_price, quantity)
print("Total Amount:", total)
Output
Total Amount: 1000
Summary
Functions are one of Python's most powerful features. They make programs modular, reusable, and easier to maintain. Whether you're writing a small script or a large application, using functions effectively will improve the quality of your code.
Key Takeaways
- Functions are reusable blocks of code.
- Use
defto define a function. - Parameters allow functions to accept input.
-
returnsends values back to the caller. - Python supports default arguments, keyword arguments,
*args, and**kwargs. - Lambda functions are useful for short operations.
- Recursive functions solve problems by calling themselves.
- Good functions are simple, reusable, and easy to understand.
Top comments (0)