Python Functions: A Complete Guide

Python Functions: A Complete Guide

29 Mar 2024
Beginner
1.73K Views
26 min read
Learn via Video Course & by Doing Hands-on Labs

Python Programming For Beginners Free Course

Python Functions: An Overview

Python is a powerful language that allows you to quickly and effectively express your ideas. In this Python Tutorial, we'll be explaining Python Functions, Functions in Python with examples, a List of functions in Python, and exactly how functions work in Python so that anyone, regardless of experience level, can make the most out of their programming endeavors. So if you're looking for a better way to get things done with Python, keep reading and consider enrolling in a Python Certification Course for a better learning experience.

What are Functions in Python?

In Python, functions are organized pieces of reusable code that accomplish specified tasks. They help in the division of large programs into smaller, more manageable sections. Functions can accept parameters, process them, and return results.

Types of Functions in Python

In Python, there are two main types of functions:
  1. Built-in library functions: These are Python standard functions that can be used.
  2. User-defined function: Based on our requirements, we can write our functions.

Read More - 50 Python Interview Questions and Answers

Python Function Declaration

A Python function is a part of the code designed to carry out a certain purpose. It can be invoked from other parts of your program to run the code contained within it.

Syntax of Function Declaration

def function_name(parameters):  
# function body

Example of Python Function Declaration

        def greet(name):
    """Greets the user with their name."""
    print(f"Hello, {name}!")
greet("Ram")
greet("Shyam")

This code in the Python Online Editor defines a greet function that takes a name parameter. The function then prints a personalized greeting to the user based on the name parameter value. The code then executes the greet function twice, once with the name "Ram" and once with the name "Shyam".

Output

Hello, Ram!
Hello, Shyam!

Read More - Python Developer Salary

Creating a Function

  • Defining a function in Python is relatively straightforward, as Python comes with many Python built-in functions that can be called upon to achieve desired outcomes.
  • Creating custom Python functions starts by using the 'def' keyword followed by the name of the function.
  • After this point, variables and other Python instructions can then be used to craft precisely what the user wants the function to do.
  • It is important to provide meaningful names for the Python functions so that other developers who may use the code can easily identify what the function does without having to look into its inner workings.
  • Once defined, python functions can be called within other commands, drastically simplifying more complex logic and keeping all related code together.

Syntax of Creating a Function

def functionname( parameters ):
 "function_docstring"
 function_suite
 return [expression]

Calling a Function

  • Calling a Python function is relatively simple, provided its user knows what parameters it expects to receive.
  • All Python functions have a specific purpose, so make sure to research the function before calling it.
  • When calling a Python function, remember to place parentheses after the name of the function which contains any relevant parameters.
  • If no arguments need to be passed in, the parentheses will simply remain empty.
  • Beyond this, python functions do not require any additional information; simply type out the function name and watch as Python does its work.

Example of Calling a Function

        # Function definition is here
def printme( str ):
 "This prints a passed string into this function"
 print (str)
 return;
# Now you can call printme function
printme("I am the first call to a user-defined function!")
printme("Again a second call to the same function")

The "printme" function, which prints a string that is supplied to it, is defined in this Python script. It shows how to use two separate string arguments when calling this procedure twice.

Output

I am the first call to a user-defined function!
Again a second call to the same function

Pass by Value and Pass by Reference in Python

Pass by value in Python

  • In Python, pass-by-value is a method of passing arguments to functions.
  • This means that when an argument is passed to a function, the Python interpreter evaluates the expression and passes its value rather than the expression itself to the function.
  • This allows the program to do more with fewer lines of code, as well as resulting in faster execution.
  • Pass by value also helps Python be secure against external influences or user mistakes that could lead to unexpected or unwanted results.
  • By passing only values, it prevents external influences from affecting the program's run-time environment.
  • Pass by value becomes especially important when dealing with large-scale applications in Python that require highly optimized code for efficient execution.

