Showing posts with label tuples. Show all posts
Showing posts with label tuples. Show all posts

Sunday, February 9, 2014

Compute Loops

Now that we know how a few collection/sequence style objects work we can dive into some more powerful ways to utilize them through looping.

Looping is a relatively simple concept. It provides a means of telling the program to run the same bit of code over and over a number of times. This is useful because it prevents the programmer from having to rewrite the same code over and over. There a few different types of loops. The first one we are going to look at is the “while” loop.

The ‘while’ loop

The while loop is pretty simple. It tells the computer that while a certain condition is true, keep doing a certain type of code. The classic example of the while loop involves printing a series of numbers to the console using three lines of code. It looks like this:

a = 0
while a < 10:
    print a
    a = a + 1

image

Notice, at the end of the “while” line I added a colon “:”. The colon lets the interpreter know that the indented code on the following lines is what should be run until the “while” condition is met. In this case, as you can probably guess, we are instructing the computer to to print the variable a as long as it has a value that is less than ten. One thing that can be annoying about Python is the indentation. Your indentations can be spaces or tabs but not both. Meaning if your first indentation is done with spaces, all of the following indentations must also be spaces. If you use tabs, then you have to continue using tabs. The number of spaces doesn’t matter, so long as it is consistent. The general rule of thumb is 4 spaces for each indentation. In Notepad++ there is an option in the “Settings > Preferences” dialog for “tab settings” you can set it to replace your tabs with spaces. I would recommend using that option if you use Notepad++.

image

While loops can be very useful, but there is also a danger in using them. Imagine what might happen if we didn’t include the last line in the code above, a = a + 1. Without that line, a would always be equal to zero, meaning that the “while” condition would never be met and the computer would continue printing a indefinitely until the end of time. (If this happens press “ctrl + c” to terminate your program.) This is known as an “infinite loop” and it is to be avoided. As a safety measure, when writing a while loop, it is a good idea to put the the code in that will complete the loop first and then insert the code that needs to run during the loop above it. There have been many times that I have written while loops that have some complicated code to run and by the time I finished writing the code I forgot to add the line that would fulfill the while condition.

Here is an example of a while loop that prints all of the numbers in the fibonacci sequence up to 1000.

a = 0
b = 1
while b < 1000:
    print b
    x = a
    a = b
    b = x + b

image

Try running the code again, but add a comma after the “print b” line.

image

The ‘for’ loop

The ‘for’ loop is a wonderful little tool for accessing all of the elements in a sequence/collection style object. That means that for loops can be used with strings, lists, and tuples (as well as a few other objects). It works like this:

for <variable> in <object>:
    do something

Let’s learn through practice. Make a string object called myString and set it equal to some word. Then use a for loop to print out each letter individually like so:

for letter in myString:
    print letter

image

The ‘letter’ in the above example doesn’t have to be ‘letter’ it could be any variable name. The word that comes after ‘for’ is a variable name. The for loop then loops through the sequence object and assigns each item in the object to the variable name specified. This looping is known as “iterating” in programmer jargon and so the act of looping is known as “iteration”. So, if you are describing the above program you can say that “I am iterating through my string and printing out each character.” In the above example we are telling the interpreter: for each character in myString, assign the character to a variable called letter, then do whatever code is below.

So in my example myString = “cow” and when I ran the code it printed the letters c o w. I could also have told it to print myString and it would have printed “cow” three times. Why? Because the for loop performs some code for each item in the object. “cow” has three characters so for each character it will run the code “print myString”.

image

So you see, you don’t only have to use for loops to do things with the items in a sequence or collection object. For instance, if there wasn’t a len() function available to us, how might we write one using a for loop? Observe:

length = 0
for x in myString:
    length = length + 1

print length

image

Here we ignore the value of x, we simply add 1 to the value of our length integer object each time we encounter an item in the myString object. Notice that when I added the print length line I didn’t add any indentation. This lets the interpreter know that it shouldn’t run the print line until it is finished with the for loop. So the interpreter knows that the any code that is indented under the for loop should be run in the loop, when it finds a line that is not indented it will not run it until the for loop is complete. See what happens when I don’t indent the print statement.

image

Loops can also be used with lists and tuples in the same way that they are used above. For example:

myList = [‘camera’, ‘steve’, 4, ‘cheesesteak’]
myTuple = (‘flippy’, 912, 0.0074, myList, 99, 42, ‘bilbo’)
for item in myTuple:
    print type(item)

image

That’s it for loops for now. Next post we will discuss the if / else statement and boolean objects and I’ll probably throw in some comparison operators…anyway, more on that next time.

Saturday, February 1, 2014

He’s makin’ a list, he’s checkin’ it recursively

We’ve dealt with strings, we’ve received the t-shirt. Now it’s time to look at another collection style object, the “list”. Python lists are wonderful little creatures that allow us to organize and manipulate data quickly and easily. We have already encountered some lists. When we ran the sorted() function on our string object in the mad libs post, the object that was returned was a list. If you recall, a “string” is a collection of characters. A list, on the other hand is a collection of anything. You can create lists of numbers, lists of strings, lists of custom objects, even lists of lists. You can also make lists of multiple types of objects. So you could have a list with integers, floating point numbers, and strings, etc. Lists also come with lots of built in methods that make using them fast and easy. 

