Python Functions


In Python, functions are reusable blocks of code designed to perform a specific task. Functions help organize code, reduce repetition, and improve readability, making your programs easier to understand and maintain. Learning to use functions effectively is essential for structured programming and is the foundation for more advanced Python concepts.

This tutorial covers defining functions, calling them, using parameters, return values, scope, default and keyword arguments, recursion, and practical examples.

What is a Function?

A function is a named block of code that executes a specific task. Functions allow programmers to:

  • Break a program into smaller, manageable pieces

  • Reuse code without rewriting it

  • Make programs easier to test and maintain

Python supports two main types of functions:

  1. Built-in functions – Predefined functions such as print(), len(), and type()

  2. User-defined functions – Functions created by the programmer for specific tasks

Defining a Function

Functions in Python are defined using the def keyword:

def greet():
    print("Hello! Welcome to Python functions.")

Here:

  • def – keyword to define a function

  • greet – the function name

  • () – parentheses where parameters (if any) are defined

  • : – denotes the start of the function body

Calling a Function

Once defined, a function is executed by calling its name followed by parentheses:

greet()

Output:

Hello! Welcome to Python functions.

Function Parameters

Functions can accept inputs, called parameters or arguments. Parameters allow a function to operate on dynamic values:

def greet_user(name):
    print(f"Hello, {name}! Welcome to Python.")

Calling the function:

greet_user("Ananya")  # Output: Hello, Ananya! Welcome to Python.

Return Statement

Functions can return a value using the return keyword. This allows the function to produce output that can be used elsewhere:

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

result = add(10, 5)
print(result)  # Output: 15

Without a return statement, a function performs an action but does not produce a value.

Types of Function Arguments

Python supports several ways to pass arguments to functions:

1. Positional Arguments

Arguments are assigned based on their order:

def divide(a, b):
    return a / b

print(divide(10, 2))  # Output: 5.0

2. Keyword Arguments

Arguments are assigned using parameter names, allowing any order:

print(divide(b=2, a=10))  # Output: 5.0

3. Default Arguments

You can assign default values to parameters:

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

greet()           # Output: Hello, Guest!
greet("Ananya")   # Output: Hello, Ananya!

4. Arbitrary Arguments (*args)

Allow functions to accept any number of positional arguments:

def total(*numbers):
    return sum(numbers)

print(total(10, 20, 30))  # Output: 60

5. Arbitrary Keyword Arguments (**kwargs)

Allow functions to accept any number of keyword arguments:

def display_info(**info):
    for key, value in info.items():
        print(f"{key}: {value}")

display_info(name="Ananya", age=22, course="Python")

Variable Scope

Variables in Python have a scope, determining where they can be accessed:

  • Local variables – Defined inside a function, accessible only within it

  • Global variables – Defined outside any function, accessible anywhere

global_var = 10

def example():
    local_var = 5
    print(global_var)  # Accessible
    print(local_var)   # Accessible

example()
print(global_var)      # Accessible
# print(local_var)     # Error: local_var is not accessible outside function

Nested Functions

Functions can be defined inside other functions for encapsulation:

def outer():
    def inner():
        print("Inner function")
    inner()
    print("Outer function")

outer()

Nested functions are useful for organizing related functionality and can also be used in closures.

Recursive Functions

A function can call itself; this is called recursion:

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

print(factorial(5))  # Output: 120

Recursion is often used for mathematical computations and algorithm design.

Practical Examples

  1. Greeting a user:

def greet_user(name):
    print(f"Hello, {name}!")
greet_user("Ananya")
  1. Calculate sum of two numbers:

def add(a, b):
    return a + b
print(add(10, 15))
  1. Check even or odd:

def even_odd(num):
    return "Even" if num % 2 == 0 else "Odd"
print(even_odd(7))
  1. Sum of arbitrary numbers:

def total(*numbers):
    return sum(numbers)
print(total(5, 10, 15))
  1. Display student information:

def student_info(**info):
    for key, value in info.items():
        print(f"{key}: {value}")
student_info(name="Ananya", age=22, course="Python")
  1. Convert Celsius to Fahrenheit:

def c_to_f(c):
    return (c * 9/5) + 32
print(c_to_f(25))
  1. Reverse a string:

def reverse_string(s):
    return s[::-1]
print(reverse_string("Python"))
  1. Check prime number:

def is_prime(n):
    if n <= 1:
        return False
    for i in range(2, int(n ** 0.5)+1):
        if n % i == 0:
            return False
    return True
print(is_prime(17))
  1. Nested function example:

def outer():
    def inner():
        return "Hello from inner"
    return inner()
print(outer())
  1. Recursive factorial:

def factorial(n):
    if n == 0:
        return 1
    return n * factorial(n-1)
print(factorial(5))

Summary of the Tutorial

Functions in Python are essential building blocks for writing organized and reusable code. They allow you to:

  • Reduce code repetition

  • Improve readability and maintainability

  • Break programs into modular components

  • Handle dynamic inputs through parameters

  • Produce outputs that can be used in other parts of the program

Understanding user-defined functions, argument types, return values, scope, nested functions, and recursion is crucial for every Python programmer. Mastering functions is the foundation for advanced topics like object-oriented programming, functional programming, and modular software design.


Practice Questions

Q1. Write a Python program to create a function that prints "Welcome to Python".

Q2. Write a Python program to create a function that takes a name as input and prints a greeting like "Hello, CodePractice!".

Q3. Write a Python program to use a default parameter in a function, such as greet(name="Guest").

Q4. Write a Python program to create a function that returns the square of a number.

Q5. Write a Python program to call a function using keyword arguments (e.g., info(name="Sanju", age=27)).

Q6. Write a Python program to use *args to accept multiple values and print their total.

Q7. Write a Python program to use **kwargs to pass and print key-value pairs inside a function.

Q8. Write a Python program to create a function that returns the sum of two numbers.

Q9. Write a Python program to create a function to multiply 3 numbers using default arguments (e.g., multiply(a, b=1, c=1)).

Q10. Write a Python program to write a recursive function to calculate the factorial of a number.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top