Example of Pass by Value in Python

        student = {'Ram': 12, 'Rahul': 14, 'Rajan': 10}
def test(student):
  student = {'Shyam':20, 'Shivam':21}
  print("Inside the function", student)
  return 
test(student)
print("Outside the function:", student)

This Python code creates a dictionary named "student" with a few key-value pairs, then calls a function named "test" that transfers the "student" dictionary to a different dictionary. The new dictionary appears while printing inside the function, but since the modifications made by the function are local when printing outside the function, the old "student" dictionary appears.

Pass by reference in python

  • When programming in Python, pass-by-reference can help save a lot of time when trying to pass values between functions and classes.
  • Pass by reference allows for direct object modification, meaning the user doesn't have to work with copies of variables or pass every piece of data back and forth between functions.
  • Essentially, pass-by-reference creates a link from one object to another, which can then be used in the program.
  • As such, pass-by-reference should be considered any time the developer is performing multiple operations on an existing object without needing to create further copies.

Example of Pass by Reference in Python

        student = {'Ram': 12, 'Rahul': 14, 'Rajan': 10}
def test(student):
  new = {'Shyam':20, 'Shivam':21}
  student.update(new)
  print("Inside the function", student)
  return 
test(student)
print("Outside the function:", student)

This Python program defines a dictionary called "student" and a function called "test" that updates the dictionary named "student" by adding new key-value pairs from the function's "new" dictionary. The "student" dictionary reflects the adjustments performed by the function both inside and outside the function.

Number of Arguments

A function must always be called with the appropriate number of parameters by default. In other words, if your function requires 2 arguments, you must call it with 2 arguments, not more or fewer. An error will occur if you attempt to call the function with just one or three arguments.

Arbitrary Arguments, *args

  • Add a * before the parameter name in the function specification if you are unsure of the number of arguments that will be given to your function.
  • The function will then receive a tuple of parameters and be able to retrieve the elements as necessary.

Example of Arbitrary Arguments in Python

        def sum_numbers(*args):
  total = 0
  for num in args:
    if not isinstance(num, (int, float)):
      raise TypeError(f"Expected a number, got {num}")
    total += num
  return total
# Example usage:
result = sum_numbers(1, 2, 3, 4, 5)
print("Sum:", result)

The sum_numbers function in this example accepts any number of inputs, and it adds them all together using a for loop in python. When you call sum_numbers(1, 2, 3, 4, 5), the sum of those numbers is computed, returned, and reported to the console. You are free to pass as many arguments as you wish; they will all be gathered into the function's args tuple.

Output

Sum: 15

Keyword Arguments

  • The key = value syntax allows you to send parameters as well.
  • This makes the argument's order of occurrence irrelevant.

Example of Keyword Arguments in Python

        def greet(name, age):
 print(f"Hello, {name}! You are {age} years old.")
# Using keyword arguments to call the function
greet(name="Alice", age=30)
greet(age=25, name="Bob")

Name and age are the two parameters that the greet function in this example accepts. We use keyword arguments to define these parameters when calling the function. As you can see, the parameters defined in the function's definition need not be passed to it in the same order as the arguments.

Output

Hello, Alice! You are 30 years old.
Hello, Bob! You are 25 years old.

Arbitrary Keyword Arguments, **kwargs

  • Before the parameter name in the function definition, add two asterisks: ** if you are unsure of the number of keyword arguments that will be provided in your function.
  • By receiving a dictionary of parameters in this manner, the function will be able to access the elements properly.

