DEV Community

Cover image for Introduction to Python Functions
kubona Martin Yafesi
kubona Martin Yafesi

Posted on • Edited on

Introduction to Python Functions

Welcome dear friend to yet another exciting talk about Python.
Last time we were here, we discussed about what Python is, what it is used for and also looked at its application domains. I hope you enjoyed that!! If you are new here, please check it out here.

What is the agenda for today?

Well today is going to be another fun ride. We will talk about functions. Topics of discussion will be:

  • What functions are?
  • How to define them.
  • When and how to use them.

We will have some examples for illustration purposes

Great!! I cannot already wait to jump right in...

Ohh I see, let us head to the fun part without wasting much time.

Functions:

A function is a group of related statements that perform a given task. So whenever you call a function, those statements will perform that task, however many times you call the function.

You said related statements! What do you mean by that?

Great question. Yes, now suppose you want your code to print your name and calculate your age very many times. So traditionally you would write your code like this and repeat it many times. Have a look:

Code Example 1


name = "Cool Python Guy"
year_of_birth = int(input("What is your year of birth"))
age = 2021 - year_of_birth

print(f"My name is {name} and I am {age} years old")

Enter fullscreen mode Exit fullscreen mode

To avoid repeating yourself to just print your name and age. You would create a function with your code. So whenever you want your name and age printed, guess what.... call the function!!!
Is that not cool?

Yeah that is really cool stuff!!! Please tell me more, I love doing cool things

So coming to the actual cool stuff, lets rewrite our code in a function. Are you ready? See this:

Code Example 2


def name_age():
   name = "Cool Python Guy"
   year_of_birth = int(input("What is your year of birth"))
   age = 2021 - year_of_birth
   # Printing the name and age
   return f"My name is {name} and I am {age} years old"
Enter fullscreen mode Exit fullscreen mode

So if you wanted to print your name and age many times, simply call your function like;

Code Example 3

name_age()
name_age()
name_age()
""" 
You can call it any number of times you like
Your name and age will be printed those many times

"""
Enter fullscreen mode Exit fullscreen mode

I see how that can save my a lot of time...

Yeah you can save plenty of time, and boost your productivity. Also you have the advantage of not repeating yourself. You will soon notice that using functions makes your code readable by say your fellow programmer or Chief Technical Officer (CTO). (You most likely will work with other people on a project). A big problem can be divided into smaller chunks of functions each doing a separate task.

Functions are really powerful creatures. So i noticed the way you called the name_age function was similar to how we print. Is print also a function?

Very nice question friend! You are picking up really fast. We might land on Mars soon enough. Until now I have showed you what we call User-Defined functions.
There is another type called Built-in functions.

In this article, we look at:
-User-Defined functions
-Built-in functions

Another type found in modules will be covered later in another piece

1. User-Defined Functions

The Code Example 2 shown above is an example of a user defined function.
These are functions that exist within our code and are defined by the programmer. In actual sense, we can call them custom made functions.

Uhmm, I see we made that name_age function by ourselves. Tell me about the other type...was it built-in?

2. Built-In Functions

Having learnt about user-defined functions, Its time we also get ourselves accustomed to built-in functions.
So these functions, are an integral part of the python programming language. They exist within python itself and are always available to use by any python programmer like you.
Actually you do not require any effort to use them, just call them... see here:

Code Example 4

# the print function is a built-in function
print('Hello Friend')
print('Hope you are enjoying python')
print('Please stick around till the end')
Enter fullscreen mode Exit fullscreen mode

*Feel free to check out other types of built-in Python functions Built-in Python Functions
*

Thanks a ton!! I will check them out after here.

That would really be great. So until now we have discussed about what functions are and their different types, But you might ask...
How do we define functions? Is it obvious? Let me not take chances here, remember, we are soon reaching mars ...

Defining Functions

The syntax for defining a function is as:

def function_name(parameters):
    """ A doc string defining the purpose 
        of the function
    """
    `statements` 
    # Comments describing what certain code is meant to achieve
    `statements`

    return `some value`
Enter fullscreen mode Exit fullscreen mode

Key takeaways

def - This keyword indicates the start of a function definition
function_name - This is the name of the function
parameters - These are optional, but are used if you want the function to use certain data to carry out a given task
doc string - Optional, but used to describe purpose of function.
comments - Simple statements to illustrate purpose of certain lines of code.
statements - Remember from our definition of functions
return - Optional, but used if you want to output a value.

This has been a smooth journey to Mars. A recap of what I learned is:

  • I now know what a function is.
  • I know the different types of functions.
  • I know how to call and use the different types of functions.
  • I know how to create my own functions.
  • I have access to other types of built-in functions.

Wow!! Such powerful knowledge you have attained today. Indeed you can now help Elon Musk write some functions for his rockets like turbo_charge().

It is a pleasure spending time with you. And I look forward to your company. Feel free to continue the discussion in the section below. I love learning new stuff and would be my pleasure to hear from you.

How was the article? Did you learn something or your mind sparked at something. Please share! Until then, I say goodbye for now.

           See you Again, Pythonista !!!
Enter fullscreen mode Exit fullscreen mode

Business_Card_Kubona

Top comments (3)

Collapse
 
incrementis profile image
Akin C.

Hello kubona Martin Yafesi,

thank you for your article.
I enjoyed reading it.
It has a very entertaining tone in my opinion.
I was very amused by your questions and the way you answered them.
I think there is a typo in there: "I see how that can save my a lot of time...".
It should be "I see how that can save me a lot of time...".

Collapse
 
aatmaj profile image
Aatmaj • Edited

Cool! You all might like to have a look at my Learning Python course series

I have recently covered user-defined functions and recursion.😀

Collapse
 
kubona_my profile image
kubona Martin Yafesi

Wonderful , thanks for sharing. Let me look into it