In Python (programming language), a function is a block of reusable code that performs a specific task.
Functions help to:
- Avoid repeating code
- Make programs organized
- Improve readability
- Make debugging easier
πΉ Defining a Function
In Python, functions are defined using the def keyword.
Syntax
def function_name():
# code block
πΉ Example: Simple Function
def greet():
print("Hello, Welcome to Python!")greet()
Output:
Hello, Welcome to Python!
Here:
greet()is the function name- The function runs when it is called
πΉ Function with Parameters
Functions can accept inputs called parameters.
def greet(name):
print("Hello,", name)
greet("Rahul")
Output:
Hello, Rahul
πΉ Function with Return Value
Functions can return a value using the return keyword.
def add(a, b):
return a + b
result = add(5, 3)
print(result)
Output:
8
πΉ Default Parameters
You can give default values to parameters.
def greet(name="Guest"):
print("Hello,", name)greet()
greet("Alice")
Output:
Hello, Guest
Hello, Alice
πΉ Multiple Return Values
Python allows returning multiple values.
def calculate(a, b):
return a + b, a - b
sum_result, diff_result = calculate(10, 5)
print(sum_result, diff_result)
Output:
15 5
πΉ Lambda (Anonymous) Functions
A lambda function is a small, single-line function.
square = lambda x: x * x
print(square(5))
Output:
25
πΉ Scope of Variables
Variables inside a function are called local variables.
Variables outside are called global variables.
x = 10 # globaldef show():
y = 5 # local
print(x, y)show()
β Key Points
- Functions are defined using
def. - They can take parameters.
- They can return values.
- Lambda functions are short, single-expression functions.
- Functions improve code organization and reuse.