You will each be using Github to submit your quiz answers. For this quiz only, you will be allowed assistance in completing the quiz.
This quick script will introduce you to several concepts at once. Our goal will be to write out the Fibonacci series up to 100. This will introduce multiple assignment, looping (with the while loop), and the print statement as output.
We start off our script with comments explaining the purpose of this code.
In [ ]:
# Fibonacci series:
# The sum of two elements defines the next
Now we are going to use multiple assignment to assignment variable a
and b
at the same time. The variables are assigned left to right to the values in order left to right.
In [ ]:
a,b = 0,1 #Initialize two variables at once by multiple assignment
Next we will start a while
loop. A while
loop will execute a block of statements repeatedly as long as the while condition is true.
In [ ]:
while b < 100:
print b
a,b = b,a+b
print "Done!"
Let's take a look at what is going on here. First we initialize the statement with the keyword while
and then follow with a condition, b < 10
. The condition makes its first check. b
is 1 (why?), so the condition is true and we execute the while
block that follows after the colon.
In Python, unlike many other languages, the a multi-line block is designated by spacing. The first line is indented, in this case with four spaces. The spacing does not have to be exactly four spaces, but it does need to be consistient across a code block. You can learn more about Python identation and some of the myths that go with it at Python: Myths about Indentation.
There are two lines in the while
block
print b
a,b = b,a+b
Both statements execute. The first statement is a print
statement, which will evaluate the string equivalent of its argument and send the resulting string to the standard output (in this case, our IPython notebook). Since b
is assigned the integer 1, that evalutes to the string "1" and "1" is sent to the standard output.
The second statement is another multiple assignment. But before assignment happens, the right-hand side of the assignment happens from left to right.
a,b = 1,a+b
a,b = 1,0+1
a,b = 1,1
a = 1; b = 1
We reach the end of the block, and loop back up to evaluate the while
statement again.
Notice that we print the phrase "Done!" only once. This line is dedented, which signals that it is not part of the while
block and so not part of the loop.