Help please! I don't understand loops

Hi,

I am signed up to the Codeacademy Pro course. I am really struggling with loops, have gone through the course and challenges but just don’t get it. I have watched videos on youtube as well but it’s just still not clear in my mind and not sinking in. I’ll watch something and think ok I think I got this but then I go to do a challenge and I can’t do it on my own and continue to look at the solution because I don’t understand the structure. I really need to understand the loops however I do feel frustrated and very thick right now! Any advice of how I can go about finally understanding this and move forward?!

Many thank in advance for your help!

What kind of loops? For loops? While loops? Both? We are here to help :wink: .

Anyways, there is plenty of documentation out there, an example here. Loops are actually quite useful once you get your head around how they work.

3 Likes

Thanks for the link, I will have a look. And yes need help with both while and for loops.

1 Like

Okay :wink: . What is it exactly that you don’t grasp. Or would like me to to just explain them here?

I just look at loops and it just doesn’t make sense so when I go to do them on my own I can’t . I will have a look at the link you sent and take it from there from now as I know I am not being very specific.

No worries let me try to explain for loops first with the following example.

Say you have a fruitbowl with different kinds of fruit. And you would like to go through the bowl and check each fruit and tell someone else in the room what they are.

How to do this in code. We can see the fruit bowl as an array of fruits. And to tell out friend we can just print it to the console.

so:

fruitbowl = [apple, banana, kiwi, apple, orange, apricot]; # an array of fruits

# now we want to check each fruit in the bowl using a for loop and we do this like so

for fruit in fruitbowl: # this will iterate past each fruit in the array of fruitbowl 
  print(fruit) # print they value of fruit

# the output of this for loop will be each fruit printed on a single line: 
apple
banana
kiwi
apple
orange
apricot

Hope this explains a for loop for you well enough.

1 Like

Thanks for this. I get the basics like this but it’s when it becomes more involved. I have done the exercise from the link you sent. I did have to look up a couple of syntax this to remind myself but I don’t get one of the things which I have commented in my solution. Also, is my solution just as good as the solution online as I get the same result right?

Task: Loop through and print out all even numbers from the numbers list in the same order they are received. Don’t print any numbers that come after 237 in the sequence.

**The solution from site:**
for number in numbers:
    if number == 237:
        break

    if number % 2 == 1:
        continue

    print(number)
**My solution**
list1=range(0,237)


# iterating each number in list 
for num in list1: 
      
# checking condition 
    if num % 2 == 0: 
       print(num, end = " ") #why do I need to put end=""? What does this do?

Well actually, even though the print output maybe the same, you are not getting the same result and you are not doing what the exercise asked you to do.

Because, you have created your own list of numbers rather than iterating through the provided array :wink:

print(num) should be enough

Thanks:) Yes i noticed this after but it does say not to show values after 237 so I just did my own. I will continue practicing and may just keep posting here when I don’t understand something. I may need to go through the section on Code Academy again.

1 Like

Ok I found an article I am going through as says to stop if you don’t understand. I have commented my thought process so perhaps this way I will understand and you can better understand how to help me too:) Thanks for your patience with this! Is it normal to be so slow and just not get it?!

Article I’m referencing:

Objective of program:
Takes a list of words, converts each one to all-uppercase, and prints out the uppercase word.

CODE:

words = [“Four”, “score”, “and”, “seven”, “years”, “ago”] #this is the list

i = 0 #counter starts at 0 which is Four in the list

while i < len(words): #why am i looking at length of words? Can’t I just tell it to convert the list to capital letters without having to use a loop? This seems unnecessary to me.

waffle = words[i] #is this the new list I want with capital letters? It starts at i because it looks at the value of counter?

uppercase_word = waffle.upper()#new variable set to make list into capital letters

print(uppercase_word)#prints the list in capital letters.

i += 1#indicates to go to the next item in the list

Ok lets see if I can make things clear for you :wink: . The goal of the exercise is to read an array of words and print each word in capitalized form. I will answer your questions you put in the code. So:


words = [“Four”, “score”, “and”, “seven”, “years”, “ago”] #this is the list

That is correct!


i = 0 #counter starts at 0 which is Four in the list

You got that right. In code you start counting at the 0th element. We are making an iterator that runs past all the items in the list based on their index a.k.a. the position in the list, hence i. But this could just as easily be any other word since it is a variable with a value of 0. You could have picked index = 0 or wordNumber = 0.

while i < len(words): #why am i looking at length of words? Can’t I just tell it to convert the list to capital letters without having to use a loop? This seems unnecessary to me.

Ok this gets a bit more complex but easy if you get your head around. Since we are using a while loop, we execute something until a certain condition is met.

So what do we want to do, and when does it end?

We want to do something with each word, and we need to stop doing it once we reached the end of the list :wink: . And how do we know when we have reached the end of the list? When we have reached the index number, our variable i that is equal to the length of the list words. So our condition of the while loop is i < len(words).

You ask why we can’t just do it without a loop, well the answer to that is, yes. You could use the map function. But we are discussing loops now :wink: . There are different loops you can use to achieve the same result, but that is the second part of the reddit topic.

waffle = words[i] #is this the new list I want with capital letters? It starts at i because it looks at the value of counter?

waffle is not a list, it is a variable that is used to store the value of the list words at the index i the while loop is at that moment. If the while loop is at i = 3, waffle will get assigned a value of words[3] which is ‘seven’. Upon the next iteration waffle will get assigned a new value of words[4].

uppercase_word = waffle.upper()#new variable set to make list into capital letters

The previously stored value of waffle will be capitalized and stored in yet another variable uppercase_word.

print(uppercase_word)#prints the list in capital letters.

All we do now is print that single value of uppercase_word

i += 1#indicates to go to the next item in the list

We have done everything we needed to do with the current word in the list of words, so now we add 1 to the value of i and the while loop hops on to the next word.

1 Like

Thanks for this, I really appreciate it. I will go through what you have said when I have time and do more exercises but I may very well have more questions:thinking:

1 Like

I’m back but have some questions from the loops quiz as don’t know or understand the answers to these questions. Can you please explain the answer and why it is the answer?

Which of these list comprehensions will create a list equal to desired_list ?

my_list = [5, 10, -2, 8, 20] desired_list = [10, 8, 20]

[i + 5 for i in my_list]

[i for i in my_list if i > 5]

[i for i in my_list if i > 10]

[i for i in my_list] #I picked this as answer as only one that made sense to me


What would be the output of the following code:

numbers = [2, 4, 6, 8] for number in numbers: print(“hello!”)

2 4 6 8

2 hello! 4 hello! 6 hello! 8 hello!

hello!

hello! hello! hello! hello! #why is this the answer? I understand it will print hello but why just 4 times?

Answer should be [i for i in my_list if i > 5]. Since the desired_list only has numbers higher than 5.

You can test this by pasting the following code inside this code editor

my_list = [5, 10, -2, 8, 20] 
desired_list = [10, 8, 20]

print([i + 5 for i in my_list])

print([i for i in my_list if i > 5])

print([i for i in my_list if i > 10])

print([i for i in my_list]) 

Well all the code does is for each number in the list of numbers to print out hello.
Since there are 4 numbers it prints out “hello” 4 times.

Again you can test this by pasting the following code:

numbers = [2, 4, 6, 8] 

for number in numbers: print("hello!")

Thanks you! Both make sense now:)

1 Like