


Khusboo Tayal
In Python, functions are a fundamental building block that allows you to organize your code into reusable blocks. They help break programs into smaller, manageable pieces and improve readability, modularity, and reusability.
A function is a block of code that runs only when it is called. It can accept parameters, perform a task, and return a result.
You define a function using the def keyword:
def greet():
print("Hello, World!")
To call the function:
greet()
Output:
Hello, World!
You can pass information into functions using parameters:
def greet(name):
print("Hello, " + name)
greet("Alice")
greet("Bob")Output:
Hello, Alice Hello, Bob
A function can return a value using the return keyword:
def add(x, y):
return x + y
result = add(5, 3)
print(result)Output:
8
You can assign default values to parameters:
def greet(name="Guest"):
print("Hello, " + name)
greet()
greet("Khusboo")Output:
Hello, Guest Hello, Khusboo
You can specify parameter names when calling the function:
def student(name, age):
print("Name:", name)
print("Age:", age)
student(age=22, name="Sara")Use *args to accept a variable number of arguments (as a tuple):
def total(*numbers):
sum = 0
for num in numbers:
sum += num
print("Total:", sum)
total(1, 2, 3, 4)Use **kwargs to accept a variable number of keyword arguments (as a dictionary):
def info(**data):
for key, value in data.items():
print(key + ":", str(value))
info(name="John", age=30, country="USA")
Variables defined inside a function are local to that function:
def example():
x = 10
print(x)
example()
# print(x) # Error: x is not definedA function can call itself (recursive function):
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5))Functions are a powerful tool in Python that help in writing clean, efficient, and maintainable code. As you progress, mastering function types, scopes, and patterns like recursion and decorators will significantly enhance your programming skills.
Q1: Can a function return multiple values?
Yes, Python functions can return multiple values as a tuple:
def data():
return "Alice", 25Q2: Are functions objects in Python?
Yes, functions are first-class objects. They can be assigned to variables, passed as arguments, and returned from other functions.
Q3: What is a docstring in a function?
A docstring is a string used to document a function. It’s placed as the first statement in a function:
def greet():
"""This function prints a greeting message."""
print("Hello!")Subscribe to our newsletter to get the latest Python tutorials, project ideas, and updates right to your inbox.
#python #pythonfunctions #functiontutorial #learnpython #pythontips #pythontutorial #pythonbeginners #def #args #kwargs