Functions in Python

    Kedar Kabra3 min readUpdated

    A function is a reusable block of code with a name. You define it once and call it whenever you need it. Here's the simplest possible function and how to use it:

    # Define a function with 'def'
    def greet(name):
        return f"Hello, {name}!"
    
    # Call it by writing its name with arguments
    message = greet("Asha")
    print(message)        # Hello, Asha!
    

    Functions keep your code organised and save you from repeating yourself. Let's break them down.

    Defining a function

    Use the def keyword, a name, parentheses for parameters, and a colon. The body is indented:

    def say_hello():
        # This runs every time you call say_hello()
        print("Welcome to Python!")
    
    say_hello()    # call it
    say_hello()    # call it again — no need to rewrite the code
    

    Parameters and arguments

    Parameters are the names inside the parentheses when you define the function. Arguments are the actual values you pass when you call it:

    # 'a' and 'b' are parameters
    def add(a, b):
        return a + b
    
    # 4 and 7 are arguments
    result = add(4, 7)
    print(result)        # 11
    

    Returning values

    The return keyword sends a value back to wherever the function was called. A function without return gives back None by default:

    def square(n):
        return n * n      # send the result back
    
    print(square(5))      # 25
    
    def show(msg):
        print(msg)        # no return -> gives back None
    
    value = show("hi")
    print(value)          # None
    

    Once a return runs, the function stops immediately — any code after it is skipped.

    Want to learn this properly?

    Join the waitlist for our courses — beginner-friendly, project-first classes in Jalgaon.

    Browse courses

    Default arguments

    You can give a parameter a default value, used when the caller doesn't supply one:

    def greet(name, greeting="Hello"):
        return f"{greeting}, {name}!"
    
    print(greet("Ravi"))               # Hello, Ravi!
    print(greet("Ravi", "Welcome"))    # Welcome, Ravi!
    

    Default arguments must come after non-default ones in the definition.

    Keyword arguments

    You can pass arguments by name, which makes calls clearer and lets you reorder them:

    def book_ticket(name, seats, city):
        print(f"{seats} seat(s) booked for {name} to {city}")
    
    # Pass by name in any order
    book_ticket(seats=2, city="Pune", name="Meena")
    

    A complete example

    # Calculate the final price after a discount
    
    def final_price(price, discount_percent=0):
        """Return price after applying a percentage discount."""
        discount = price * discount_percent / 100
        return price - discount
    
    # Without a discount
    print(final_price(1000))            # 1000.0
    
    # With a 15% discount
    print(final_price(1000, 15))        # 850.0
    

    That triple-quoted line is a docstring — a short description of what the function does. It's good practice to add one.

    Common mistakes

    • Forgetting to call the function: Writing greet instead of greet("Asha") doesn't run it — it just refers to the function object.
    • Confusing print and return: print() shows something on screen; return sends a value back so other code can use it. If you print instead of return, you can't reuse the result.
    • Putting default arguments before required ones: def f(a=1, b) is a SyntaxError. Defaults go last.
    • Using a mutable default like []: def f(items=[]) reuses the same list across calls, causing surprising bugs. Use def f(items=None) and create the list inside the function.
    • Indentation errors in the body: Every line inside the function must be indented under the def line.

    FAQ

    Can a function return more than one value? Yes — return them separated by commas, and Python packs them into a tuple: return a, b. You can unpack with x, y = my_func().

    What is a parameter's scope? Variables created inside a function are local — they only exist while the function runs and can't be seen from outside.

    How many arguments can a function take? As many as you like. You can even accept a variable number with *args and **kwargs, which you'll meet as you progress.


    Once you're comfortable with functions, explore the shorter Lambda Functions in Python and the powerful idea of Recursion in Python. See all topics on the Python learning hub.

    Want to learn this properly? Join the waitlist for our Python course — taught in Jalgaon, beginner-friendly.

    Want to learn this properly?

    Join the waitlist for our courses — beginner-friendly, project-first classes in Jalgaon.

    Browse courses
    Kedar Kabra

    Instructor, Infoplanet

    Kedar Kabra teaches Python at Infoplanet, helping beginners become confident programmers through hands-on, project-first practice.

    Related guides