Example of Arbitrary Keyword Arguments in Python

        def print_kwargs(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")
# Example usage
print_kwargs(name="Alice", age=30, city="New York")

The print_kwargs method in this example accepts any keyword parameters using **kwargs. A dictionary kwargs is created when the function is called with the arguments name="Alice," age="30," and city="New York." The function then outputs each key-value pair in the dictionary.

Output

name: Alice
age: 30
city: New York

Function Arguments

  • Functions accept arguments that can contain data.
  • The function name is followed by brackets that list the arguments.
  • Simply separate each argument with a comma to add as many as you like.

Example of Function Arguments in Python

        # Function with positional arguments
def add_numbers(a, b):
 result = a + b
 return result
# Calling the function with positional arguments
sum_result = add_numbers(3, 5)
print("Sum:", sum_result)# Function with keyword arguments
def greet_person(first_name, last_name):
 greeting = f"Hello, {first_name} {last_name}!"
 return greeting
# Calling the function with keyword arguments
greeting_message = greet_person(first_name="John", last_name="Doe")
print(greeting_message)

The code defines two functions: 'add_numbers' accepts two positional arguments and returns their sum, and 'greet_person' takes two keyword parameters and provides a greeting. With certain arguments, the functions are called, and the output is reported.

Output

Sum: 8
Hello, John Doe!

Required arguments in Python

  • As the name indicates, mandatory arguments are those that must be given to the function at the time of the function call.
  • Failure to do so will lead to a mistake. In simple terms, default function parameters are the exact opposite of required arguments.

Example of Required Arguments in Python

        def add_numbers(a, b):
 result = a + b
 return result
# Call the function with required arguments
sum_result = add_numbers(5, 3)
print("Sum:", sum_result)

This example uses the add_numbers function, which requires the two inputs a and b. Both a and b must have values when calling this function. We are passing 5 as a and 3 as b in the add_numbers(5, 3) call. The result of the function's addition of these two numbers is then returned and reported to the console.

Output

Sum: 8

Default Parameter Value

  • When a function is defined in Python, default parameter values are values that are given to the function's parameters.
  • It is optional to send an argument for that parameter when calling the function because these default values are utilized if the caller of the function does not supply a value for that parameter.

Example of Default Parameter Value in Python

        def greet(name="Guest"):
 print(f"Hello, {name}!")
# Calling the function with and without an argument
greet() # Output: Hello, Guest!
greet("Alice") # Output: Hello, Alice!

In this example in the Python Online Compiler, the name argument for the greet function's default parameter value is set to "Guest". The function uses the default value when called without an argument. If you supply an argument, it substitutes the supplied value.

Output

Hello, Guest!
Hello, Alice!

Default arguments in Python

  • The syntax representation and default values for function parameters are different in Python.
  • If no argument value is given during the function call, default values mean that the function parameter will assume that value.
  • By employing the python's assignment(=) operator with the syntax keywordname=value, the default value is set.

Example of Default Arguments in Python

        def greet(name, greeting="Hello"):
 """Greet a person with a default greeting."""
 print(f"{greeting}, {name}!")
# Calling the function without providing a custom greeting
greet("Alice") # Output: Hello, Alice!
# Calling the function with a custom greeting
greet("Bob", "Hi") # Output: Hi, Bob!

Name and greeting are the two parameters for the greet function in this example. The default value for the greeting argument is "Hello." The default value is used when the function is called without a value for greeting. The default value can be overridden by passing a specific greeting when using the function, though.

Output

Hello, Alice!
Hi, Bob!

Variable-length arguments in Python

  • Arguments that can accept an infinite amount of data as input are known as variable-length arguments or varargs.
  • When using them, the developer is not required to wrap the data in a list or another sequence.
  • Python recognizes two different forms of variable-length arguments: non-keyworded arguments (*args) and keyword arguments (**kwargs).

Example of Variable-length Arguments in Python Compiler

        # Define a function that accepts a variable number of arguments
def add_numbers(*args):
    result = 0
    for num in args:
        result += num
    return result
# Call the function with different numbers of arguments
sum1 = add_numbers(1, 2, 3)
sum2 = add_numbers(10, 20, 30, 40, 50)
# Print the results
print("Sum 1:", sum1)  # Output: Sum 1: 6
print("Sum 2:", sum2)  # Output: Sum 2: 150

The add_numbers function in this example uses *args to accept a variable number of parameters. The sum of the arguments is then calculated after iterating over each one. This function can be called with any amount of input, and it will compute the sum appropriately.

Output

Sum 1: 6
Sum 2: 150

Recursion

  • Python also permits function recursion, allowing defined functions to call one another.
  • A frequent concept in math and programming is recursion.
  • It denotes that a function makes a call to itself.
  • This has the advantage of allowing you to loop through data to conclude.
  • The developer should exercise extreme caution when using recursion because it is quite simple to write a function that never ends or consumes excessive amounts of memory or processing resources.
  • Recursion, however, can be a very effective and mathematically elegant technique for programming when used properly.

Example of Recursion in Python

        def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)
