Hello, I’m currently doing this quiz:
There’s a piece of code that looks like this;
for i in range(len(word)):
if i % 2 == 0:
My first question is why does it use range(len()) instead just for i in word?
My other, bigger question is how is it possible to use modulo on a string. i in this code corresponds to a singular character from a string that is being iterated through, so how come modulo operator is able to do a mathematical calculation on a string?
are you certain
i variable contains a string? Have you tried to run the code and
print(i) to see what the value of
i is each iteration of the loop?
When I see variable
i, the first thing that often comes to mind is
How does the code know that i is for index? Is it a method in Python, like “i” means for compiler that we mean index?
Edit: wait, is it because of range(len())? Since range gives us numbers and len(word) is not direct reference to “word” string (it just uses word to get numer of indexes code has to iterate through) code will just iterate through set of numbers and when it comes up to odd numer it will print the letter that is stored at the same index in a string we are passing as a parameter!
It feels nice to realize this by myself, I could delete it but I’ll leave it for future generations of dummies xD
it doesn’t, but
i often a commonly used variable name to indicate/abbriviate an
Yes. But its important to understand how this works.
len() are both built-in functions.
len() returns the length, which is then used by
You learned about the range() function, right?
so yes, you got there yourself Gaining the insight yourself is very valuable. For the next time, when something like this happens, see if you can gain insight yourself by for example printing
len() (or whatever it is you run into
or use a debugger, can also be really useful to gain insight into code.
What’s a debugger? I don’t think it was covered yet.
something like this:
some editors (like Pycharm and Vscode) have debuggers included, you can put breakpoints in your code (causing the code to pause at that point), at which point you can step through your code
really useful when your codebase starts to grow and you need to debug.
I don’t think I understood your explanation (what would I gain by pausing code execution, how it will help me understand whats going on?) but debugger will be covered later in Python course, right?
I tried using pythontutor, most of the time when i click next step it just goes like 10 steps or something further without letting me see what’s happening in between
no, it is something you will have to learn on your own. Well, if we pause the program, we inspect the state of the program as well Like the values of variables.
are sure you press the right button? There also is a last step button, sounds like you press that