Functions in Python

Have you ever cooked the same recipe again and again? Wouldn’t it be easier if you had a ready-made recipe card so you don’t have to remember every step each time?

That’s exactly what functions in Python do!
They help you write code once and reuse it anywhere in your program.

functions in python
Functions in Python

What is a Function?

A function is a block of code that performs a specific task.

👉 Instead of writing the same code again and again, you can put it inside a function and call it whenever needed.


How to Create a Function in Python?

We use the def keyword to define a function.

Syntax:

def function_name(parameters):
    # code block
    return result
  • def → keyword to define function
  • function_name → name of your function
  • parameters → input values (optional)
  • return → gives back a result (optional)

Example 1: A simple function

def greet():
    print("Hello, welcome to Python!")
    
greet()  # calling the function

Output:

Hello, welcome to Python!

Example 2: Function with parameters

def greet_user(name):
    print(f"Hello {name}, nice to meet you!")
    
greet_user("Tejas")
greet_user("Riya")

Output:

Hello Tejas, nice to meet you!
Hello Riya, nice to meet you!

Example 3: Function with return value

def add(a, b):
    return a + b

result = add(5, 7)
print("Sum is:", result)

Output:

Sum is: 12

Example 4: Default parameters

def greet_user(name="Guest"):
    print(f"Hello {name}, welcome!")

greet_user("Aman")
greet_user()

Output:

Hello Aman, welcome!
Hello Guest, welcome!

Example 5: Functions with multiple return values

def calculate(a, b):
    return a + b, a - b, a * b

x, y, z = calculate(10, 5)
print("Addition:", x)
print("Subtraction:", y)
print("Multiplication:", z)

Output:

Addition: 15
Subtraction: 5
Multiplication: 50

Also Read: Loops in Python


Lambda Functions in Python (Anonymous Functions)

Sometimes you don’t need a big function with a name.
You just want a small, quick function for one-time use.

For that, Python gives us lambda functions.

Syntax:

lambda arguments: expression
  • lambda → keyword
  • arguments → input values
  • expression → single line of code (result is returned automatically)

Example 1: Square of a number

square = lambda x: x * x
print(square(6))

Output:

36

Example 2: Add two numbers

add = lambda a, b: a + b
print(add(10, 20))

Output:

30

Example 3: With map()

Suppose we want to square every number in a list. Instead of writing a full function, we can use lambda inside map()

numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, numbers))
print(squares)

Output:

[1, 4, 9, 16, 25]

Example 4: With filter()

If we want only even numbers from a list:

numbers = [10, 15, 20, 25, 30]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)

Output:

[10, 20, 30]

Example 5: With sorted()

We can sort a list of tuples by the second value using lambda:

students = [("Riya", 21), ("Aman", 19), ("Tejas", 22)]
sorted_students = sorted(students, key=lambda x: x[1])  # x[0] = 'name', x[1] = 'age'
print(sorted_students)

Output:

[('Aman', 19), ('Riya', 21), ('Tejas', 22)]

Key Takeaways

  • Functions help you organize code and reuse it.
  • Use def when you need a named, reusable function.
  • Use lambda when you need a quick one-line function.
  • Commonly used with map(), filter(), reduce(), and sorted().

Mini Project Challenge

Write a function-based program for a Student Grading System:

  • Ask user to enter marks of 3 subjects
  • Create a function that calculates the average
  • Another function should decide the grade (A, B, C, Fail)
  • Print result

👉 Sample Output:

Enter marks of 3 subjects: 75 80 90
Average Marks = 81.67
Grade = A

Final Thoughts

Functions are the building blocks of Python programming.
They not only save time but also make your programs more professional and clean.

FAQs – Functions in Python

Functions make code cleaner, reusable, and easier to understand. They help you avoid repetition and improve debugging and testing.

  • Built-in functions are already available in Python (like print(), len(), type()).

  • User-defined functions are functions you create using the def keyword.

Yes ✅, Python allows returning multiple values as a tuple. For example:

def calc(a, b):
     return a+b, a-b

Calling calc(5, 3) will return (8, 2).

A lambda function is a short, anonymous function created using the lambda keyword. Example:

square = lambda x: x * x
print(square(5))
# Output: 25

They are often used when you need a simple one-line function.

Yes, this is called function nesting. One function can call another to complete a task.

What’s Next?

In the next post, we’ll learn about the Lists in Python

Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Translate »
Scroll to Top