Programmer Coding

Function in Python

What is Function

A set of statements that returns the particular task is called a Python function. The concept is to group together some often performed activities into a function so that, rather than writing the same code repeatedly for various inputs, we can call the function calls repeatedly to reuse the code they contain.

Types of Python Functions

  • Built-in functions
  • User-defined functions

Python’s standard library has many powerful functions. Some functions in Python include print(), int(), len(), sum(), etc. is available. These functions are always available because they are loaded into the computer’s memory as soon as the Python interpreter starts.

standard library also combines various modules. Each module defines a set of tasks. These features are not easy to use. You need to transfer them from their modules into memory.

In addition to creating projects and working in the creation group, you can also create your own projects. These functions are called user-defined functions.

Defining a Python Function

You can define custom functions to provide the required functionality. Here are simple rules to define a function in Python.

  • A function block begins with the def keyword, followed by the function name and a parentheses ( ( ) ).
  • All input parameters or parameters must be placed in these lines. You can also check the parameters in this system.
  • The first statement of the work may be optional; functions of document string or docstring.
  • Blocks of code in each function begin with a colon (:) and are indented.
  • Message return [description] Non-functional, optionally forward the message back to the caller. A return with no parameters is the same as returning None.

Syntax to Define a Python Function

def function_name(parameters):
"""function_docstring"""
# function_suite (code block)
# Perform tasks here
# You can use the parameters passed to the function
return [expression]

By default, parameters have a positional behavior and you need to inform them in the same order that they were defined.

Once the function is defined, you can execute it by calling it from another function or directly from the Python prompt.

Example to Define a Python Function

The following example shows how to define a function programmer(). The bracket is empty so there aren’t any parameters.

The first line is the docstring. Function block ends with return statement. when this function is called, programmercoding.com message will be printed.

def programmer():
    "This is docstring of greetings function"
    print("programmercoding.com")
    return

programmer()

Calling a Python Function

Defining a characteristic handiest gives it a name, specifies the parameters which might be to be included in the characteristic and structures the blocks of code.

once the simple shape of a function is finalized, you may execute it by way of calling it from any other function or directly from the Python spark off.

Example to Call a Python Function

Following is the example to call printme() function –

# Function definition
def printme(str):
    "This prints a passed string into this function"
    print(str)
# Call the function with different strings
printme("Welcome to programmercoding.com!")
printme("This is another example of calling a user-defined function.")

Output

Welcome to programmercoding.com!

This is another example of calling a user-defined function.

 

Pass by Value vs Reference

Python’s function calling mechanism is different from C and C++. There are two main functions called mechanisms: calling by value and calling by reference.

When a variable is passed to a function, what does the function do with it? If a change made to the variable is not reflected in the space, it uses the call by value mechanism. On the other hand, if change occurs, it becomes a call-by-reference mechanism.

C/C++ functions are said to be called by value. When a function is called in C/C++, the value of the actual value is not copied into the variable representing the invalid value. If the function changes the value of the argument, it does not affect the variable passed to it.

Python uses pass-by-reference mechanism. Since variables in Python are labels or pointers to objects in memory, mutable objects are used as null and void values ​​to refer to the same object in memory. We can verify this fact by checking the ID of the variable before and after passing it().

Example

# Function definition
def testfunction(arg):
    print("ID inside the function:", id(arg))
# Define a list
my_list = "programmercoding.com"
# Print the ID before passing to the function
print("ID before passing:", id(my_list))
# Call the function with the list as argument
testfunction(my_list)

Output

ID before passing: 139354219323008

ID inside the function: 139354219323008

Python Function Arguments

The performance of a function often depends on some information given to it when it is called. When you define a function, you must provide a variable name that contains the information passed to the function. Variables in the sentence are called formal parameters.

When calling a function, you must provide a value for each parameter. These are called lies.

Example

def programmer(name):
    "This is docstring of programmer function"
    print("Hello {}".format(name))
programmer("Ramkrishna")
programmer("Mausam Mishra")
programmer("Rohan Kumar")

Output

Hello Ramkrishna