# Test the factorial function
num = 5
result = factorial(num)
print(f"The factorial of {num} is {result}")

This Python program first builds the recursive function "factorial(n)," which computes the factorial of a non-negative integer "n," before testing it by computing and printing the factorial of 5.

Output

The factorial of 5 is 120

Anonymous Functions in Python

  • Anonymous functions in Python are incredibly useful for quickly writing simple, single-use functions that don't require a full definition.
  • Anonymous functions take the form of lambda expressions, where the user passes particular parameters through a single expression.
  • These functions can then be used in places where the developer would use any other type of function, such as with the map or filter constructors.
  • Anonymous functions are essential tools when dealing with higher-order functions such as reduce, which is used to condense a sequence of data into one value.
  • Anonymous Functions allow for concise code that would otherwise require several lines to write, making them important to bear in mind when programming with Python.

Syntax of Anonymous Functions in Python

lambda [arg1 [,arg2,.....argn]]:expression

Example of Anonymous Functions in Python

        # Function definition is here
sum = lambda arg1, arg2: arg1 + arg2;
# Now you can call sum as a function
print ("Value of total : ", sum( 10, 20 ))
print ("Value of total : ", sum( 20, 20 ))

This program in the Python Editor defines the lambda function "sum," which takes two arguments and returns the sum of those arguments. It explains how to compute and display the sums of 10 and 20 and 20 and 20, respectively, using the lambda function.

Output

Value of total : 30
Value of total : 40

Summary

Python functions allow us to define specific tasks, pass parameters, receive return values, and even group related code into fewer lines of code. Using these techniques in our everyday coding, especially when pursuing a Python Certification, will help make our work easier to maintain, reducing both development time and errors.

FAQs

Q1. What are functions in Python?

In Python, functions are reusable units of code that carry out particular tasks.

Q2. How many functions are in Python?

Depending on the Python version and libraries used, there are several built-in functions in Python.

Q3. What are the top 5 functions in Python?

Print(), len(), range(), input(), and str() are frequently among the top 5 built-in functions in Python.

Q4. What is an argument?

In Python, an argument is a value or variable that is supplied to a function to use while it is being executed.

Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
Angular Certification Course May 25 SAT, SUN
Filling Fast
06:00PM to 08:00PM (IST)
Get Details
Full Stack .Net Certification Training May 26 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
ASP.NET Core Certification Training May 26 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification Training May 26 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Data Structures and Algorithms Training Jun 04 TUE, FRI
Filling Fast
08:30PM to 10:00PM (IST)
Get Details
Azure DevOps Certification Training Course Jun 09 SUN
Filling Fast
04:30PM to 06:30PM (IST)
Get Details
ASP.NET Core Certification Training Jun 21 MON, WED, FRI
Filling Fast
07:00AM to 08:30AM (IST)
Get Details
Azure Developer Certification Training Jun 23 SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Sakshi Dhameja (Author and Mentor)

She is passionate about different technologies like JavaScript, React, HTML, CSS, Node.js etc. and likes to share knowledge with the developer community. She holds strong learning skills in keeping herself updated with the changing technologies in her area as well as other technologies like Core Java, Python and Cloud.

Accept cookies & close this