With while
loops, there's always a risk of accidentally creating a conditional that never becomes False
, leading to an endless loop. Luckily, this can usually be avoided just by checking over your loop logic carefully.
Let's look at an example. The following code is an endless loop:
count = 1
while (count <= 10):
print count
Output:
1
1
1
1
1
... (never ending...)
Don't try running this code in the notebook -- it will just cause the notebook to freeze up because it never stops running! (Note: if you ever create an endless loop in your Jupyter notebook, click the "interrupt kernel" (square) button at the top to stop it.)
So what is going on here? Notice that unlike our other examples so far, we never increment count
within the loop. Therefore count
always remains 1, and so the while
condition is always True
and we keep looping forever.
Let's see if you can spot an endless loop before it occurs! For the following examples, guess whether or not the loop will be endless (note that these blocks will not be runable to prevent you from freezing up your notebook; see below for the answers).
Answer Key
- No
- No (in fact this won't print anything at all, since the condition "
count > 5
" is neverTrue
)- No
- Yes (we never increment
count
within the loop, so it never becomes equal to 5.)- Yes (since we're incrementing
count
by 2 each time, count takes the values 0, 2, 4, 6, 8, etc. Socount
never equals 5, so the condition "count != 5
" never becomesFalse
, and we keep looping forever.)
range()
As it turns out, range()
is a pretty cool function that can create many different kinds of number series. Here's the full definition:
[ Definition ] range()
Purpose: Creates a list with the indicated range of integers from start
to end-1
. If only one argument is given, this argument is assumed to be the end
value and the start
is assumed to be 0, so a list of integers from 0 to end-1
is created.
Syntax:
range(end)
range(start, end, interval)
Notes:
Examples:
In [ ]:
print range(5)
In [ ]:
print range(1, 6)
In [ ]:
print range(0, 11, 2)
In [ ]:
print range(4)
In [ ]:
print range(4, 8)
In [ ]:
print range(0, 50, 10)
In [ ]:
print range(50, 0, -10)
You don't have to read a file using a loop. You can also read it manually line by line, or dump all the lines into a list. We won't go over those methods much here, but here is a list of some of the more useful functions that are available:
.read()
- reads in the entire file at once as a single string.readline()
- reads one line at a time.readlines()
- reads all lines in file into a list.close()
- close the file Example:
In [ ]:
inFile = open("genes.txt", 'r')
header = inFile.readline() #read first line of file (often we do this to get rid of a header)
line = inFile.readline() #read second line of file (repeatedly calling .readline() progresses through the file)
restOfLines = inFile.readlines() #read rest into list (each line will be an element)
inFile.close()
print header
print line
print restOfLines
In [ ]:
infileName = "genes.txt"
outfileName = "output3.txt"
inFile = open(infileName, 'r')
outFile = open(outfileName, 'w')
for line in inFile:
line = line.rstrip('\r\n')
outFile.write("Found " + line + "\n")
outFile.close()
inFile.close()
This code prints the following to "output3.txt":
Found uc007afd.1
Found uc007aln.1
Found uc007afr.1
Found uc007atn.1
Found uc007bcd.1
Found uc007bmh.1
Found uc007byr.1
In [ ]:
print "Hello\tHello\tHello"
As you'll see in the next lesson and saw in the Unix lessons earlier in the course, we often work with tab-delimited text files, so it's useful to know how to make a tab in your output files.
In [ ]:
count = 0
while count < 10:
count = count + 1
print count
In [ ]:
string = ""
for i in range(5):
string = string + "a"
print string
Basically, these are situations where we're adding or concatonating something to an existing variable, and then overwriting the old value of the variable with the new value.
We do this so much in programming that there's actually a shorthand for it: +=
. Here's what the same examples look like using this shortcut:
In [ ]:
count = 0
while count < 10:
count += 1
print count
In [ ]:
string = ""
for i in range(5):
string += "a"
print string
So this saves you a little bit of typing. You'll see this shortcut used quite a bit in real life Python code.