Press "Enter" to skip to content

Python Function

Zigya Acadmey 0

What is a Function?

OK, here goes. A function performs a specific operation on its arguments and produces a predictable output. Huh, not much simpler, and definitely not as precise (or as correct) as the other definition. Let me give you an example of an automated teller (ATM) machine which provides money (if your bank approves!).

The ATM has a function which gives you money based on a bunch of different inputs: (your card, your pin number, the amount of cash requested, the availability of cash in the machine, and whether or not your bank approves of the withdrawal). The ATM is quite a bit more complicated than this, but I only needed a quick example and this will do fine. Every time you use the ATM to withdraw cash, you are using the same function. If the inputs remain the same then the output will be predictably the same: cash (if everything is fine) and no cash (if the machine is empty, for example). If the ATM behaved randomly it would be of no use at all.

We could say that finding the product of two numbers is a function. A python function which accepts two numbers as input arguments, multiplies them, then returns the product as the output is a function.

Let’s Code

def greet(name):
    return "Welcome {}!!".format(name)
>>> greet('Sarah')
'Welcome Sarah!!'

Functions Are Objects

All data in a Python program is represented by objects or relations between objects. Things like strings, lists, modules and functions are all objects. There’s nothing particularly special about functions in Python. They’re also just objects.

Since greet function is an object, we can assign it to another variable, just like any other object:

>>> receive = greet

The above line does’t call the function. It takes the function object reference by greet and creates a second name, receive, that points to it. We can execute the method by calling receive:

>>> receive('Sarah')
'Welcome Sarah!!'

Function objects and their names are two separate things. We can delete the functions’ original name (greet) and still call the function, since another name (receive) still points to it.

>>> del greet
>>> greet('Sarah')
NameError: "name 'greet' is not defined"
>>> receive('Sarah')
'Welcome Sarah!!'

Therefore, a variable pointing to a function and the function itself are two separate concerns.

Functions Can Be Stored in Data Structures

Since functions are first-class citizens, we can store them in data structures, just like we can with other objects. For example, we can add functions to a list:

>>> funcs = [len, str.isdigit, str.lower]
>>> funcs
[ <built-in function len>,
 <method 'isdigit' of 'str' objects>,
 <method 'lower' of 'str' objects> ]

Accessing the function objects stored inside the list works like it would with any other type of object:

>>> for f in funcs:
... print(f, f('Hello World!'))<built-in function len> 12
<method 'isdigit' of 'str' objects> False
<method 'lower' of 'str' objects> hello world

Functions Can Be Passed to Other Functions

Because functions are objects, we can pass them as arguments to other functions.

def accept(func):
    msg = func('Roark')
    print(msg)>>> accept(greet)
'Welcome Roark!!'

We can influence the resulting msg by passing in different functions. For example:

def leave(name):
    return "Good Bye {}!".format(name)>>> accept(leave)
'Good Bye Roark!'

The ability to pass function objects as arguments to other functions is powerful. It allows us to abstract away and passes around behaviors. In the above example, accept function stays the same but we can influence its output by passing in different behaviors.

Functions Can Be Nested

Perhaps surprisingly, Python allows functions to be defined inside other functions. They are often called nested functions or inner functions.

def speak(text):
def whisper(t):
return t.lower + "..."
return whisper(text)>>> speak('Hello World')
'hello world...'

Now, what’s happening above? Every time we call speak, it defines a new inner function whisper and then calls it immediately after.

Also, what’s noteworthy here is — whisper does not exists outside speak:

>>> whisper('hello')
NameError: "name 'whisper' is not defined"

NOTE: if we really want to access that nested whisper function from outside speak, we can return the inner function to the caller of parent function. For example:

def get_func(flag):
    def add(a, b):
        return a + b
    def multiply(a, b):
        return a * b
    if flag > 0.5:
        return multiply
    else:
        return add>>> func_inst = get_func(0.7)
>>> func_inst
<function get_func.<locals>.multiply at 0x102d54290>
>>> func_inst(10, 6)
60

This means not only can functions accept behaviors through arguments but they can also return behaviors.

Conclusions:

  • Everything in Python is an object, including functions. We can assign them to variables, store them in data structures, and pass or return them to and from other functions.
  • First-class functions allow us to abstract away and pass around the behavior in our program.
  • Objects can be made callable. In many cases this allows us to treat them as functions.

This brings the end of this Blog. We really appreciate your time.

Hope you liked it.

Do visit our page www.zigya.com/blog for more informative blogs on Data Science

Keep Reading! Cheers!

Zigya Academy
BEING RELEVANT

Leave a Reply

Your email address will not be published.