From crawling to walking! - Lesson 3
Alright guys, in the last tutorial I showed you how to write your first function. By now you know what arguments are, how to define functions, and how to compile and run a function. If you need a quick refresher, check out Lesson 2.
In this tutorial, we're going to take it one step further and learn about while loops, and Python lists to write a bit more complex function.
To start off, what are while loops?
While loops, in most programming languages, are control statements that allow you to repeat a block of code as long as the while statement is true.
Okay, you get that, but what does it actually look like?
#here is an example of a while loop (in Python, we use hashtags (#) to denote comments. Comments are lines of text that the Python interpreter knows to ignore because they start with a hashtag. Always use comments in your code because it helps other people know what in the world you're doing, and it helps you to remember your work as well!)
toprint = "Hello, world!"
while toprint == "Hello, world!":
So basically, what this chunk of code in bold is doing is printing out toprint, which is a variable that stores the string "Hello, world!" as long as toprint is actually storing "Hello, world!". Now, if we were to have made toprint store another string, like just "Hello" then our while loop would have ignored the print statement since toprint wouldn't be equal to "Hello, world!". Get it?
Why don't we try something a bit more complicated?
Let's set out goal for this lesson to be to write a function that takes as input (arguments), a list of numbers, and returns the average of all the numbers in that list.
You're probably thinking, "Wait a minute, Sri never told us squat about lists!!" You're right. I didn't. But, we're gonna learn about them, now!
As the name might've suggested, Python lists are what they seem...lists! They look like this:
Lists are denoted by the square brackets and values are comma-separated. Just like in the "real world" Python lists can hold just about anything: numbers, letters, words, sentences, other lists!
So, now that we know what lists are, let's learn a bit more about how to use them. Let's say we have a list of numbers from 1 to 10. Just like any other value (such as our "Hello, world!" string, or our numbers in the last function) we're gonna have to assign our list to a variable. In other words, we have to name our list so we can use it! To keep things simple, let's call our list "mylist."
mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Note that the values in our list are integers and not string characters, this is because we know that our function wants to do mathematical things with the numbers. For that we need integer values, since adding strings does something completely different that we'll cover in the next lesson!
Now, how do we access an element in our list? Well, a weird thing about computer scientists is that we start counting at 0. So everything in mylist is numbered from 0 to 9 instead of 1 to 10 like you're used to.
So, to access the first element of the list, we type:
This will return 1, as you can see in the screenshot below. Why don't you test out how to access the other values in the shell?
Done testing? Okay. Another thing to know about lists is that they are mutable. This means that lists can be modified in certain ways that some other data sequences, like strings, can't be.
Because lists are mutable, we can do things to them like this:
Now type mylist in your shell and hit enter. The shell should reply to you like this:
[99, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Crazy, huh? But not really. You did tell mylist that its first element should now be 99 when you set mylist[0] to 99. So, you know how mylist is a variable for the entire list. Think of mylist[0] as a variable for the first element in the list, mylist[1] as a variable for the second element of the list, and so on. If you were to set another variable equal to a number, for instance like this:
Then you could also access the second element of mylist, or the element of mylist at the index (which is basically a fancy way to say place/placeholder) 1 in the list.
So, mylist[i] would return 2 since that's the element at index 1 in mylist.
I know this was a lot to process, so take a second to think about it and to test out how list indices and accessing elements in lists works in the shell. You can make another list with different elements if you'd like, too!
For more info on lists, and other examples check out this guide.
Now that we know how to write a while loop, and how to use lists, let's go ahead and work on our function. As we learned in the last lesson, it's always good to plan out how your function should work using pseudocode. Let's write some up right now!
1. Define the function with one argument (alist).
2. Check the length of the list (don't worry, we'll talk about how to do that when we start writing the actual function!).
3. Write a while loop that goes through the elements of the list.
4. Get each element from the list and add it to the sum of the previous elements (which we'll store in a variable called sumsofar).
5. After you've gone through all the elements, divide the sum of all the elements by the number of elements in the list.
So, let's define our function. We're going to call it, averageList. Now, averageList should take one argument (alist) so our function should look a little something like this:
Great. Now, let's check the length of our list. But how do we do that? Well, lucky for us, Python has a build in library of functions that we can just use as we like! One of those functions is len(list), which checks the length of a list and returns the integer value.
Let's put what we have so far together:
length = len(alist) #we are adding a comment here to explain what is happening in this line. We're getting the length of the list we passed in as input and assigning it to a variable to use later.
Next, we want to write a while loop to go through every element of the list. So, we learned that computer scientists start counting at 0 right? So, let's set a variable equal to 0 that we can change as we like as we go through elements of the list. We want to set it to 0 since we need to access the first element of the list, which is at index 0 (see above).
What we're going to do with our variable (x) is add 1 to it every time we look at an element in the list and add it to our sum. This ensures that we don't go back to the indices we looked at already. And we keep adding 1 to x as long as there are more elements in the list, or in other words, as long as x is less than the length of the list. But do we have to use the len function again to get the length of the list? Nope. Remember, we saved the length in a variable called length, so that's what we'll use.
So, our while loop should look a little like this:
Time to put our code together again:
while x < length: #while x < the length of our list (it's just algebra mixed with words!)
Okay, so now what? Well, we have to figure out what exactly it is we do where we have the comment "do something." Let's check our pseudocode.
We need to access each element in the list using alist[ ] ... but how do we get EVERY element? We use x! That's why we set it to 0. So, the first time around in our loop, x = 0. We call alist[x] and we get the first element in the list. Then, we add 1 to x so the next time we're in the loop, x = 1. When we call alist[x], we'll get the second element in the list and so on!
Now, what do we do with these values that we get? We create a variable called sumsofar (check psuedocode) and add the value to sumsofar like this:
sumsofar = 0 #since we don't have a sum yet
x = 0 #since we start at the first index
But there's something wrong with the code above. Can you guess what it is? Each time we go through the loop, we do add sumsofar and the element at x in alist, but this value isn't being saved because we're not assigning it to anything! What do we assign it to? sumsofar! Just like the x = x + 1 line, which tells us that the new value of x is the old value of x, plus one, we need a line that tells us what the new value of sumsofar is.
sumsofar = sumsofar + alist[x]
Adding this to our code will save our progress!
At this point, our loop should be working correctly. It should be starting at the first index of the list, getting the value, adding it to the sumsofar variable, and moving on to the next index of the list. All we have left is to divide the sum by the number of elements in the list, which we can do like this:
sumsofar/length #our sumsofar variable has stored the sum of all the elements in the list, and the length variable has stored the length of the list.
All we need to do is assign the value we get from this calculation to another variable, which we'll call average. Simple.
average = sumsofar/length
Then, we just return the average.
To put it all together, check out this screencap that I posted.
You'll notice that instead of returning the correct average (which is 5.5) the function returns 5. That's because we're doing integer division. We are dividing an integer by an integer, so Python thinks we want an integer as the answer. In Python, decimals are treated differently than regular integer numbers. If we want our function to return the decimal value, or float value as Python calls it, then we have to make one of our values a float. Let's try making the sumsofar a float. We do this by typing:
It works just like the len function, where you put the list you want to know the length of in between the brackets. Here, you're putting the integer value that you want to turn into a float.
So our calculation line (average = sumsofar/length) will look like this:
average = float(sumsofar)/length
And now, Python should be telling you that the average of the list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] is 5.5, which it is indeed.
I know that this tutorial was a bit longer than the others, but that's just because we covered like three times the material in this one than we did in the other ones. To recap, in this tutorial we learned about:
3. built in Python functions (len, float)
In the next tutorial, we'll work with strings and tons of other cool Python things! Here's to you and your awesome coding abilities! Let me know if you have any questions or comments!