NetLogo

y; Example of a For loop
repeat 5 [
	do-something
]
; Example of a While loop
let i 0
while [i < 5] [
	do-something
	set i i + 1
]

Python

# Example of a For Loop
for i in range(0,5):
	do-something

# Example of a While Loop
i = 0
while (i < 5):
	do-something
	i = i + 1

While Loops

Generally, any for loop can be rewritten as a while loop. For loops are used primarily when you know how many times something is going to be repeated or looped.

In NetLogo, this was super simple. repeat # of time you want to repeat. And generally, you do know how many times you want to loop something. How many objects there are in a list, go forward and turn right 90 4 times, do something for every student in a class, etc.

While loops are useful however, when you need to specify a condition of when to exit a loop. We've been using them primarily as "until i hits some number." But this could also be...

NetLogo

; Example of a While Loop
while [grades.completed = false] [
	grade-papers
]

Python

# Example of a While Loop
while (grades.completed == False):
	grade_papers()

For Loops

For loops are primarily used to iterate over a list of stuff. We use lists and other similar data types pretty often (more next week), and iterating (going over each one) happens quite often—

# Example of a For Loop
student_names = ["Billy", "Bobby", "Joe", "Sarah", "Alyssa", "Jo"]
for i in range(len(student_names)):
	print(student_names[i] + " says hello!")

Infinite Loops

You may have noticed that we run into a problem when we forget to add 1 to i. (please remember to put your i = i + 1. This is called an infinite loop... because, well, you never get out of the loop.

In this example to the right, we can see that we will print "hi" over and over again, until i is no longer the value of 0. Which is... never.

This is an infinite loop and it will never terminate. Stay away.

i = 0
while (i == 0):
	print("hi")

There are actually very few applications of infinite loops. Like VERY few.

Like, our command center. But that, too, should have some exit.

while (True):
	line = input("")
	commands = line.split(" ")
	if commands[0] == "shout":
		....