Loops

Loops can be used to run through data structures.

for loop

We want to count from 1 to 10.

for i in range(10):
	print(i)

How does this work? range(10) generates a list of ascending numbers. The list has 10 elements and it starts from 0! 0 1 2 3 4 5 6 7 8 9 are our 10 elements. The code from above will print a wrong answer. To fix it, we can add 1 to each element of the list. We’ll get: 1 2 3 4 5 6 7 8 9 10. Let’s add 1 in the code:

for i in range(10):
	print(i+1)

If we want to count to 20, we replace 10 with 20. We can even write a function:

def count_to_x(x):
	for i in range(x):
		print(i+1)
	return

count_to_x(10)

Because we do not return anything, we can skip the return keyword:

def count_to_x(x):
	for i in range(x):
		print(i+1)

count_to_x(10)

General syntax for for loop:

for i in {list}:
	{block of code
	do something with i}

while loop

General syntax:

while {condition}:
	{block 
	of
	code}

We can use while when we have to check an external event:

i = input()
while i!='exit':
	print("you wrote: "+i)
	i = input()