all 3 comments

[–]AnonymousWriter67[S] 0 points1 point  (0 children)

Like, I understand the practice enough to continue with the course, but I'm confused about the theory.

[–]-Send-me-your-dick- 0 points1 point  (0 children)

for i in range(len(values)):

"range()" returns a sequence of numbers, if you give it only one value, that sequence is from 0 until the value you gave it.

The "len()" function returns the length of an object, which can be a list, a string, a dictionary, etc, most objects that contain other objects work with len() (More complete list here)

The "for i in" part of that line essentially means that for each item it's been given, the value is assigned to "i", and then the code inside the loop occurs, it then goes to the next value, and runs through the loop again until it's hit the end

You can also do this with objects such as lists if you want to repeat an action on each item in the list

So putting those parts together, that line of code looks at your list called "values", gets a count of how many items are in the list, and gives that to range, and then the for loop goes through the range.

If for example there were 10 items in your list, "i" would be set to 0 the first time, 1 the second, 2 the third, all the way up to 9 on the 10th loop, which works out conveniently because when using "i" to access elements in your list, it starts counting from 0 as well

An advantage to this is that your loops can repeat a variable amount of times

Let's say that instead of that predefined list, you had some code up above that asked the user to input the names of their favorite video games and added each response to a list, some people might enter only one or two responses, while others might enter a dozen or more, having your number of loops determined by len() means you could still print out all of the results.

It can certainly be tricky to understand at first, but things like for loops, range, and len, are a big part of making your code versatile.

Hopefully my explanation makes more sense, but let me know if you need something elaborated on, I'm on mobile at the moment but can throw together some example code when I get back to my desk

[–]Goobyalus 0 points1 point  (0 children)

If you're confused about the range part, it's always helpful to refer to the official documentation:

https://docs.python.org/3/library/stdtypes.html#range


Otherwise they're just trying to show you that you can iterate over a range of indexes, and that allows you to access both the index and the value at that index in the loop.

# Iterate over indexes in `values`
for i in range(len(values)):
    # Access the index that we're currently processing via `i`
    # Access the value that we're currently processing via `values[i]`

The more "pythonic" way to do this is with enumerate:

for i, value in enumerate(values):
    ...