Functions In Python And It’s Examples

1
544

What Are Functions In Python?

A function is a block of code that performs a specific task and runs only when it is called.  Functions generally take in the data, process it, and return a result. Python provides various built-in functions like print(), etc. Like, other programming languages here also we can create our own functions, these functions are called user-defined functions.

Why do we Write Functions?

  • The basic idea is to put some commonly or repeatedly done tasks together and make that as a function so that instead of writing the same code again and again for different inputs, we can directly call the function.
  • Functions allow us to keep our variable namespace clean (i.e., local variables only “live” as long as the function does). In other words, function_one can use a variable called i, and function_two can also use a variable called i and there is no confusion. Each variable i only exists when the system is executing the given function.
  • Functions allow us to test small parts of our program separately in isolation from the rest.

Basic Syntax for Functions in Python

various Syntax for Functions in Python for users.
Syntax for Functions in Python

How To Create a Functions?

In Python Programming language we define a function by using the def keyword.
Example:

def my_function():
     print("Hello from a function")

How to Call Functions?

To call a function in Python, use the function name followed by a parenthesis.
Example:

def my_function():
     print("Hello from a function")

my_function()

Output:

Hello from a function

Parameters

Information can be passed to functions as parameter. Parameters are written after the function name, inside the parenthesis. One can add as many parameters as you want, just separate them with a comma(,).


The following below example has a function with one parameter (fname). When the function is called, we pass along a string, which completes the whole word.

def function(fname)
     print("Data " + fname)

function("Science")
function("Analysis")

Output:

Data Science, Data Analysis

When Passing a List as a Parameter

You can send any data types of the parameter to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.
E.g. when we send a list as a parameter, it will still be a List when it reaches the function.

def my_function(Cities):
  for x in Cities:
    print(x)

cities = ["Nagpur", "Pune", "Mumbai"]

my_function(Cities)

Output:

Nagpur, Pune, Mumbai

Returning Values

When we want a function to return a value, we use the return statement.
Example:

def my_function(x):
     return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))

Output:

10, 25, 45

Keyword Arguments

In Python, you can also send arguments with the key = value syntax.
Here the order of the arguments does not matter.
Example:

def my_function(child3, child2, child1):
  print("The youngest child is " + child3)

my_function(child1 = "Rahul", child2 = "Rohan", child3 = "Ganesh")

Output:

The youngest child is Ganesh

Arbitrary Arguments

In the case when you do not know how many arguments that will be passed into your function, add a * before the parameter name in the function definition.


Here the function will receive a tuple of arguments and can access the items accordingly
Example:

def fage(*kids):
print("The youngest child is " + kids[2])

fage("Rahul", "Rohan", "Ritesh")

Output:

The youngest child is Ritesh

Recursion in Python

As in other programming languages, Python also accepts function recursion, which means a defined function can call itself.


Recursion is a common mathematical and programming concept which means that a function calls itself. This has the meaning that you can loop through data to reach a result.
The developer must be very careful with recursion as it can be quite easy to commit mistake in writing a function which never terminates i.e., making it an infinite loop, also which can uses excess amounts of memory or processor power.

However, when written correctly recursions can be a very useful approach to programming.
Example:

# FactoriaL of a number using recursion
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num = 7
# check if the number is negative
if num < 0:
print("Sorry, factorial does not exist for negative numbers") elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recurfactorial(num))

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here