Intro Python 1: Functions & String Formatting

This is our Intro Python 1: Functions & String Formatting tutorial that will introduce functions in python and show one way to format strings as output. A basic understanding of functions and python is going to be important in order to follow some of the more involved code we write later on.

Hello, World

First, lets get a formality out of the way. As is tradition, the first thing we’re going to do in Python is say “hello” to the world. Don’t ask me why, but it’s a requirement whenever one is learning a new language.

Let’s hop right into Spyder so we can get this prerequisite taken care of. See this post for instructions on installing Anaconda if you haven’t already. We won’t mess around with any popup boxes, just type the following line of code in the IPython console ( should be in the lower right-hand corner) and hit enter:

print(“hello world”)

 

Writing an Average Function

The first challenge of Functions & String formatting is going to be to understand what exactly a function is. Function’s tackle specific tasks. Sometimes they are built in to a programming language, or its packages – and usually you can define and write your own. An example would be finding the mean for a set of data. Whether it’s called “average” or “mean”, this function will be included in many languages. However, we can also write our own quite simply.

Here’s a quick example of how we would write a custom function to find the average, lines with a # hashtag at the beginning are read by python as comments:

The bulk of the code written above is a brief walk-through of what I wrote. In reality, we only wrote three lines of code. One line creating a list of numbers called “list”, one line creating our function called “average” and assigning it one input, and one line where we used our “list” as the input for our function “average”.

Take a closer look at how we checked our work, do you notice anything redundant?

Compare these two lines of code:

print(sum(list))

And:

10/len(list)

We didn’t need to utilize “print” to display the answer of sum(list), but we also weren’t penalized for it. This is a tiny example of why Python is a joy to code in, it’s forgiving of small oversights in addition to being incredibly flexible and syntatically simple. Still, keeping our code clean and simple is always best, so we should go ahead and remove “print” from the first part of our check.

You try. Can you find the sum of our list yourself?

What about truncating our check so that it’s all in one line? Give it a shot.

On a final note, naming our list as “list” is bad form. I only did it the first time a Python list was introduced to help you remember that it is, in fact, a list. Going forward one should not create a list called “list” or a function called “function”, etc.

Adding a description – string formatting

The code we wrote will return the average of our list of numbers, but what if we want to add a text description? There’s a handy way to do this that I use frequently so that I always know exactly what the output of a script corresponds to. It’s called string formatting. A string is just a collection of text.

What we’ll do is write a print function, placing some text inside of it as our description. Then we’re going to add a pair of {} at the end of our text. Today we’re just going to add one, but we could add as many as we want. Example:

planet = “Earth”

print(“Hello {}”.format(planet)) 

If you run these two lines of code the output will be “Hello Earth”.

Why? In line 1 we defined our planet as the text “Earth”. In line 2 we utilize a string method called “format”. For each set of {} we place in our string, the format method will replace it with an argument we give it. In this case we gave it the argument planet, which we had defined as earth.

We can incorporate this utility in our already existing code in order to get output that also provides a description for us. While we’re at it, let’s go ahead and migrate out of the IPython Console.

Go ahead and create a new file in Spyder and save it with any name you like. In the new file let’s type out some code that’s a little cleaner than it appears when we operate entirely out of a shell or console:

You can run each line of this code one by one using F-9 on windows, or run the entire file by using F-5.

 

With our new code we should get something that looks like:

“The average of our list of numbers is: 3.333333333335”

 

String formatting and defining functions both add a lot of flexibility. Consider if instead of a random list of numbers, we were finding the average return for a number of different stocks. We would create a list of returns for each stock and save them with the corresponding name. After that, instead of writing a print() call for each of our stocks, we can combine them all. Example:

I can understand how this might not seem particularly useful right away, but trust me it is. Especially when you’re developing something with numerous intermediate calculations and you need to verify that each is correct, the technique above helps keep the output and error handling organized while you’re still building it.

 

 

 

Your email address will not be published. Required fields are marked *