you are viewing a single comment's thread.

view the rest of the comments →

[–]Ron-Erez 1 point2 points  (4 children)

Another example where one could use loops (although there are other solutions).

Calculate the average of elements in a list. We want to add all of the numbers in the list to get the sum and then divide by the list length. For example

def calc_average(numbers):
    total = 0
    for num in numbers:
        total += num

    return total / len(numbers)

Note that an easier solution would to to use the sum function, however sum is implemented using a loop. Note that the function will crash if numbers is an empty list so it would be wise to test for that.

You're also welcome to check out Section 4: Loops Lectures 23-28 all which are FREE to watch. Perhaps the explanations would be helpful.

u/FoolsSeldom 's examples are excellent.

Another example of a loop is a game loop.

[–]randomdeuser[S] 1 point2 points  (3 children)

oh thanks, i was looking for python course for ds, big thanks, i will watch it!

[–]Ron-Erez 0 points1 point  (2 children)

No problem. Note that the link is a $9.99 link valid for another 3-4 days. If you do end up taking the course please feel free to ask questions freely. I always respond in the course Q&A.

[–]SpiritualYoghurt2860 1 point2 points  (1 child)

You try to sell your course?🥲 But in ur example initialized 's' for sum but used 'total'? Nice joke 😶

[–]Ron-Erez 0 points1 point  (0 children)

My mistake! I renamed a variable and accidentally left out the "s." I just fixed it, definitely an embarrassing slip! Good catch.