Python Define Function: Syntax and Examples

When you're just starting out with Python, you'll quickly notice that writing the same code again and again becomes tedious. That’s where functions come into play. They allow you to write a block of code once and reuse it whenever needed. It’s like packing your daily routine into a neat, reusable box that you can open whenever required.

Python Define Function

In this blog, we’ll break down what functions are, how to define them, the syntax involved, and how they make your code efficient and organized. You’ll also get practical examples and tips that’ll help you become more confident in writing clean Python code.

If you're new to Python or looking to build a solid foundation in programming, check out Uncodemy’s Python Course designed to make learning interactive and career-focused.

What is a Function in Python?

A function in Python is a block of organized, reusable code used to perform a specific task. Functions help reduce code repetition, improve readability, and make debugging easier.

There are two types of functions in Python:

  • Built-in Functions: Like print(), len(), etc.
  • User-defined Functions: These are the ones you create using the def keyword.

Why Use Functions?

Let’s say you’re working on a calculator app. You’ll often need to add, subtract, multiply, or divide numbers. Instead of writing the logic for each operation multiple times, you can write a function for each and call them as needed.

Benefits:

  • Avoid code repetition
  • Simplify complex problems
  • Make code modular and easier to manage
  • Enhance readability and maintenance

Syntax of Defining a Function

The basic syntax of defining a function in Python is:

Copy Code

def function_name(parameters):

   """docstring (optional)"""

    # code block

    return value

Let’s break it down:

  • def: This keyword is used to define a function.
  • function_name: This is the name you give to the function.
  • parameters: These are values you pass into the function (optional).
  • return: Sends the result back to the caller (optional).
  • """docstring""": Describes what the function does (optional, but recommended).

Example 1: A Simple Function Without Parameters

Copy Code

def greet():

    print("Hello, welcome to Python learning!")

greet()

Output:

Hello, welcome to Python learning!

Example 2: Function With Parameters

Copy Code

def add(a, b):

    return a + b

result = add(5, 3)

print("The sum is:", result)

Output:

The sum is: 8

Example 3: Function With Default Parameter

Copy Code

def greet(name="Guest"):

   print(f"Hello, {name}!")

greet()

greet("Muskan")

Output:

Hello, Guest!

Hello, Muskan!

Example 4: Return Statement

Copy Code

The return statement is used when you want your function to give back a result.

def square(num):

    return num ** 2

print(square(4))

Output:

16

Docstrings: Describing the Function

It’s always a good practice to write a docstring right after the function definition to explain what it does.

Copy Code

def multiply(a, b):

   """Returns the product of two numbers."""

    return a * b

You can then use the help() function to view it:

help(multiply)

Keyword Arguments vs Positional Arguments

Positional Arguments

These are arguments passed to functions in the correct position.

Copy Code

def full_name(first, last):

   print(f"{first} {last}")

full_name("Muskan", "Singh")

Keyword Arguments

These are explicitly named when calling the function.

Copy Code

full_name(last="Singh", first="Muskan")

Variable-Length Arguments

Sometimes you don’t know in advance how many arguments will be passed.

*args (Non-keyword variable length)

Copy Code

def total_sum(*numbers):

    return sum(numbers)

print(total_sum(1, 2, 3, 4))

**kwargs (Keyword variable length)

Copy Code

def display_info(**info):

    for key, value in info.items():

       print(f"{key}: {value}")

display_info(name="Muskan", age=20)

Scope of Variables

Variables defined inside a function are local to that function.

Copy Code

def show_name():

    name = "Python"

    print(name)

show_name()

# print(name)  # This will throw an error

Lambda Functions (Anonymous Functions)

Lambda functions are small, one-line functions without a name.

square = lambda x: x ** 2

print(square(5))

Output:

25

Recursion in Functions

A function that calls itself is called a recursive function.

Copy Code

def factorial(n):

    if n == 1:

        return 1

    else:

        return n * factorial(n - 1)

print(factorial(5))

Output:

120

Best Practices While Defining Functions

  • Keep function names descriptive and lowercase.
  • Don’t make functions do too many things keep them focused.
  • Add docstrings for clarity.
  • Return values instead of printing inside the function if possible.
  • Avoid using global variables inside functions unless necessary.

Real-Life Use Case Example: Billing System

Copy Code

def calculate_total(bill_amount, tax_rate=0.18):

   """Calculate final bill including tax"""

    return bill_amount + (bill_amount * tax_rate)

print("Total bill is:", calculate_total(1000))

Common Errors to Avoid

  • Forgetting to call the function: Defining it is not enough you need to call it.
  • Wrong indentation: Python relies heavily on indentation.
  • Incorrect number of arguments: Make sure you pass exactly what the function expects.

Conclusion

Understanding how to define functions in Python is fundamental to writing efficient and readable code. As you begin creating larger projects, you’ll notice how functions act as the building blocks of your applications. From calculators to web apps, everything relies on well-structured function logic.

If you're eager to take your Python skills to the next level, don’t miss the Python Programming Course by Uncodemy. With real-world projects, expert guidance, and practical learning you're on your way to becoming job-ready in no time.

Placed Students

Our Clients

Partners

...

Uncodemy Learning Platform

Uncodemy Free Premium Features

Popular Courses