Coding Now – Best AI & Full Stack Courses in Delhi NCR | 100% Placement
Limited Offer: Get 50% OFF on AI & Full Stack Courses
📞 Call Now: +91 9667708830
Back to Python Notes
Topic #6

Functions in Python

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 def and called by name followed by parentheses
  • Parameters can have default values, and arguments can be passed positionally or by keyword
  • *args and **kwargs let a function accept a flexible number of arguments
  • Lambda functions are compact, single-line functions often used with map(), filter(), and sorted()

Want to go beyond the notes?

Join CodingNow's Python course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available
💬 Talk to Advisor
1
WhatsApp

Latest from Our Blog

Insights on AI, Data Science, Full Stack & Career

View All Articles →