A Function is a block of code that performs a specific task. Functions help make code reusable, organized, and easier to maintain.
Creating a Function
Use the def keyword to create a function.
Syntax
def function_name():
# code
Example
def greet():
print("Welcome to Python")
greet()
Output:
Welcome to Python
Function with Parameters
Parameters allow you to pass data into a function.
Syntax
def function_name(parameter):
# code
Example
def greet(name):
print("Hello", name)
greet("John")
Output:
Hello John
Function with Multiple Parameters
Example
def add(a, b):
print(a + b)
add(10, 20)
Output:
30
Return Statement
The return statement sends a value back from a function.
Syntax
def function_name():
return value
Example
def add(a, b):
return a + b
result = add(10, 20)
print(result)
Output:
30
Default Parameter Value
You can provide a default value for a parameter.
Example
def greet(name="Guest"):
print("Hello", name)
greet()
greet("John")
Output:
Hello Guest
Hello John
Function Returning Multiple Values
Example
def calculate(a, b):
return a + b, a - b
sum_result, sub_result = calculate(20, 10)
print(sum_result)
print(sub_result)
Output:
30
10
Calling a Function Multiple Times
Example
def welcome():
print("Welcome")
welcome()
welcome()
welcome()
Output:
Welcome
Welcome
Welcome
Benefits of Functions
- Avoid code repetition.
- Improve code readability.
- Make programs easier to maintain.
- Allow code reuse throughout the application.
Summary
- Functions are created using the
defkeyword. - Functions can accept parameters.
- Functions can return values using
return. - Default parameter values can be provided.
- Functions can be called multiple times.
- Functions help organize and reuse code.