Udacity CS 101: Loops

Loops go in loops:

Decision

Loops, they loop.
Image courtesy of http://www.thelineofbestfit.com

Yea I probably don’t make much sense, but loops do exactly what they mean! Loops continue executing the block until a specific expression stops it. It is possible to write an infinite loop that keeps going on and evaluating the same block of code, but that will probably eat up your computer memory and crash. A simple kind of loop is called the while loop:

i = 0
while i < 10:

print i
i = i + 1

What this code does is set the variable i to the value 0. It then enters the while loop. The statement checks the condition i < 10. If this expression evaluates to True, the code block below is executed. The value of i is printed, and the i is increased by 1. The code returns to the while statement, remember this is a loop! So now the value of i is 1, the while statement will evaluate the expression i < 10, since 1 is less than 10, the code block is executed again, i is printed, then increased by 1, and while repeats.
So when does this loop end? The first instance when i < 10 evaluates to False, which is when i is 10. Simple!

Since you can enter a loop, there is also a way to break out of the loop!

i = 0
while i < 10:

print i
i = i + 1
if i == 5:

break

So here we nest an if conditional statement inside the for loop, so when the program reaches i = i + 1 where the value of i is then 5, the if statement will evaluate to True and the program will break, which means it leaves the while loop. This doesn’t make much sense we could have just written the while statement as while i < 5. A more practical use is this:

i = 0
while True:

if i > n:

break

print i
i = i + 1

This can be used to check if n (a user entered integer), is negative, because since i is 0, any number smaller than i would be negative, hence the loop breaks!

With this we’re done with Unit 2, well ahead of schedule! Feel free to try the homework and do comment if you’re stuck somewhere! See you at Unit 3.

This Udacity post references Udacity CS 101 Unit 2 Chapters 22, 23, 24, 25, 26, 27, 28, 29 and 30.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s