Hello Mausam Mishra

Hello Rohan Kumar

Types of Python Function Arguments

  • Positional Arguments
  • Keyword Arguments
  • Default Arguments
  • Variable-Length Positional Arguments (*args)
  • Variable-Length Keyword Arguments (**kwargs)

Positional Arguments

Positional arguments are the maximum common type of arguments.

They may be handed to the feature based totally on their position or order in the characteristic call.

The function parameters acquire the values of positional arguments within the identical order.

Example

# Function definition with two parameters: name and coding
# The function prints a message using the provided name and coding
def programmer(name, coding):
    print(f"{coding}, {name}!")
# Calling the function with arguments "Ramkrishna" and "Hello"
programmer("Ramkrishna", "Hello")

Output

Hello, Ramkrishna!

Keyword Arguments

Keyword arguments are exceeded to the function with their corresponding parameter names.

They permit specifying arguments in any order, so long as their names are provided.

Example

# Function definition with two parameters: name and coding
def programmer(name, coding):
    print(f"{coding}, {name}!")
# Calling the function with keyword arguments
# Here, the arguments are passed in a different order compared to the function definition
# The function correctly identifies the parameters based on their names
programmer(coding="Hello", name="Mausam Mishra")

Output

Hello, Mausam Mishra!

Default Arguments

Default arguments have default values assigned to them within the function definition.

If a cost isn’t furnished for a default argument for the duration of the function name, the default cost is used.

Example

# Function definition with a default argument for coding
def programmer(name, coding="Hello"):
    print(f"{coding}, {name}!")
# Calling the function with only the required argument name
# Since a value is not provided for the default argument coding, its default value "Hello" is used
programmer("Vishnu Singh")

Output

Hello, Vishnu Singh!

Variable-Length Positional Arguments (*args)

Variable-period positional arguments permit passing an arbitrary wide variety of arguments to a characteristic.

they are represented by way of an asterisk * observed by using a parameter name (often args by conference).

inside the characteristic, args turns into a tuple containing all of the more positional arguments.

Example

# Function definition with variable-length positional arguments *args
def sum_numbers(*args):
# Calculate the sum of all arguments using the sum() function
    total = sum(args)
# Print the sum
    print("Sum:", total)
# Calling the function with multiple arguments
# The arguments are passed as a sequence of values
sum_numbers(1, 2, 3, 4, 5)

Output

Sum: 15

Variable-Length Keyword Arguments (**kwargs)

Variable-length key-word arguments permit passing an arbitrary range of key-word arguments to a characteristic.

they’re represented by means of two asterisks ** accompanied via a parameter name (regularly kwargs with the aid of conference).

in the feature, kwargs will become a dictionary containing all of the more keyword arguments.

Example

# Function definition with variable-length keyword arguments **kwargs
def coder(**kwargs):
# Iterate over the key-value pairs in kwargs
    for name, coding in kwargs.items():
# Print each name and coding
        print(f"{coding}, {name}!")
# Calling the function with keyword arguments
# Here, the arguments are passed as key-value pairs
coder(Shubham_Kashyap="Hello", Ankit_Jha="Hi", Birendra_Yadev="Hey")

Output

Hello, Shubham_Kashyap!

Hi, Ankit_Jha!

Hey, Birendra_Yadev!

Python Function with Return Value

The return keyword in the last expression of the function means the end of the function block and the service flow returns to the calling function. It is good practice to use return, although decreasing the indentation after the last statement in a block also affects the return.

In addition to flow control, functions can pass the value of pointers back to the callback. The value of the returned message can be stored in a variable for further processing.

Example

# Function definition for subtracting two numbers
def sub(a, b):
# Subtract b from a and store the result in c
    c = a - b
# Return the result
    return c
# Define two variables x and y with values 198 and 125 respectively
x = 198
y = 125
# Call the sub function with arguments x and y
# Store the result of the function call in the variable result
result = sub(x, y)
# Print the values of a, b, and the result of the subtraction
print("a = {} b = {} a-b = {}".format(x, y, result))

Output

a = 198 b = 125 a-b = 73

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top