BLACK FRIDAY EXTRA SAVINGS EVENT - EXTENDED
START FREE

Loops, i for some reason cannot wrap my head around them

Hey everyone, I have been coding for roughly 2 weeks now. Up until now, I have grasped things and have been able to make it make sense. But loops, its just something about how the lessons are worded that makes them difficult. So many words to tell how to do something that has now been made complicated. Could someone explain loops to me like im a 5 year old? I get the process of iteration but more so, breaking down the text to understand the loop and then setting the loop up correctly. Any help would be great. Thanks!

1 Like

Hi @scchapman94,

I had some difficulty wrapping my head around loops as well.

While Loop

A while loop executives the code within the body of the loop while a specified condition is met. Let’s look at the loop below:

# The while loop below iterates over each character in the string *fruit* and print the each character

fruit = 'banana' # Initialize the string 'banana' to the variable fruit
index = 0 # Initialize an index variable to increment after each execution of the loop
while index < len(fruit):  # While the index variable is less than the length of the contents of the string fruit (6)
    print(fruit[index]) # Display the character of the string fruit at the current index (index: 0, character: 'b', etc.)
    index = index + 1 # Increment the index variable (index = index (0) + 1)

# The while loop will continue to run and execute the body of the loop until the specified condition is no longer met (when the index variable is 7).

Let’s now look at a for loop.

For Loop

A for loop executes the body of the loop for a given number of iterations. Using the same example, take a look at the below for loop:

# The for loop below iterates over each character in the string *fruit* and prints each character

fruit = 'banana' # Initialize the string 'banana' to the variable fruit
for letter in fruit: # For each letter in the string fruit (6 characters, body will execute 6 times)
    print(letter) # Print the current letter (letter would represent the character at index 0, then 1, etc.)

# Note that we can name the letter variable whatever we'd like, 
# but it makes sense to use letter since we're iterating over each element in a word

# Also note that we don't need to increment the letter variable, 
# the for loop does this for us
 

Hopefully this quick explanation will be helpful! Best of luck in continuing to learn!