How To Make My Code Shorter With Python Function.

Python function is very important in structuring your code in a program.

When it comes to writing a simple program, you can do it without functions, but when your program becomes long and would need maintenance from time to time, I recommend you design your code into chunks (functions).

Here’s the deal:

When you learn about Python function, you’ll never repeat a code more than once in your program again.

Hence you make your code shorter and elegant to read.

Isn’t that cool?

But you may be wondering:

What Exactly is a Function in Python?

A function is a block of code that is organized in such a way that you can re-use it to perform a particular action in a program.

Python has 68 built-in functions and examples are: print(), len(), max(), min(), sum(), eval(), input(), next(), help() etc.

You now know what a function is in Python.

2 Top Reasons That Will Make You Change The Way You Code – Why You Should Use Function in Your Program Now

Many Python beginners will write long chunks of code to solve a simple problem.

That can make your code boring to read, but making your code shorter is one of the fun things to do with Python believe me.

I will just outline two major reasons that will make you use functions in your program, hence changing the way you code.

  1. Functions make your code shorter and easier to read and hence more than one programmer can work on the same project.
  2. With function, you can quickly debug your program.

Use these 8 Quick Steps to Define a Function in Python.

  1. Begin your block of code with the keyword def
  2. In the same line, type in your function name and include parentheses ()
  3. Any argument is added within the parentheses
  4. At the end of the parentheses include a colon (:)
  5. Press enter
  6. You can describe your function name in quotes (“ “)
  7. Press enter and write your program
  8. When you finish writing your program, include the return keyword
How to define a function in Python

8 quick steps to define a function

Below is a quick video guide on How to define a Function in Python.

I will quickly talk about step 6 as it’s a good habit to give a description of what your function does.

