Skip to main content

Command Palette

Search for a command to run...

How To Define Functions in Python 3

Published
5 min read
How To Define Functions in Python 3
A

I have built products ranging from:

  • Point of sales application
  • Computer-based testing applications
  • Blogs

My career goals aim at combining my technical skills with my passion for adding value to the startup ecosystem.

I want to explore writing and how I can provide value through creating.

What is a function?

A function is simply a chunk or group of lines of code, with a specific name, which can be called upon if needed. A function in any programming language can accept inputs that are called parameters while the function is being created, and arguments when the function is being called upon or used.

Why are functions needed?

Imagine needing to ask for the same input from a user more than 90 times in a program, or needing to send 10mails to a user from the sign-up to onboarding into the product. Would you rather write 10 emails in your program; or write a function that will take in the email body and recipient and call the function when needed? Nobody who values clean code or writes a DRY (Don't Repeat Yourself) code would want to write the same chunk of code 10 times, instead of using a function.

Using a function won't only save you time and stress, but will enable easy comprehension for anybody who will be reading your code in the future. So please, use a function haha.

Python3 functions

To create a function in python you use the def keyword, function name opening and closing parentheses, and a colon. But it doesn't stop there; your intended chunk of code has to go under the definition of function and as an indented chunk of code to show it is a child of that definition of function or that it belongs to that function, else you run into an indentation error.

You can define a function in python3 below:

def say_hello():
    print("Hello Python Developer")

Whenever the above function is called, it basically prints the string "Hello Python Developer". But how do get to call a function so we can get the print statement to happen?

To call a function, we write the function name we used while defining it with an opening and closing parenthesis as shown below.

say_hello()     #    Hello Python Developer

Yeeey we created our first python function and called it to perform a supposed task. But hey, it doesn't end there.

Python functions and parameters

The say_hello function wasn't given inputs to work with. It wasn't created or defined with any parameters, so it can accept corresponding arguments when we call it.

To add a parameter to a python function you specify or include it inside the parenthesis when you are creating the function. Let's see how we can modify the say_hello function below.

def say_hello(name):
    print(f"Hello {name}, pleased to meet you")

From the above example, we can see that the function accepts just one parameter which is printed out along the string in the print function. Let's see how we can call this function.

name = input("What should we call you?")

say_hello(name)

The above function call takes in the name variable as an argument. Simple right, what if you need to add more than one parameter when defining a function; The number of parameters during function definition must be equal to the number of arguments when you call the function else you TypeError

To modify our say_hello function below;

def say_hello(name, age):
    print(f"Hello {user_name}, you are {age}")

Our say_hello function is no longer taking in one function but two. And the python interpreter will expect us to provide two arguments when calling the functions as shown below.

name = input("What should we call you?")
age = input("And how old are you?")

say_hello(name, age)

Python Functions and Default Parameter Value

Since parameters are variables we specify when defining a function, we can specify default values for these parameters. This also helps as a bug fixer or bug checker in the case where we forget to specify a corresponding argument when calling the function or if we do not need to add an argument during the function call.

def say_hello(name = "James", age = 0):
    print(f"Hello {name}, you are  old")

name = input("What should we call you?")
say_hello(name)

We didn't specify an argument for the age parameter, and yet the above program will execute without an error due to the help of the default parameter for age.

Python Functions and Return Values

The best use of a function is to return a value after an operation has happened. The return value can then be used for further operations. For our say_hello function, let's return the name instead of printing it.

def say_hello(name = "James", age = 0):
    return "Hello" + name

Calling the above function will return or give us a result. To see the return value we either enclose the say_hello function in a print function or use it as a value for a variable.

print(say_hello(name))  # prints the value of the return sattement    

value = say_hello(name)   #    stores the value of the function in a variable

Python function and Pass Statement

When writing a program, you might want to create a function but leave it empty or dormant. This will cause an indentation error. To avoid this we use the keyword pass.

def say_hello():
    pass

With the above instance, you can run the code without worry.

Python Arbitrary Arguments(*args)

Arbitrary arguments denoted as *args are used in defining a function when you are not sure of the number of arguments that will be passed into the function call.

Maybe you made a single parameter for just a name during function definition and want to pass in a first name and a surname as an argument. This logic alone will create an error when you call the function.

def say_hello(name):
    print(f"Hello {name}, how are you ")

calling the above function as:

say_hello(first_name, surename)

will throw a NameError.

To mitigate this scenario, we make use of 'args. Which is simply adding an asterisk before the variable name during the function definition.

def say_hello(*name):
    print(f"Hello {name}, you are  old")

So when we call the say_hello function with multiple arguments without running into an error.

say_hello(first_name, surename)

I hope this article was helpful. I will be updating it in time as I grow in my software development journey.

#python3 #functions

More from this blog

U

Udeagbala Anthony

5 posts

I am a python developer who is more interested in building web solutions with python. A team player and an attentive listener. Executing user and client requirements are my core values.