Python Functions

Today we’ll discuss Python functions with examples in an attempt to satisfy the thirst of readers.

The Python function is a block of code that runs only when it is invoked.

Data can be passed into a function as parameters.

When a function returns data, it is called a return value.

 

python functions detail examples

 



Python Functions Types

Functions in Python can be divided into two types:

  • Python’s standard library functions are built-in functions that can be used.
  • User-defined functions – Depending on our needs, we can create our own functions.

In Python functions, standard library functions are built-in functions we can use directly.

  1. print() – displays the string inside quotation marks.
  2. sqrt() – returns a number’s square root.
  3. pow() – gives the power of a number.

A module defines these library functions. It is necessary to include the module within our program in order to use them in Python functions.


Creating a Python Function

The syntax of functions

  1. def – Statement to declare functions.
  2. function_name – Give your function a name.
  3. arguments – The value to pass to the function.
  4. return (optional) – returns a value.

We define our first Python functions using the def statement and name it as follows:

def mrx_function():
      print("Above you have created your first function in python")

Call Python Function

The name of the function must be followed by parenthesis when calling Python functions:

Example: 

def mrx_function(): print("Hi, This is a response from mrx function.") mrx_function()

 

python functions print example


Arguments Number

Python functions must be called with the proper number of arguments by default. You should not call a function with more or fewer arguments if it expects two arguments.

There are two arguments expected and two arguments received by this function:

Example

def mrx_function(fname, lname): print(fname + " " + lname) mrx_function("Elon", "Musk")

You will get an error if you try to call the function with less or more arguments:

Only one argument is passed to this function, but it requires two:

Example

def mrx_function(fname, lname): print(fname + " " + lname) mrx_function("Elon Musk")

Python Function Arguments

Python functions can take arguments, which are pieces of information to be passed into the function.

Parentheses are used to place arguments after the function name. With a comma between each argument, you can add as many as you like.

In the following example, there is one argument (firm) to the function. A first name is passed along when the function is called, which will be used to print the full name inside the function:

Execute

Example

def mrx_function(firm): print(firm + " PVT LTD") mrx_function("Alphabet ") mrx_function("Tesla ") mrx_function("PayPal ")

Additional Information :Python documentation often refers to arguments as args.


Parameters or Arguments?

It is possible to refer to parameters and arguments as the same information passed to a Python function.

As seen from the perspective of a function:

When a function is defined, the parameters are the variables listed inside parentheses.

Arguments are values that are sent to functions when they are called.


Keyword Arguments

The key = value syntax can also be applied when supplying arguments to Python functions.

By doing so, it does not matter in which order the arguments are presented.

Execute

Example

def mrx_function(child3, child2, child1): print("The richest CEO is " + child1) mrx_function(child1 = "Elon Musk", child2 = "Jeff Bezos", child3 = "Mark Zuckerberg")

Important: In Python documentation, Keyword Arguments is often abbreviated to kwargs.


Arbitrary Arguments, *args

If you are unsure how many arguments your function will take, add an asterisk * before the parameter name in a Python function definition.

Using this method, the function will receive a tuple of arguments, and it will be able to access those arguments as follows:

When there is unknown number of arguments, add a * before the parameter name:

Example

def mrx_function(*ceos): print("World top Ceo's are " + ceos[2]) mrx_function("Elon Musk", "Jeff Bezos", "Mark Zuckerberg")

Note: Python documentation often shortens arbitrary arguments to args.


Arbitrary Keyword Arguments, **kwargs

Adding two asterisks ** before the parameter name in Python functions is convenient when you are unsure how many keyword arguments will be passed into your function.

A dictionary of arguments will be provided to the function, which will then be able to access each item as necessary:

Add a double asterisk ** before the parameter name if you do not know how many keyword arguments there are:

Example

def mrx_function(**ceo): print("Richest man last name is " + ceo["lname"]) mrx_function(fname = "Elon", lname = "Musk")

Tip: It is common for Python documentation to shorten arbitrary Kword Arguments to **kwargs.


The recursion

Function recursion is also supported by Python, meaning that a function can call itself within the same function.

A common mathematical and programming concept is recursion. In other words, it means that a function calls itself. The benefit of this is that Python functions can loop over data to return a result.

Developers should be extremely careful when using recursion. This is because it can be quite easy to accidentally write a function that never terminates, or one that consumes an excessive amount of memory or processing power. When programmed correctly, recursion is a highly effective and mathematically elegant approach to programming.

Using tri_recursion(), we define a function that will run itself (“recurse”). Our data is the x variable, which decrements by one every time we recurse. If the condition is zero, the recursion ends.

When you are new to programming, it can take some time to understand how exactly this works. The best way to learn how exactly it works is to test it out and customize it as much as you can.

Execute

Example

def tri_recursion(x): if(x > 0): mrxoutput = x + tri_recursion(x – 1) print(mrxoutput) else: mrxoutput = 0 return mrxoutput print("\\n\\nRecursion Example Output") tri_recursion(6)

Default Parameter Value

Using a default parameter value is demonstrated in the following example.

The default value of the function is used if it is called without an argument:

Execute

Example

def mrx_function(country = "Germany"): print("I am from " + country) mrx_function("USA") mrx_function("Canada") mrx_function() mrx_function("Austria")

Passing a List as an Argument

Function arguments of any type will be treated the same in the function (string, number, list, dictionary, etc.).

For instance, a List sent as an argument will still be a List when it reaches the function:

Execute

Example

def mrx_function(firms): for sam in firms: print(sam) fruits = ["Elon Musk", "Jeff Bezos", "Mark Zuckerberg"] mrx_function(fruits)

The pass Statement

It is not possible to have an empty function definition, however, you can put a pass statement in to avoid getting an error if there is no content in the function definition.

Execute

Example

def mrxfunction(): pass

Return Values

Use the return statement to return a value from a function:

Example: 

def mrx_function(sam): return 9 * sam print(mrx_function(3)) print(mrx_function(5)) print(mrx_function(9))

Python Functions Importance

The importance of using python functions are as follow:

  • Functions allow you to write reusable code blocks that can be called multiple times throughout your program. This promotes code efficiency and reduces redundancy.
  • Functions improve the readability of your code by breaking it into smaller, logical components. This makes it easier to understand and maintain your codebase, especially as it grows in complexity.
  • Functions encapsulate a set of instructions, providing a higher-level abstraction of functionality. This allows you to hide the implementation details and focus on the functionality provided by the function.
  • Functions help in organizing your code by dividing it into smaller, manageable chunks. This improves the overall structure of your program and makes it easier to navigate and comprehend.
  • Functions can accept parameters, allowing you to pass values into the function and customize its behavior. This makes functions flexible and adaptable to different scenarios, enhancing the reusability and versatility of your code.
Get the latest technical information delivered to your inbox by subscribing to our Newsletter.
We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

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