A Cool Way to Describe Your Function Without The Hash(#) Symbol

In Python to describe your code, you use the hash symbol(#). Python ignores comment as it is for the humans to read.

To describe your function in Python, you use a docstring which is the sixth step in defining a function.

To demonstrate this, I will write a function to calculate a quadratic mathematical equation.

I will also show you how to access a docstring of a function.

The program is saved as quadratic_Calculator.py( for those that will download the source code of this Python programming tutorial).

 

In the last line of code in the code snippet above, the docstring of the function name (quad_calculate) is accessed by quad_calculate.__doc__

NOTE:

__doc__ is a function attribute and it has two leading and two trailing underscores.

This block of code to solve a quadratic equation is executed when the function(quad_calculate) is called. You will learn how to call a Python user defined function later.

But first:

Good Practices When Defining a Function in Python

When defining a function in Python, never do the following:

Starting your function name with something that is not a letter except an underscore

Your function name can begin with an underscore(_) or a letter(either upper case or lower case) first then after that you can include digits.

The only acceptable symbol in your Python function name is an underscore(_). If you don’t follow this rule, Python will raise an error(SyntaxError).

Including Spacing in Your Function Name

You can’t include a space in your function name rather Python accepts an underscore(_).

Using Python’s Keywords As Your Function Name

In Python, keywords are known as reserved words and they cannot be used as a function name.

Here is a list of Python keywords:

  • False
  • None
  • True
  • and
  • as
  • assert
  • break
  • class
  • continue
  • def
  • del
  • elif
  • else
  • except
  • finally
  • for
  • from
  • global
  • if
  • import
  • in
  • is
  • lambda
  • nonlocal
  • not
  • or
  • pass
  • raise
  • return
  • try
  • while
  • with
  • yield

Want to know the best part?

You don’t need to memorize these Python keywords.

Here is a short video tutorial on how to get all the keywords in Python 3.

Just run the following code snippet in Python interactive shell to get all the keywords in Python 3.

To determine if your function name is a keyword or not:

Type the following code snippet in Python’s interactive shell.

Observe:

A True value is returned for the word “raise” because it is a keyword in Python.

A False value is returned for the word “printstr” because it is not a keyword in Python. Hence we can use it for a function name

Example of a Function in Python.

Now:

Let us write a Hello World program using function by following the 8 quick steps to define a function.

Type the following code snippet into Python’s interactive shell.

Note: The program will still run fine without the return statement. I will explain the return statement later.

Let us see how we can add arguments to our function.

Project 1:

Write a function to print a string.

Type the following code snippet into Python’s interactive shell.

This program takes one argument which is a string and prints it.

Let us do something that’s a bit tougher.

How to call a function in Python (3 Simple Hacks You Need to Know)

Here is something funny about function( a joke)

Funny Python joke on function.

Funny Python joke on function.

Alright, let’s be serious now.

You have learned how to define a function by giving it a name and including argument(s) within the parentheses.

A function can be called directly or from another function.

The following code snippet illustrates a function calling another function.

The program is saved as square_root.py( for those that will download the source code of this Python programming tutorial).

The above program is to find the square root of a number. We have two functions(main and square_root). The main function calls the square_root function.

Here are the arguments you can use to call a function.

  1. Required argument
  2. Keyword argument
  3. Default argument

Required argument

In required argument, the arguments are called according to the position as defined.

To understand you have to type the following code snippet into Python interactive shell.

Did you observe anything?

The required arguments are name, dept and level and when you call the function student_info you have to provide the arguments in the order of the name of the student, the dept and the level.

Keyword argument

In keyword argument, the order in which you put the arguments to call the function does not matter. All you have to do is assign the value to the argument when you call the function.

You will better understand this if you type the following code snippet into Python interactive shell.

In the above code snippet, Chemical Engineering is assigned to dept, 400 is assigned to level and Godson is assigned to name.

I hope you observed that the order of the argument in the function definition is different in the function call.

Default argument

In default argument, a default value is assigned to an argument while defining the function.

Let say you what to write a function to deduct the tax of your income and return your net income.

Your tax is 10% of your income.

Type the following code snippet into Python’s interactive shell.

Python Function with While loop

Let us try Python function with a condition statement(while loop) and write a cool program.

Project 2

We will write a function to print out a range of number from lower bound to upper bound with a step the user provides.

Type the following code snippet into Python’s interactive shell.

 

Our function(printRange) accepts three arguments(lower, upper and step).

The while loop runs only when the lower bound is less than or equal to the upper bound.

In Python <= means less than or equal to. It is a relational operator.

end=”,” ensures we print our range in one line with the numbers separated by commas(,)

When the function is executed the lower bound is incremented by the step size the user provided.

Note: I didn’t use the keyword return.  I will explain why I didn’t add it later.

Global and Local Variable

A local variable is a variable that can only be accessed by the function that contains the variable while a global variable is a variable that can be accessed by all the functions in your program.

Global Variable

I will illustrate a global variable in the following code snippet.

The program is saved as stats.py( for those that will download the source code of this Python programming tutorial).

In this program  stats.py the global variable is data and it can be used by all the functions(mean_value, mode_value, and mode_value ) in the program.

I hope you observed that the global variable(data) is written outside all the functions in the program.

Local Variable

I will illustrate a local variable in the following code snippet.

The name of this program is local_variable.py

In the program above, x, y are local variables and they can only be accessed by the functions square_root and square respectively.

Variable Argument

You may need to write a program in which the number of argument in your function is unknown like a function to calculate the average of some numbers.

Observe the following code snippet, if possible type and run them to understand variable argument

Code Snippet 1

Code Snippet 2

 

 

When you run code snippet 1 and 2 you will get an error in snippet 2.

This is because:

mean_value() takes 2 positional arguments but 4 were given.

To prevent error in your program(code_snippet1.py and code_snippet2.py) , do the following in the next code snippet.

An asterisk (*) is placed before the variable name(num)  that will hold the values of all variable arguments.

Note:

If you want a function to have an argument that accepts an arbitrary number of arguments and a keyword argument, the argument that accepts an arbitrary number of argument must come last.

Below is an example.

Sometimes you would love to write a function to accept a name-value pair. To do this we attach double asterisks (**) to the argument.

The above program is boring to me. Let’s modify our program to accept a name-value pair.

Save the program above as grade.py and run.

The **grade creates an empty dictionary with the variable name grade and it packs the name-value pair it receives when you call the function.

student_database={} – This line of code creates an empty dictionary with the variable name student_database

student_database[“Student_name”]=name – This line of code assigns the key(Student_name) to the value(name)

The for loop is use to add each key(course) and value(scores) pair in the dictionary(grade) to the dictionary( student_database)

The Return Statement

The return statement returns a value of a function.

Type the following code snippet into Python’s interactive shell

From the above code snippet, it can be observed that the variable (result) stores the cube of the argument(num) and it is returned by the return statement.

Here’s the best part:

Python allows you to return more than one variable from a function.

Run the following code snippet in Python’s interactive shell.

By default, a tuple is returned.

If you want a list, replace return num,result with return [num,result]

How  To Assign A Function To A Variable

I am Godson by name but my friends call me “lappy”. The name(Godson) and nickname(lappy) refer to one entity which is me.

If you call me either Godson or lappy, I will answer you.

That is the same thing in function.

Observe the following code snippet:

You can compare the function name( hello_world) to my name(Godson) and the variable  (my_first_program) can also be compared to my nickname(lappy).

Both hello_world and my_first_program are now the same entity. All the grammar I’ve been using is to explain to you that function can be aliases to a variable. I’ve explained aliasing effect on aliasing effect on list before.

 

How To Create Anonymous Functions with Lambda

You may be wondering:

What is an anonymous function?

What is lambda and how can I use it to make my code shorter?

Well, an anonymous function is the function you don’t create with the 8 steps I outlined from the beginning. That is, an anonymous function is a function created without the def keyword.

Therefore to create an anonymous function you use lambda.

lambda is a function that does not have a name, it can have more than one argument but it only has one expression.

Fun fact:

Lambda is derived from the Greek letter λ which is used to indicate an anonymous function in mathematics.

The following code snippet explains lambda and how to use them to make your code shorter.

 

Here’s a video tutorial on How to use lambda to write a program in Python3.

Before this Python tutorial on function comes to an end, let me teach you some Python built-in function which are:

  • filter()
  • map()
  • reduce()

filter()

Let’s be practical, when you pour water that has particles into a filter, the water passes through the filter but the particles remain in the filter.

A filter function does the work of a filter. A filter() function returns a sequence for which a function is true, I.e. the items you don’t want are discarded.

The syntax of the filter() function is:

list(filter(Boolean_function, sequence))

What I mean by a Boolean_function is a user-define function that returns a True or False value

Observe the following code snippet.

In the above program, the function even is created and it is a Boolean function because it returns a True or False statement.

Here is a proof in the code snippet below.

range(2,21) is a sequence of numbers from 2-20.  list(filter(even,range(2,21))) returns a list of even numbers from 2-20.

Here’s a video tutorial on how to use filter() in Python 3.

Lambda function With Filter

Here’s a program to illustrate how you can use an anonymous function(lambda) with filter.

Here’s a video tutorial on How to use lambda with filter() and map() to write a program in Python3.

map()

map is used in Python when you want to apply a function to each value in a sequence (string, list and dictionary) and return another sequence.

The syntax of the map() function is:

list(map(user_define_function, sequence))

In project 1 of my Python list tutorial, I wrote a program to replace each integer in this list [289,256,225,196,169,144] with its square root.

Let me now show you how you can use function with mapping.

How to Make a Module with Python Function

Programmers are really good at collaborating with other programmers and one good way to do that is to save a function as a module and share it with other programmers.

A module is a great way to re-use your code in different programs making your code shorter. You can also share it with other programmers.

A module is a file that contains the blocks of code you want to import in another program and it ends with a file extension .py

Import is a keyword in Python use to make available the blocks of code in a module to your current program.

Open a new file editor window and type the following code snippet. Save it as mathstats.py

Open a new file editor window and type the following code snippet. Save it as program.py and run.

To make each function in a module available in your current program you use the syntax below.

module_name.function_name()   

Note:

program.py and mathstats.py has to be saved in the same directory for you to import mathstats in program.py

 

Y0u have come to the end of this tutorial.

Please don’t forget to:

Please if you have any questions or contributions, please leave it in the comment section.

Thanks for reading. If you enjoyed this tutorial, hit the share button. It would mean a lot to me and it helps other people to see the tutorial.

 

About the author

Rapture Godson

I am Godson; the brain behind Cool Python Codes. On this blog, I will make Python much fun and very practical. My up-to-date tutorials are based on my studies and they are very easy for you to understand.

16 Comments

Leave a Comment