Python Functions are a fundamental part of programming that help structure code efficiently. This article explains what functions are, the different types, and how to use them in Python. It also explores their benefits and practical applications to give you a thorough understanding of Python functions.
Contents:
- Introduction to Functions in Python
- Types of Functions in Python
- Defining and Calling a Function in Python
- Function Parameters and Arguments in Python
- Positional Parameters in Python
- Default Parameters in Python
- Keyword Parameters in Python
- Arbitrary Arguments (*args) in Python
- Arbitrary Keyword Arguments (**kwargs) in Python
- Lambda Functions in Python
- Recursive Functions in Python
- Built-in Functions vs. User-defined Functions
- Function Annotations
- FAQs on Python Functions
Introduction to Functions in Python
Functions are an essential part of Python programming that allow you to organize and reuse code efficiently. They help break down large programs into smaller, manageable, and reusable blocks.
What is a Function?
A function is a block of code that performs a specific task. It runs only when called and can take inputs, process them, and return results.
Key Features of Python Functions
Here are some key features that make Python functions versatile and useful:
- Code Reusability: Write a function once and use it multiple times, reducing duplication.
- Modularity: Break complex programs into smaller, manageable blocks for better organization.
- Increases Efficiency: Makes code easier to read, maintain, and debug.
- Improved Readability: Helps maintain organized and clean code.
Types of Functions in Python
Here are the different types of functions in Python:
- Built-in Functions – Predefined functions in Python (e.g., print(), len(), type()).
- User-defined Functions – Functions created by the user to perform specific tasks.
- Lambda Functions – Anonymous functions defined using lambda keyword.
Defining and Calling a Function in Python
In Python, functions are defined using the def keyword, followed by the function name, parentheses (which may contain parameters), and a colon. The function body is indented and contains the logic to be executed when the function is called.
Syntax of a Function
def function_name(parameters): """Optional docstring""" # Function body return value # Optional return statement
Example 1: Defining and Calling a Simple Function
# Defining a simple function def greet(): print("Hello! Welcome to Sanfoundry.") # Calling the function greet()
Output:
Hello! Welcome to Sanfoundry.Example 2: Function With Parameters
# Defining a function with a parameter def greet(name): print(f"Hello, {name}! Welcome to Sanfoundry.") # Calling the function with an argument greet("Harsh")
Output:
Hello, Harsh! Welcome to Sanfoundry.
Example 3: Function With Default Parameters
# Defining a function with two parameters def add_numbers(a, b): result = a + b print(f"The sum of {a} and {b} is: {result}") # Calling the function with two arguments add_numbers(5, 3)
Output:
The sum of 5 and 3 is: 8
Example 4: Function with Keyword Arguments
# Defining a function with keyword arguments def display_info(name, age): print(f"Name: {name}") print(f"Age: {age}") # Calling the function using keyword arguments display_info(age=25, name="Sanfoundry")
Output:
Name: Sanfoundry
Age: 25Example 5: Using **kwargs for Arbitrary Keyword Arguments
# Using **kwargs to accept multiple keyword arguments def display_details(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}") # Calling the function with multiple keyword arguments display_details(name="Sanfoundry", course="Python", duration="3 months")
Output:
name: Sanfoundry
course: Python
duration: 3 monthsFunction Parameters and Arguments in Python
In Python, parameters and arguments allow you to pass information to a function so that it can perform tasks based on that data.
Types of Function Parameters in Python
Python supports different types of function parameters:
- Positional Parameters
- Default Parameters
- Keyword Parameters
- Arbitrary Arguments (*args)
- Arbitrary Keyword Arguments (**kwargs)
Positional Parameters in Python
In Python, positional parameters (also called positional arguments) are the most common way to pass values to a function. They are matched based on the position in which the arguments are passed during the function call.
Example: Using Positional Parameters
# Defining a function with two positional parameters def display_info(name, age): print(f"Name: {name}") print(f"Age: {age}") # Calling the function with arguments in the correct order display_info("Sanfoundry", 25)
Output:
Name: Sanfoundry
Age: 25- name and age are positional parameters.
- The values “Sanfoundry” and 25 are passed in the same order as the parameters.
Order Matters in Positional Parameters
If the order of arguments is changed, the function may not behave as expected.
def display_info(name, age): print(f"Name: {name}") print(f"Age: {age}") # Incorrect order of arguments display_info(25, "Sanfoundry")
Output:
Name: 25
Age: SanfoundryDefault Parameters in Python
Default parameters in Python allow you to assign a default value to a function parameter. If an argument is not provided during the function call, the default value is used instead.
Syntax of Default Parameters
def function_name(param1=value1, param2=value2, ...): # Function body
Example 1: Basic Default Parameter
# Defining a function with a default parameter def greet(name="User"): print(f"Hello, {name}!") # Calling with and without argument greet("Arya") greet()
Output:
Hello, Arya! Hello, User!
Example 2: Multiple Default Parameters
def course_details(name, course="Python", duration="3 months"): print(f"{name} is learning {course} for {duration}.") # Calling with different arguments course_details("Vinay", "Java", "6 months") course_details("Pooja")
Output:
Vinay is learning Java for 6 months. Pooja is learning Python for 3 months.
Example 3: Mixing Positional and Default Parameters
def order_summary(item, quantity=1, price=100): print(f"Item: {item}, Quantity: {quantity}, Total: {quantity * price}") # Calling with different arguments order_summary("Laptop", 2, 50000)
Output:
Item: Laptop, Quantity: 2, Total: 100000 Item: Mouse, Quantity: 1, Total: 100
Keyword Parameters in Python
Keyword parameters in Python allow arguments to be passed to a function using parameter names. This makes function calls more readable and helps avoid confusion with argument order.
Syntax:
def function_name(param1, param2, ...): # Function body # Calling the function function_name(param1=value1, param2=value2)
Example 1: Using Keyword Parameters
# Defining a function def display_info(name, age): print(f"Name: {name}") print(f"Age: {age}") # Using keyword arguments display_info(name="Sanfoundry", age=25) display_info(age=30, name="Harry")
Output:
Name: Sanfoundry Age: 25 Name: Harry Age: 30
Example 2: Mixing Positional and Keyword Arguments
Positional arguments must come before keyword arguments.
# Correct usage display_info("John", age=28) # Incorrect usage (keyword before positional) display_info(age=28, "John")
Output:
SyntaxError: positional argument follows keyword argument
Example 3: Default Parameters with Keyword Arguments
def course_details(name, course="Python", duration="3 months"): print(f"{name} is learning {course} for {duration}.") # Using keyword arguments with default parameters course_details(name="Mary", duration="6 months")
Output:
Mary is learning Python for 6 months.
Arbitrary Arguments (*args) in Python
In Python, *args allows a function to accept any number of positional arguments. This is useful when the number of inputs is unknown or variable.
Syntax:
def function_name(param1, *args): # Function body
Example 1: Using *args
# Defining a function with *args def sum_numbers(*args): total = sum(args) print(f"Sum of numbers: {total}") # Calling with multiple arguments sum_numbers(10, 20, 30, 40) sum_numbers(5, 15)
Output:
Sum of numbers: 100 Sum of numbers: 20
Example 2: Passing Mixed Parameters with *args
*args can be combined with other parameters. Positional arguments must come before *args.
# Defining a function with a regular parameter and *args def display_info(name, *courses): print(f"Student Name: {name}") print("Courses Enrolled:", courses) # Calling the function display_info("Ankit", "Python", "Java", "C++")
Output:
Student Name: Ankit Courses Enrolled: ('Python', 'Java', 'C++')
Example 3: Looping Through *args
def print_items(*items): for item in items: print(item) print_items("Python", "Java", "C++", "JavaScript")
Output:
Python Java C++ JavaScript
Arbitrary Keyword Arguments (**kwargs) in Python
In Python, **kwargs allows a function to accept any number of keyword arguments. These arguments are passed as key-value pairs and are stored in a dictionary.
Syntax:
def function_name(param1, **kwargs): # Function body
Example 1: Using **kwargs
# Defining a function with **kwargs def display_info(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}") # Calling the function with multiple keyword arguments display_info(name="Harry", age=25, course="Python")
Output:
name: Harry
age: 25
course: PythonExample 2: Passing Mixed Parameters with **kwargs
**kwargs can be combined with other parameters. Positional arguments and *args must come before **kwargs.
# Defining a function with a regular parameter and **kwargs def student_info(name, **details): print(f"Student Name: {name}") for key, value in details.items(): print(f"{key}: {value}") # Calling the function student_info("John", age=20, course="Java", duration="6 months")
Output:
Student Name: John age: 20 course: Java duration: 6 months
Example 3: Mixing *args and **kwargs
def course_info(course, *topics, **details): print(f"Course: {course}") print("Topics Covered:", topics) for key, value in details.items(): print(f"{key}: {value}") # Calling the function course_info("Python", "Loops", "Functions", duration="3 months", level="Beginner")
Output:
Course: Python Topics Covered: ('Loops', 'Functions') duration: 3 months level: Beginner
Example 4: Order of Parameters with **kwargs
Order of Parameters: Regular parameters, *args, Default parameters, **kwargs
def student_data(name, *subjects, age=18, **details): print(f"Name: {name}, Age: {age}") print("Subjects:", subjects) print("Additional Info:", details) student_data("Pavan", "Math", "Science", city="New York", grade="A")
Output:
Name: Pavan, Age: 18 Subjects: ('Math', 'Science') Additional Info: {'city': 'New York', 'grade': 'A'}
Lambda Functions in Python
A lambda function in Python is a small, anonymous function that can have any number of arguments but only one expression. It is often used for short, simple operations where defining a full function is unnecessary.
Syntax:
lambda arguments: expression- arguments – Input values passed to the lambda function.
- expression – A single expression evaluated and returned.
Example 1: Calculate Total Marks
# Lambda to calculate total marks of a student total_marks = lambda sub1, sub2, sub3: sub1 + sub2 + sub3 # Sanfoundry student's marks print("Total Marks:", total_marks(85, 90, 95))
Output:
Total Marks: 270Example 2: Check Pass or Fail
# Lambda to check pass or fail based on marks pass_fail = lambda marks: "Pass" if marks >= 40 else "Fail" # Checking result print("Result:", pass_fail(75)) # Sanfoundry student passed print("Result:", pass_fail(35)) # Sanfoundry student failed
Output:
Result: Pass Result: Fail
Example 3: Square of a Number
# Lambda to calculate square of a number square = lambda x: x ** 2 print("Square:", square(5))
Output:
Square: 25Example 4: Using lambda with map()
# List of numbers numbers = [1, 2, 3, 4, 5] # Squaring numbers using map and lambda squared = list(map(lambda x: x ** 2, numbers)) print("Squared Numbers:", squared)
Output:
Squared Numbers: [1, 4, 9, 16, 25]
Example 5: Using lambda with filter()
# List of numbers numbers = [1, 2, 3, 4, 5, 6] # Filtering even numbers using filter and lambda even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) print("Even Numbers:", even_numbers)
Output:
Even Numbers: [2, 4, 6]
Example 6: Using lambda with reduce()
from functools import reduce # List of numbers numbers = [1, 2, 3, 4, 5] # Sum of elements using reduce and lambda sum_of_numbers = reduce(lambda x, y: x + y, numbers) print("Sum:", sum_of_numbers)
Output:
Sum: 15Recursive Functions in Python
A recursive function is a function that calls itself to solve a problem. It breaks a problem into smaller subproblems, solving each recursively until reaching a base case.
Syntax of a Recursive Function
def recursive_function(parameters): if base_condition: # Base case to stop recursion return result else: return recursive_function(modified_parameters) # Recursive call
Example: Factorial of a Number
# Recursive function to calculate factorial def factorial(n): if n == 1: # Base condition return 1 else: return n * factorial(n - 1) # Calculating factorial of 5 print("Factorial of 5:", factorial(5))
Output:
Factorial of 5: 120
Built-in Functions vs. User-defined Functions
Here’s a structured comparison of Built-in Functions vs. User-defined Functions in Python
| Feature | Built-in Functions | User-defined Functions |
|---|---|---|
| Definition | Pre-defined functions provided by Python. | Functions created by the user to perform specific tasks. |
| Usage | Can be used directly without definition. | Must be defined before they are called. |
| Flexibility | Limited to predefined operations. | Fully customizable based on user requirements. |
| Examples | print(), len(), sum(), type() | def greet():, def add_numbers(): |
| Need for Import | Available by default, no need to import. | Defined manually within the program. |
| Performance | Optimized for efficiency as they are built into Python. | Performance depends on how they are written. |
| Complexity | Simple to use with predefined functionality. | Can be simple or complex depending on the logic implemented. |
| Best Use Case | Common operations like printing, summing, and sorting. | Custom logic, automation, and modular programming. |
Function Annotations
Function annotations in Python allow you to attach metadata to function parameters and return values. They provide hints about expected data types but are not enforced by Python at runtime.
Annotations use a colon (:) for parameters and -> for the return type. For example:
def add(a: int, b: int) -> int: return a + b
These hints improve code readability and can be accessed using the __annotations__ attribute:
print(add.__annotations__) # Output: {'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}
Annotations are commonly used with type-checking tools like mypy to help detect type inconsistencies during development. They are useful for documentation and making code more maintainable.
FAQs on Python Functions
1. What is a function in Python?
A function in Python is a reusable block of code that performs a specific task. It is defined using the def keyword.
2. What are the types of functions in Python?
Python has built-in functions (e.g., print(), len()) and user-defined functions. User-defined functions can be regular functions, lambda functions, recursive functions, and functions with different types of parameters.
3. How do you define a function in Python?
A function is defined using the def keyword, followed by the function name and parentheses (). The code inside the function is indented.
4. What is the purpose of a return statement in a function?
The return statement is used to send a result back from a function. If there is no return statement, the function returns None by default.
5. What are default arguments in Python functions?
Default arguments have predefined values in the function definition. If no value is provided when calling the function, the default is used.
6. What is a lambda function?
A lambda function is an anonymous function defined using the lambda keyword. It can have multiple arguments but only one expression.
7. What is the scope of a variable in a function?
A variable inside a function is local to that function. Variables outside all functions have global scope.
8. How do you modify a global variable inside a function?
Use the global keyword before the variable inside the function.
9. What is a nested function?
A function defined inside another function is called a nested function. It is useful for encapsulation.
10. What is a higher-order function?
A function that takes another function as an argument or returns a function is called a higher-order function (e.g., map(), filter(), reduce()).
Key Points to Remember
Here is the list of key points we need to remember about “Python Functions”.
- A function in Python is a reusable block of code that performs a specific task. It helps in structuring programs efficiently.
- A function is defined using the def keyword, followed by a function name, parentheses (with optional parameters), and a colon, with the function body indented.
- Python functions can be categorized into built-in functions and user-defined functions. User-defined functions can include standard functions, lambda functions, and recursive functions.
- Positional arguments are passed in order and matched by position, whereas keyword arguments are passed with parameter names, allowing flexibility in argument order.
- *args allows a function to accept multiple positional arguments as a tuple, while **kwargs allows a function to accept multiple keyword arguments as a dictionary.
- Lambda functions are anonymous, single-expression functions used for short, simple operations without requiring a full function definition.