Loops

In this section, we'll talk about loops. These are important for "automating" code, and repeating these processes multiple times.

Loops

There are many data types in Python. For this section, we'll be focusing on String, Integers, and Floats.

Why Loops?

Loops are extremely useful when we want to repeatedly perform a task. For example, if we wanted to print "hello" 100 times, we can use a loop to do this, rather than write the print statement 100 times. Another use of loops is iterating lists, which we will discuss in the next topic.

We'll be using the while and for loops in this course.

While Loops

The while loop is nice for looping over known ranges. For example, if we want to loop through and print the first 100 numbers, we can simply use a while loop.​

Example: 

i = 1
while i < 101:
 print(i)
 i += 1

In this example, we declared the variable 'i' to take on the value of 1. Then we have a while loop, which states that while i < 101, execute the code below. The code below will print i each time it runs, but after it runs, we are adding 1 to i. Therefore, the value of i will increase as time goes on until it reaches 101, at which point the while loop will be broken.

For Loops

For loops are another way to write loops. They are quite useful for iteration. That is, we can use it to loop through all elements in some group.

Example:

for x in "banana":
 print(x)

In this case, x is an arbitrary variable that represents the letters in "banana". The for loop tells us that we will loop through each character in "banana", and print the letter. For loops are very convenient when working with lists, which we will cover in the next section.

Exercises:

1. Write a for-loop which prints each number from 0-99.

2. Write a while-loop which does the same as number 1.

3. Write a loop which multiplies every integer from 1-1000 by 5 only if it is divisible by 7. Keep everything else the same. Print all of the modified numbers. (Challenge Problem)

4. Declare a String with at least 10 characters in it. Print each of the characters using a loop.