Defining Functions in Python
Defining functions is a great way to demonstrate your coding ability. It shows you know how to create something that doesn't need to be changed every time to run. I mean that you do not have to change numbers or variables to get the outcome you desire. This could be charting graphs without changing the title or axes, but you programmed the graph to update the title and axes accordingly. Another example is adding all the numbers together up to a certain number. In this post, I’ll show you how to do the latter.
If I wanted to add all the numbers from zero to four, most people wouldn't need python or a calculator to do that. However, what if I wanted to add every number from zero to three thousand? It is possible to do it by hand or by the calculator, but it would take quite a long time. Python is faster, and when we create a function, we can finish this task much quicker.
To start, let’s think about what tools python has built-in that can help us. I know sum(), and range() will be able to help us.
Before I declare my function, I like to create lines of code that will work when not in a function. I want to add all the numbers from zero to ten first.
Remember, the range function includes the first argument and exempts the second argument. So, eleven is not included, but ten is.
What if we have a negative number? We can still add those too.
Negative ten is smaller than zero, so we place that number as our first argument and zero as the second argument. We get a negative 55 as a result.
Now that I have a working code, it’s time to make a function out of it.
Start by defining the function.
My function, numbers, will take an argument ‘ i ’. This ‘ i ‘ is generic for an input that will be in the function.
We know the input can be negative or positive, so we need to account for that by using if, else statements.
If the input is greater than zero, we want the function to run a certain way. We know the range function excludes the second argument, so we want to add one to our number in the range. Without a return statement, the function will not produce a result.
If the input is smaller than zero, we want the function to run a different way. Below, ‘ i ‘ is now the first argument because it is smaller than zero. It is okay to exclude zero because zero does not change the sum of a product.
The resulting function is written as so:
To test it out, let’s give it a number we can do in our heads.
The function works for 1 + 2, so what about 10 like in the previous example?
Let’s try a tiny number.