A function in Python is a reusable block of code that performs a specific task. Functions help organize code and avoid writing the same code again and again.
Python provides many built-in functions, such as print(), len(), and type(). You can also create your own functions according to your needs.
What is a Function?
A function is a block of code that runs when it is called. It can take input, perform an operation, and return a result.
For example:
def greet():
print("Hello, Python!")
greet()Output:
Hello, Python!Here, greet() is a user-defined function that prints a message.
Creating a Function
In Python, you create a function using the def keyword, followed by the function name and parentheses.
def greet():
print("Welcome to Python")The code inside the function must be indented.
A function does not run just because it has been defined. You need to call the function to execute its code.
Calling a Function
To call a function, write its name followed by parentheses.
def greet():
print("Hello!")
greet()Output:
Hello!You can call the same function multiple times:
def greet():
print("Hello!")
greet()
greet()
greet()Output:
Hello!
Hello!
Hello!Function Syntax
The basic syntax of a Python function is:
def function_name(parameters):
# function bodyFor example:
def add(a, b):
result = a + b
print(result)In this example:
- def defines the function.
- add is the function name.
- a and b are parameters.
- The indented code is the function body.
Function with Parameters
Parameters allow you to pass data to a function. They make a function more flexible because the same function can work with different values.
def greet(name):
print("Hello", name)
greet("Rahul")
greet("Amit")Output:
Hello Rahul
Hello AmitA function can have multiple parameters:
def add(a, b):
print(a + b)
add(10, 20)Output:
30Here, a and b are parameters, while 10 and 20 are the values passed to the function when it is called.
Function Without Parameters
A function does not always need parameters. A function without parameters performs its task using values already defined inside the function or through other available data.
def welcome():
print("Welcome to Python Programming")
welcome()Output:
Welcome to Python ProgrammingAnother example:
def show_message():
message = "Learning Python is easy"
print(message)
show_message()A function without parameters is useful when the function performs a fixed task and does not need input from the caller.