What Is a Function?
A function is a reusable block of code that performs a specific task. Instead of repeating the same code, you write it once inside a function and call it whenever you need it.
Defining a Function
Functions are defined using the def keyword:
def greet():
print("Hello, welcome to CodingNow!")
greet() # calling the function
Parameters and Arguments
Functions can accept input values called parameters:
def greet(name):
print("Hello,", name)
greet("Aman") # Hello, Aman
Default Parameter Values
def greet(name="Student"):
print("Hello,", name)
greet() # Hello, Student
greet("Riya") # Hello, Riya
Multiple Parameters and Keyword Arguments
def add(a, b):
return a + b
print(add(5, 3)) # positional arguments → 8
print(add(b=10, a=2)) # keyword arguments → 12
The return Statement
Use return to send a value back to wherever the function was called:
def square(num):
return num * num
result = square(4)
print(result) # 16
A function without a return statement automatically returns None.
*args and **kwargs
Sometimes you don't know how many arguments a function will receive. Python handles that with *args (variable positional arguments) and **kwargs (variable keyword arguments).
def total(*args):
return sum(args)
print(total(1, 2, 3, 4)) # 10
def show_info(**kwargs):
for key, value in kwargs.items():
print(key, ":", value)
show_info(name="Aman", course="Python")
Lambda Functions
A lambda is a small, unnamed, single-expression function — useful for short, throwaway operations:
square = lambda x: x * x
print(square(5)) # 25
nums = [5, 2, 8, 1]
print(sorted(nums, key=lambda x: -x)) # [8, 5, 2, 1]
Variable Scope
A variable defined inside a function is local — it only exists inside that function. A variable defined outside all functions is global.
x = 10 # global variable
def show():
x = 5 # local variable, different from global x
print("Inside function:", x)
show() # Inside function: 5
print("Outside:", x) # Outside: 10
Key Takeaways
- Functions are defined with
defand called by name followed by parentheses - Parameters can have default values, and arguments can be passed positionally or by keyword
*argsand**kwargslet a function accept a flexible number of arguments- Lambda functions are compact, single-line functions often used with
map(),filter(), andsorted()