Functions

A function is defined as a block of organized, reusable code used to perform a single, related action. Python has many built-in functions; you can also create your own.

Let's take a look at the print and len function in Python.

The print(object) function prints the given object to the standard output device (screen) or to the text stream file. That’s why if you type in print("Hello World") you get the output Hello World.

Same goes for len, The len(object) function returns the number of items in an object.When the object is a string, the len() function returns the number of characters in the string.

Now let's create our own function to use for greeting.

In [2]: def greet (name):
"""This function greets
the name passed in as
parameter"""
print("Good morning! Mr "+ name +". How are you doing today? ")

So above we have defined our function greet, lets see what happens when we execute our function.

In [2]: greet('Michael')

Out[2]: Good morning! Mr Michael. How are you doing today?

So we can see that when we made the object name "Michael" we have an output that greets Michael from the function. Now the advantage of this is let’s assume you have an app that need to greet a user. To do that in your application, you just call on the function greet to handle that.

results matching ""

    No results matching ""