More About For Loops in Python & Solutions to the Last 2 Problems (Python Tutorial #7)


So in previous videos, we saw a few examples of how to use for loops in Python. For example, if you have “a” being equal to a list with three elements. “Apple”, “banana” and “republic” You can print each element with “for element” in “a” colon 4 spaces, print element. And when you run this cell, you should see apple banana and republic, and you do. So another way of doing the same thing is by using the indexes, or the indices of these 3 elements. You can do that with for i for index, in range of 0 comma 3 colon. Because this way, range will go from 0 to 3 but not including 3. So that would be 0, 1 and 2. Actually, a shorthand for this would be range of just 3 and it does exactly the same thing. So lets see how that works with print “i” And you can see that 0, 1 and 2 as expected. So using this as the index, you can just write print “a” square brackets “i” And then it’s gonna print “apple”, “banana” and “republic”. And instead of using 3, we could also use “len” parentheses “a” which will return the length of “a” which is 3 So this is going to do the same thing as what we had before So why would we want to use the second method instead of the first method? The way I think about it is by default, you should use the first method which is like for element in “a” because that’s a much simpler method. But in some cases the index matters, not just the element. For example if you wanted to print “apple” once, “banana” twice and “republic” three times here’s what you can do For “i” in range of len of “a” which is the same as what we had before and then within this “for loop”, create a new “for loop” with for “j” in range of “i” plus 1 and this way when “i” is equal to 0, “j” will be just 0. And when “i” is equal to 1, “j” will be 0 and then 1 And when “i” is equal to 2, “j” will be 0, 1 and then 2. So actually the value of “j” doesn’t really matter because we’re not gonna use it but the important thing here is that we’re going to go through this inner “for loop” which includes “j” once when “i” is equal to 0 and we’re gonna go through this loop twice when “i” is equal to 1 and we’re gonna go through that loop 3 times when “i” is equal to 2. So within this “for loop”, within the outer “for loop”. We can print “a” square brackets “i” and that should print “apple” once, “banana” twice and “republic” 3 times. Let’s run this cell, and that’s exactly what we see. Ok, let’s now quickly go through the 2 problems I gave you in the last 2 videos. In tutorial 5, I gave you this problem. Can you compute the sum of all multiples of 3 and 5 that are less than 100? So that would be the sum of 3, 5, 6 and so on, and then 15 which is a multiple of both 3 and 5 18, 20 and so on. And here’s my solution First initialize a variable, let’s say… “total” to 0 and then run a “for loop” for “i” in range of 1 comma 100. So that would be all the positive integers that are less than 100 and in this “for loop”, just write if “i” mod 3 is equal to 0 So if “i” is a multiple of 3 then add this number to “total”, with “total” plus equals “i”. And else if “elif”, if that number is a multiple of 5 then add this number to “total” After this “for loop” just print the results which is “total” and we get 2318, so that’s the answer. But instead of using “elif” we could also do, if “i” % 3 is equal to 0 or if this number is a multiple of 5 which is the same thing as “i” mod 5 is equal to 0 Then add “i” to the total number and then print “total”. So this “or” statement says we want to do the following which is total plus equals “i” if the first condition or the second condition is true. And if both of those conditions are true, then we still want to do the following and that’s good because when “i” is equal to 15, we still go through and we still add “i” which is 15 to total. And then once we run this cell, we get the same answer: 2318 And here’s the problem I gave you in tutorial 6. We were given this list and the assumption there was that we don’t necessarily know the content or the length of this list but we know that it’s sorted in a descending order so that the largest number comes first and then when you go right the numbers always stay the same or go down. And we also assume that there’s at least 1 positive number in this list and we wanted to find the sum of only the negative numbers here. To do this, here is my solution. Let’s first initialize “total2” to be 0 and then I’ll initialize an index, lets call it “j”, to the length of given_list minus 1. So that would be the index that corresponds to the last element of this list and then what I’m going to do is I’m going to change “j” so that we can iterate over only the negative numbers starting from the right because just in case there are a lot of positive numbers in this list but only a few negative numbers, we dont really wanna go through the whole list if we can avoid it. So we’re going to do that with while given_list square brackets “j” is less than 0 so while the current element that we’re examining is less than 0, add that item to total2. So total2 plus equals given_list square brackets “j” and then go to the next item by decreasing “j” by 1 so you could write “j” equals “j” minus 1 but it’s the same thing as “j” minus equals 1. And after that, just print total2. So the answer is -17 let’s check that, -2 plus -3 plus -5 thats -10 plus -7 thats -17. So it looks like this solution is correct. Ok, if you’re following these tutorials in real-time you might have noticed that the pace of me posting these tutorials has been kind of slow recently and it’s just because I’ve been working on other videos. So if you don’t wanna wait for the next tutorial, I’d recommend the following 2 courses I have on Lynda.com and Pluralsight. And you’ll be able to take them for free so the one on Lynda.com is called Get Ready for Your Coding Interview. It is about coding interviews but I cover a lot of basics in Python so it should be a good course for you to take after this course. Actually my voice doesn’t sound great in this course, but it’s just because I didn’t know what I was doing back then but the content should be good. And the second course I’d recommend is called Introduction to Data Visualization with Python on Pluralsight and this one’s good if you’re interested in getting into data analysis with Python. And like I said, you can take these courses for free with their 30-day free trial and 10-day free trial. I’m gonna put the links in the description below for these courses but don’t worry because I’m gonna come up with more Youtube tutorials too. Ok, again I am so sorry if you’ve been disappointed with the pace of me posting these tutorials but hopefully I will see you guys soon in the next video

100 thoughts on “More About For Loops in Python & Solutions to the Last 2 Problems (Python Tutorial #7)

  1. You can download the sample file for this video here: https://www.csdojo.io/python7

    And here are the courses I mentioned at the end of this video:
    Get Ready for Your Coding Interview: https://goo.gl/RMCaxW
    Introduction to Data Visualization with Python: https://goo.gl/fZ5oVX

  2. Can someone explain the answer for Tutorial 6 why he set
    j = len(given_list) -1?
    Timestamp around: 6:39

  3. I just want to say I don't know if I'm correct but I think your solution to the 3,5 multiples question is wrong. You specifically asked for us to make a code that would give us the sum of all multiples of 3 and 5. those multiples to 100 would include 15, 30,45,60,75,and 90. they add up to 315 so the answer to your specific question would be 315. in your solution however you made a code that would add every single multiple of 3 to every multiple of 5 but it would not add the multiple of BOTH 3 AND 5. so your code adds all the multiples of 3 and multiples of 5 up and leaves out the combined multiples(15,30,45,60,75,90). I figured all of this out on a very good calculator. so I know for a fact it is right. You gave the answer of 2318. that however is the sum of all the multiples of 3 and 5 minus the common multiples between 3 and 5. You wanted the sum of the common multiples between 3 and 5 if I heard correctly. So you would add 15,30,45,etc. together to get the correct answer of 315. for the code, after the if i ÷ 3 == 0:, you have to take out the first "total" line and the elif should just be if. Taking out the first total line make the code calculate the sum for the multiples of BOTH 3 AND 5 instead whereas your code says to add all multiples of 3 and then add all multiples 5 if they are not multiples of 3. Please read this so you can maybe correct this mistake in the future. Just to clarify, I may not have heard you correctly when you said the problem but I'm pretty sure I did. I also don't know if you meant to tell us one problem but accidently explained it in a different way. Thank you for your consideration and time in reading this post. I just wanted to also say that I think you are very incredible at teaching hit to code and learn python. Nobody else I've seen online has been able to explain python as well as you have. I hope you live the rest of your amazing life remembering of what an impact you have made on my life and several others lives who watched your videos to learn python. Keep up the good work.

  4. someone could explain for me how to compute the sum of all the negative numbers in " given_list" ?? I don't understand why must we write that to get the result ?

  5. Just wow, spent most of this week trying to figure out this negative number problem. Please give us some more simple problems! This has been great. Thank you.

  6. why would i get different result?
    d = list (range(1, 100))
    total11 = 0
    for i in range(len(d)):
    if i % 3== 0:
    total11 += i
    elif i % 5 == 0:
    total11 += i
    print (total11)

    result becomes 2219

  7. given_list3 = [7, 5, 4, 4, 3, 1, -2, -3, -5, -7]
    total6 = 0
    i = 0
    for element in given_list3:
    if element <= 0 :
    total6 += given_list3[i]
    i += 1
    print(total6)

  8. at 3:11 what caused apple to be printed once,banana to be printed twice and republic to be printed thrice?
    also at 7:00 why did he write j-=1 ? what did he do by doing that or what would've happened if he didn't do that?

  9. I see that you do this full time and that’s awesome. it could really help you out if you start to monetize your videos. this way, you can earn a little extra income.

  10. bro you on tut 7 and no tutorial on input() yet my god, check out the courses on edx.org i like the one from microsoft it's free

  11. given_list3 = [7, 5, 4, 4, 3, 1, -2, -3, -5, -7]
    total = 0

    for element in given_list3:
    if element < 0:
    total += element

    print(total)

    -17

    It gave -17 aswell, is this correct?

  12. given_list3=[7,5,4,4,3,1,-2,-3,-5,-7]
    total6=0
    k=0
    while k<len(given_list3) and given_list3[k]<0:
    total6+=given_list3[k]
    k+=1
    print(total6)
    this code output is zero why?
    what is wrong with this

  13. Is there a way to continue on a sequence in a list? For instance if I have the list [1, 2, 4, 7, 11] is there a way to continue that sequence? thanks

  14. Hi CS Dojo,
    this is another alternative to the solution that you posted.

    given_list2=[7, 5, 4, 4, 3, 1, -1,-2, -3, -5, -7]
    total2=0
    i=len(given_list2)-1
    while True:
    total2+=given_list2[i]
    i-=1

    if given_list2[i]>0:
    break

    print(total2)

  15. cs dojo's lessons are simple and easy.
    That's why i learned how to code python in a week or two.
    before this awesome step in python, i didn't know how to code in it at all.

  16. can you explain the
    for j in range(i + 1):
    like this
    j=1,t2=0
    j<5
    t2+=j
    j+=1

    1<5
    t2(0)+=1,t2=1
    j(1)+=1,j=2

    2<5
    t2(1)+=2,t2=3
    j(2)+=1,j=3

    3<5
    t2(3)+=3,t2=6
    j(3)+=1,j=4

    4<5
    t2(6)+=4,t2=10
    j(4)+=1,j=5

  17. I do not understand. How does the second solution = -17.
    j = len(given_list) – 1, doesnt that mean J = 9. Then the while loop would start at j = 9 which excludes the last number of the list.

  18. @CS Dojo ,Brother I think for loop in j, when i = 0 that means j = 1 not 0. It has to be corrected if I'm not wrong.

  19. Hey CS Dojo, I found this method of finding the sum of the multiples of 3 & 5 on the net. Sum({*range(1, 100, 3)}|{*range(1, 100, 5)}). It'll be great if you could explain it.

  20. What about using a for loop to iterate over a bunch of shapefiles you found previously to be able to print out each filename?

  21. the "i +1" loop part, I tried that in pycharm, and it doesn't work out like the one in the video( 1 "apple", 2 "banana", 3 "republic"), instead it keeps giving me error shows there is something wrong with the code

  22. thanks CS Dojo! Your solutions and the way you explain things is so simple and effective! Occam's Razor in action

  23. Does anyone know why for the first example in the if-statement if “else” is used over “elif” a different output results?

  24. Thanks for the videos! Few questions about the practice problems.

    What is the purpose of assigning the variable 'total' and 'total2' to = 0 in both problems? There exists not much explaining as to why making those variables equal to 0 helps the code run. To some real newbie beginners like myself, we want to understand all this code conceptually too. So if anyone could explain that, it'd be much appreciated.

  25. hey yk 🙂 i used the for loop for the tutorial 6 problem and it is much more simpler than yours i think ..take a look .. Thanks ..
    given = [7, 5, 4, 4, 3, 1, -2, -3, -5, -7]

    total = 0

    for i in given:

    if i < 0:

    total += i

    print(total)

  26. Hi Would the following also be a correct solution:

    given_list3 = [7, 5, 4, 3, 2, 1 , -2, -3, -5, -7]

    total = 0

    increment = -1

    while given_list3[increment] < 0:

    total += given_list3[increment]

    increment -= 1

    print(total)

  27. given_list = [7, 5, 4, 4, 3 , 1, 2, -3, -2, -3, -5, -7, -1]

    total = 0

    i = -1

    while given_list[i] < 0:

    total += given_list[i]

    i -= 1

    print(total)

    For me, this is also working fine. Since I have taken i = -1 the loop will start in reverse order i.e., from -7 in this case.

  28. One thing CS Dojo never mentioned in any video is the "runtime" in each cell after it is executed. It would be very nice to see the time displayed at the bottom of each cell automatically after it is executed. I have tried about a dozen recommendations from the Internet, but none of them works! Any reliable suggestion would be greatly appreciated. Thank you.

  29. given_list3 = [7, 5, 4, 3, 3, -2, -3, -5, -7]

    total5 = 0

    for z in given_list3:

    if z <= 0:

    total5 += z

    print(total5)

    cant we do like this answer is same

  30. can someone please explain the concept of the inner for loop and why a[I] is printed out once, twice and three times accordingly? p.s. you're videos are amazing, thank you so much

  31. Hi YK,

    for the problem in Tutorial 6 can u see where my mistake is?

    given_list3 = [7,5,4,4,3,1,-2,-3,-5,-7]
    total6 = 0
    j = 0
    while given_list3[j] < 0 and j < len(given_list3):
    total6 += given_list3[j]
    j += 1
    print(total6)

    this gives me 0, is it because the first index causes it to auto-break?

  32. I can break down each line of the code in his example for the for Loop inside of the for Loop and still can't manage to recreate it without coming straight from memory. I understand that he used the index of each string and added one to it to get how many times it would print ie. Banana in index position 1+1 print 2 times and so on.. but I just can't fully relate all of the info in my head lol

  33. gl9 = [7, 5, 4, 4, 3, 1, -2, -3, -5. -7]

    total9 = 0

    j = len(gl9) – 1 #line 4

    wgile gl9[j] < 0:

    total2 += gl9[j]

    j -= 1 #line 7

    print(total9)

    didn't we start from the end of the list to avoid the positive numbers?
    weren't we supposed to write += instead of -= ?, if so then what was the purpose of line 4?

  34. when am writing this code my output is the series of all individual totals but your output is only the final total 2318 what is the reason?

  35. instead of len(list)-1 you can just set index = -1 and it will start at the end of the list.
    total = 0
    index = -1
    while list[index] < 0:
    total += list[index]
    index -= 1
    total

  36. Has anyone gotten " In [*] : " next to the cell (where you type your code)? What does the * mean?

    This would come up after running a cell code that I was looking to print my answer. Nothing gets printed and it moves on to the next cell… ?

    I read something about the kernel still processing something.

    My solution was closing the kernel and restarting jupyter notebook.

  37. Ok now I got it , i used javascript syntax by accident … thats why I got the wrong answer , but now I get it

  38. # did this on my own
    total3 = 0
    for t in range(1,100):
    if t % 3 == 0 or t % 5 == 0:
    total3 += t
    print(total3)

  39. #tutorial6 , also works for non descending orders .
    givenl_listrr = [ 8,7,9,-2,-3,-1]

    totalo = 0

    i = len(givenl_listrr)-1

    while givenl_listrr [i] < 0:

    totalo += givenl_listrr [i]

    i -= 1

    print(totalo)
    -6 .

  40. Hi YK, I have one problem how one should use while loop when the list is not sorted like list= [-2,20,-43,-54]

  41. Can anyone explain me if I have a list new_list = [23,45,-56,34,56,-67,-87,94] how can I add only negative numbers, and print the total by using "WHILE" loop? Please post ur code because I could easily do it by using for loop but stuck by using WHILE

  42. given_list4 = [7, 5, 4, 4, 3, 1, -2, -3, -5, -7]

    total7 = 0

    a = 0

    for element in given_list4:

    if element < 0:

    total7 += element

    print(total7)
    -17 is this okay or wrong???

  43. given_list = [7, 5, 4, 4, 3, 1, -2, -3, -5, -7]
    total = 0
    w = -1

    while given_list[w] < 0:
    total += given_list[w]
    w -= 1
    print(total)

  44. What to do when we do not want to add repeated elements in first problem (#5 tutorial)?
    AND
    What to do when we want to add repeated elements in first problem (#5 tutorial)?

  45. I like the stuff you cover but you need to show your work a bit more
    thoroughly in terms of the math I watched the " for j in range(I + 1):" like 15 times just to get how you added the list.
    I know it sounds dumb but you would make your tutorial a 100x better with aspects covering that.

  46. Can you please upload a whole playlist where we can be "ZERO TO HERO" in python? if you cant make vidoes ,atleast give me some links or anything from where i can be that :"(

  47. if i use this code
    list=["ball","cat","dog"]

    for i in range(len(list)):
    for j in range(i+1):
    print(list[j])
    i get this result:
    ball

    ball

    cat

    ball

    cat

    dog
    CAN ANYONE TELL ME WHY

  48. YK, I don't exactly understand the "for j in range(i + 1)" or the solution to the problem in tutorial 6. Could you please explain the solutions? I'm having trouble reasoning and I simply don't quite understand.

  49. list1=[]

    N=int(input())

    for i in range(0,N):

    x=int(input())

    list1.append(x)

    print(list1)

    sum=0

    for i in range(len(list1)):

    if (list1[i]<0):

    sum=sum+list1[i]

    print(sum)

  50. The variable 'i' used in the problem from tutorial 5 isn't referring to the index right? Is it referring to the element in the list?

  51. list = [7, 5, 4, 4, 3, 1, -2, -3, -5, -7]
    #sum of all negative numbers
    total = 0
    for i in list:
    if i < 0:
    total = total + i
    print(total)

  52. for i in range(len(a)):

    for j in range(i+1):

    print(a[i])

    Couldn't understand this, can you please explain this?

  53. for i in range (len(a)):# 0,1,2

    for j in range(i + 1):

    print(a[i])

    I put this exact code in and tried to run it, It give me one of each like before, I don't understand what i did wrong?, can anyone clarify my mistake?
    Edit:If there are another way of doing of this code please tell me, I been trying many solutions but don't seem to work as well.

  54. Hello CS dojo, thanks for all the amazing videos. Could you by any chance make a video on some useful shortcuts for Python? I appreciate it!

  55. How can I print a list with comma's in between of all number divizeble by 3 and as a horizontal list, not just printing the result.

  56. Hello YK I just started learning python and your tutorials have been of so much help… Can you please explain the concept behind the looping of multiples of 3 & 5 and summing them up?? (What I think is that multiples of 3 and 5 mean that we should sum only numbers which are divisible by both 3 and 5 at the same time and that will be ) 15, 30, 45, 60, 75 and 90 = 315??

  57. hey cs dojo , i think the solution for the last exercise you gave in this video is a little complicated , i tried it in a different way, i got the same result , please next time , try to give easier solutions , by the way thanks for these videos , its really helping me

  58. So I definitely was overthinking the first exercise and got it wrong….
    This is what I thought the answer was lol:
    a = [ ]

    b = [ ]

    for i in range(1, 101):

    if i % 3 == 0:

    a.append(i)

    if i % 5 == 0:

    b.append(i)

    print(a)

    print(b)

    #ADDING THE MULTIPLES TOGETHER IN EACH LIST

    total4 = 0

    for i in a:

    total4 += i

    print(total4)

    total5 = 0

    for i in b:

    total5 += i

    print(total5)

    #ADDING BOTH LISTS TOGETHER

    print(total4 + total5)

  59. 7:05 I exactly did the same thing. But I thought this is not an easy way because I always solve math problems in very lengthly way. And I also have low confidence.

Leave a Reply

Your email address will not be published. Required fields are marked *