This guide introduces functions in Python — a key concept for writing clean, reusable, and modular code.
A function is a block of reusable code that performs a specific task.
Instead of repeating code, you define it once and call it whenever needed.
- Organize code better
- Avoid repetition (DRY principle)
- Improve readability and debugging
- Enable reuse and testing
def function_name():
# code blockdef greet():
print("Hello, world!")To call the function:
greet()def greet(name):
print("Hello,", name)
greet("Prashant")
greet("Prabesh")You can pass multiple parameters:
def add(a, b):
return a + b
result = add(5, 3)
print(result) # Output: 8Functions can return data using the return keyword.
def square(x):
return x * x
print(square(4)) # Output: 16You can provide default values for parameters:
def greet(name="Guest"):
print("Hello,", name)
greet() # Output: Hello, Guest
greet("Prashant") # Output: Hello, PrashantCall functions using named arguments:
def intro(name, age):
print(f"{name} is {age} years old.")
intro(age=25, name="Prabesh")Use *args and **kwargs for flexible inputs.
def total(*numbers):
return sum(numbers)
print(total(1, 2, 3, 4)) # Output: 10def display_info(**info):
for key, value in info.items():
print(key, ":", value)
display_info(name="Prashant", age=30)Variables defined inside a function are local:
def demo():
x = 10 # local variable / block scoped
print(x)
demo()
# print(x) # Error: x is not defined outsideUse global if you must access a global variable:
count = 0
def increment():
global count
count += 1A function calling itself:
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5)) # Output: 120Use with care — make sure there's a base case to stop.
Short, one-line functions:
square = lambda x: x * x
print(square(5)) # Output: 25def maximum(a, b, c):
return max(a, b, c)def reverse_string(s):
return s[::-1]def is_even(n):
return n % 2 == 0---Created with love by Prashant