Get Your Feet Wet with Python

Suppose we want to know the square of a bunch of numbers plus 2. The simplest way to do this in Python would be to print each calculation individually:

print((1 * 1) + 2)
print((2 * 2) + 2)
print((3 * 3) + 2)
...

This is all well and good, but if we decide later that we want the squares plus 3 instead, we’ll have to change that value on every line. That’s a huge headache! Functions to the rescue. We can write a function square_plus_n that takes in a number to square and optionally takes in a number n to add to the square result:

def square_plus_n(number_to_square, n=2):
return (number_to_square * number_to_square) + n
print(square_plus_n(1))
print(square_plus_n(2))
print(square_plus_n(3))
...

Now if we want to change our default added number, we can just change n=2 to n=(some number) in the function definition. There are a couple of new pieces to talk about in our function. Let’s review.

“def” is a keyword in Python, short for “define,” that means “here is a function definition.” Then comes the name of the function, square_plus_n.

Next are our arguments. square_plus_n takes an argument called number_to_square and a second argument n. Since n has a default value specified, n is optional. If unspecified when the function is called, n will default to whatever default you choose.

The colon means that the following indented lines are the body of the function. Our function body here is a single line, which uses the “return” keyword to return the result of our function to wherever it was called. The result that’s being returned is our calculation of the square plus a number.

Now that we have our function defined, we can call it multiple times. Notice that we’re only supplying one argument each time, meaning that the second argument, n, is defaulting to 2. We could specify a different default:

print(square_plus_n(3, n=5))

This would result in a calculation of (3 * 3) + 5 = 14.