Functions in Python

Omar Raheem
5 min readMay 3, 2019

--

Don’t be scared they’re here to help us!

When programing with Python, you’ll have calculations and logical operations that you’ll need to repeat over and over again. The best way to do this is to take that operation and put it into a function. From the outset, making functions can be intimidating but don’t be afraid, they are here to help!

In this installment we will build some very basic functions that do some very cool calculations.

Structure of a function

def function(arguments):
pass
var = a + b
return result

Functions are DEFined with def. This is how you begin your functions in Python.

Followed by the name of the function. This is just a demo so I named it function.

Next inside parentheses are the arguments. You can put more than one arguments in a function but since you’re just getting your feet wet I am just going to use one.

Next type : and press return. This will automatically indent. Functions in Python are structured with indentations. This is also called a new ‘code block’.

For this function I will put the word pass. Pass is how you tell Python skip this line and do nothing.

Next, I will name a variable and define it. Python can do very basic calculations with its default program so a simple command such as: a + b is well within its abilities. In this demo I am calling var equal to a plus b.

Next line is return and the result. If the return statement is not specified in the function definition, the function will return None. Once it reaches a return statement, the function will terminate.

The above function doesn’t do anything. If you were to write it in your editor it would give you an error for your trouble. Let’s build a function that does something.

Let’s name this function:

def ping():
return "Ping!"

And you call the function by typing the name of the function followed by parentheses.

In [1]: ping()Out [2]: 'Ping!'

Because we did not assign a variable Python simply printed it to the terminal. This is an example of a user made function.

Ready to take it up a notch? Let’s make for loop but before I do I want to introduce 2 things: built-in functions and comments.

Comments are denoted with hash tags and basically makes that line invisible to the Python calculation. Comments are a huge part of being a good programmer. Commenting code allows you to keep track of what your code is doing as well as makes your code more readable to your fellow programmers. It’s just good practice. Get in the habit of writing comments as you write your code.

Built-in functions are functions already inside the basic Python framework that perform calculations for you without you having to build functions from the ground up. Here’s a link to some built-in functions(here). In this example I’ll use the built-in function range(). Returns a sequence of numbers, starting from 0 and increments by 1. There’s many use cases. Often you will want to use this when you want to perform an action X number of times. Now you’re probably asking: Omar, can you put a function inside a function?

Watch:

#One at a time, assign each value of the range to i and multiply by    n 
def multiply_me(n):
for i in range(50):
# multiply i by 5 and store the product in a new variable, x # create a new variable, x,
x = i * n
# print the value of x
# after the entire sequence processes,
print(x)
else:
# print this
print('All Done!')

Let’s call the function.

In [1]: multiply_me(10)Out [2]: 
0
10
20
30
40
50
60
70
80
90
100
110
120
130
140
150
160
170
180
190
200
210
220
230
240
250
260
270
280
290
300
310
320
330
340
350
360
370
380
390
400
410
420
430
440
450
460
470
480
490
All Done!

Wow! It did what I told it to. It multiplied by 10, 50 times. Pro-tip: with range() the first number is 0 unless you specify otherwise. That is why the first number is 0 followed by 10, 20 , 30 …. 490.

That was cool but let’s make a function that’s a little more powerful. Let’s call in the big guns. Numpy, you’re up.

Numpy is 42–0
import numpy as np

From numpy.org:

NumPy is the fundamental package for scientific computing with Python. It contains among other things:

a powerful N-dimensional array object

sophisticated (broadcasting) functions

tools for integrating C/C++ and Fortran code

useful linear algebra, Fourier transform, and random number capabilities

In this case I’ll need a little bit of algebra. Specifically: mean(). The mean is another build in function but only in the numpy package. Mean finds the average of a set of numbers. So I imported the numpy package and defined it as np.

Next, I’ll use the method append(). The append() method adds an item to the end of the list. List in Python are defined with [ ].

Example:

animal = [‘cat’, ‘dog’, ‘rabbit’]

I will take an empty list [ ], add some numbers to this empty list then find the average, using the mean() function. The function will then print out text with the calculations using f strings. Find out more about f strings here from John D Hazard himself.

Check it out:

#rename function to something more appropriate
def find_mean(n):
x = [] #empty list for results to go into and set as x
for i in range(50):
# multiply i by n and append it into the empty list
x.append(i * n)
#print results using an 'f' string
print(f"The mean is {np.mean(x)}")

Call the function:

[1]: find_mean(10)The mean is 245.0
Nice!

That’s just a small example of what functions can do. I urge you to explore the tools of Python and don’t be afraid to write functions. They are here to help!

More about me and links to my other blogs: https://orah82.github.io/

--

--