Showing posts with label loops. Show all posts
Showing posts with label loops. Show all posts

Friday, January 30, 2015

Using files to file stuff...

Everything we’ve dealt with up to this point has had no real permanence. That is to say that all of the data we’ve processed only exists during the life of the program, once the program is complete, the data is destroyed. This is ok for programs like calculators, but most programs require data to be contained between uses. In order to do that the data needs to be saved to disk in the form of a file. Luckily, reading and writing from files is pretty easy using Python. Let’s begin by opening the interpreter and making a new file like this:
f = open(<path to file/filename>, “w”)
Notice that this immediately creates a file in my file system. I created a text file, but you can add any extension you want to. However, adding a jpg or mov extension won’t automatically make your file an image or a video. Certain file types require special readers and writers to work properly. This method only allows you to save data in readable form, such as text or numbers. I will discuss more advanced methods of file reading and writing in a later post. For now, we’ll stick with the text file.

The open( ) function takes the filepath as its first argument, followed by an optional argument, which in our case was “w”. The “w” stands for write, because we wanted to write a file at the path that we specified. Without the “w” the open function would have errored because the file didn’t already exist on disk. So when creating a new file, use the “w” argument. 

Now we have a blank file open in a file object. Let’s add some text into it using the write( ) method that is built in to our file object.
Remember the “\n” represents an “end of line” character. Now that we’ve added some data to our file object we can close the file using the close( ) method. This will write the data to disk because we invoked the “w” argument when we created the file object.
Now we can re-open our file by using the open( ) function again, but this time we will pass it “r” as a second argument. “r” stands for read and will prevent the file from being modified inadvertently by opening it as a read-only file stream.
Now we can iterate through our file object using a for loop to read the data from it:
If we repeat the for loop we will get nothing.
This is because the file has already been read through and our file “cursor” is sitting at the end of the file. We can confirm this by using the tell( ) method, which tells us what position our cursor is at in the file.
Now we can see that we are at the 103rd position in the file. In order to move the cursor back to the beginning of the file we can use the seek( ) method.
The seek( ) method will set the file cursor to the position specified. Using an argument of 0 will set the cursor back to the beginning of the file.

Now we can invoke a different method to read our file. The read( ) method can be used to assign the entire contents of the file to a variable.
There are lots of methods that can be used on file objects. The last one I’ll talk about is the readline( ) method. This method, as you might guess, reads the file until it finds a newline character “\n”.
Putting it all together
We now have the tools to save information from a program and read it back in again later. There are many ways we can go about this. For instance, let’s pretend we are writing a video game in which our player’s character has different attributes like health, speed, strength, and items. Each time we load our game we can read the attributes from a file, and each time we close the program we can write the data out to a file.
Let’s assume that the file looks something like this:
Name:Bob
Health:50
Strength:10
Speed:5
Handsomeness:2
We could load these lines in using a file object and read through each line to get the attribute and it’s value. Attribute:value should give you an idea of how this data might be stored once we load it into the program. We could load it into a dictionary. We can do this in the following manner:
file = open(“D:/character.txt”,”r”)
character = {}
for line in file:
    attributes = line.split(“:”)
    key = attributes[0]
    value = attributes[1].replace(“\n”,””)
    if key == “Name”:
        character[key] = value
    else:
        character[key] = int(value)

Notice that each value has the newline character “\n” removed before loading. Also, if the item to be loaded is numeric it is converted from a string to an integer using int(value) when being assigned to the dictionary value.
Once the data is loaded into a dictionary it can be manipulated using standard methods.
Then when the program is closed or the user prompts a save if can be written out using a similar method:
file = open(“D:/character.txt”,”w”)
for key in character.keys():
    line = key + ’:’ + str(character[key]) + “\n”
    file.write(line)

file.close()

 
Now the data your programs generate can live on long after your program has been closed. There are many pre-existing methods to read and write files of different types which I will cover in future posts, but for now, go wild with the possibilities inherit in long term data storage and retrieval.

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.