Let’s begin by creating a list. List creation is similar to string creation, except that instead of enclosing your list items in quotes, you use the square brackets ‘[‘ and ‘]’ to denote the start and end of your list. Each item you want to put into your list should be separated by commas. Open your interpreter and type:
myList = [‘a’, ‘b’, ‘c’, ‘dog’]
Lists are easy to spot because they will always be enclosed in square brackets. Accessing items in lists uses the same indexing system that strings use. The first item has an index of 0, the second item’s index is 1, etc. 

Note that if you check the type of myList using the type() function, it will return 'list'. However, if you check the type of myList[<index>] it will return the type of the item in the list, in our case, a 'string'. This is because the list object is acting as a container for the objects inside. So the list is and object, and the items in the list are also objects. Each object in the list will retain its original properties. Scary and a little confusing, but powerful. See below:


One of the cool things about lists is we can change them without needing to redefine them. For instance, if we create a list and then later on need to add or remove an item we can do that without having to create a new list. There are several ways to add and remove items from lists.

Common methods for adding or removing objects to/from lists
Method Description
myList.append(<item>)
The append() method will add an item on to the end of a list. This is a useful function when starting with a blank list and adding items to it.
 
myList.insert(<index>, <item>) The insert() method allows you to put an item into your list in whatever location you choose.
myList.remove(<item>)
The remove() method will remove the specified item from the list. If there is more than one occurrence of the item in your list, the remove() method will remove the first item, and leave the rest.
myList.pop()
myList.pop(<index>)
The pop() method will remove the the last item in your list. You can also give an index number to the pop method and it will remove the item at the index number. If no index is given then it will remove the last item in the list.

Like I said, there are lots of cool ways to access and manipulate lists; LOTS of ways. I’m going to cover some of the more common methods in this post, and probably mention some of the more obscure methods in later posts. Now that we know how to add and remove items, let’s look at some methods that allow us to play with the data in our lists. For the following examples I am going to define a new object.
testList = [‘hogwarts’, ‘salmon’, ‘alpaca’, 4, ‘cheese’, 2, ‘superman’, ‘cheese’]
Common methods for adding or removing objects to/from lists
Method Description
testList.reverse() The reverse() method reverses the order of the list.
testList.count(<item>) The count() method counts the number of times the specified <item> occurs in the list.
testList.sort() The sort() method orders the items in the list, numerically and/or alphabetically.
testList.index(<item>)
The index() method returns the index number for the specified <item>. If there is more than one occurrence of the <item>, then index() will return the index number of the first occurrence.

 

Finally, there are a few more built in python functions that can be used with lists, some of them you’ve seen before when dealing with strings. (I told you there was lots of stuff you can do with them.)
Built-in Python Functions that can be used with lists
Function Description
len(<list>) This function works just like it did with strings. The value returned will be an integer that specifies the number of items in the list.
max(<list>)
The max() function will return the item in the list with the maximum value. In the case of numbers, the highest number will be returned; for strings, the highest alphabetically ordered string will be returned.
min(<list>) Like the max() function, min() will return the item with the lowest alpha or numeric value.
sum(<list>) The sum() function only works with numeric lists. It adds all of the items in the list together and returns the sum. If there are non-numeric items in the list, sum() will error.

Tuples

I can’t talk about lists without mentioning it’s less popular and underappreciated kid brother, the “tuple”. Tuples are similar to lists in many ways, but different in one very key way. Tuples are unchangeable. Unlike his big, popular, handsome brother, the tuple has no methods for adding or removing elements. Once the tuple is created, he cannot change. The term programmers user for this is “immutable”. Tuples are immutable objects. Immutable is just a fancy and unfriendly way of saying unchangeable. Programming, like most other fields, likes to use jargon that other “outsiders” won’t easily understand.

Tuples and lists look very similar, but you can always spot a tuple because, instead of being enclosed in square brackets ‘[ ]’, the tuple is enclosed in parentheses ‘( )’. Tuples can be created the same way as lists, just enclose the items in ‘( )’ instead of ‘[ ]’.
myList = [‘cheese’, ‘eggs’, “welch’s grape”]
myTuple = (‘cheese’, ‘eggs’, “welch’s grape”)
The purpose of the tuple is often difficult to understand for new programmers, especially python programmers. This is because Python, unlike the ‘C’ programming languages, manages memory for you. The reason the tuple exists is that it uses less memory than a list, and it can be accessed faster. So, tuples should be used when you have a constant list of items that won’t require any ‘in-program’ changes. For example, if you want to write a program that sorts items into pre-defined categories, the list of categories should be put into a tuple because the categories will be:
  • Defined before hand
  • Accessed often
  • Not changed during the program’s execution.
So, don’t dismiss tuples, in many situations they can perform better than the bulkier list object. Plus, it’s a fun word to say... tuple. If you start talking about immutable tuples, other programmers will perk up and know that you are a member of the club.

There is a lot more that can (and will) be said about lists, but this should be a good enough primer to get you familiar with their operation. I will probably do a follow up post to this one that has practical applications for the functions that I have mentioned in this post. After that we will discussing ways of comparing data and making decisions within our programs. Stay tuned.