What is a Function?
- A function is a block of reusable code that performs a specific task.
Why Use Function?
Reuse code multiple times
Improve code readability
Reduce code duplication
Make programs easier to maintain
Syntax:
def function_name():
<statement>
Example:
def greet():
print("Hello, Python!")
greet()
Output:
Hello, Python!
Three types of Functions:
Function without Parameters
Function with Parameters
Function with return values
Function without Parameters:
A function that does not accept any input values is called a function without parameters.
Example:
def greet():
print("Hello, Python!")
greet()
Output:
Hello, Python!
Function with Parameters:
A function that accepts input values is called a function with parameters.
Syntax:
def function_name(parameter):
<statement>
Example:
def greet(name):
print("Hello", name)
greet("World")
Output:
Hello World
Function with Return Value:
A function that returns a values using the return statement.
Example:
def add(a, b):
return a + b
result = add(10,20)
print(result)
Output:
30
Top comments (0)