Hello all. I apologize in advanced if this has been asked before but I have not been able to find this information via google or searching here. Everything I found is related to how a for loop works. I know how to use a for loop in python and what my input will do and what the output will be. My question is more related to how the syntax itself actually works:

I have the very basic example:

for i in range(10):
    print i

I know that this will print 0 through 9 one at a time and that is the expected output and why it starts at 0 and not 1 and why it ends at 9. My question is more related to how the interpreter knows that "i" is meant for iteration (since I can technically use whatever variable I want) when "i" has no declared value and I never declare i++ or i.next

Recommended Answers

All 3 Replies

I think you need to step back a second and think that this is not C++. for loops in python are different. They move through what's after the key word "in". So to see what it will iterate through, list that range(10).

Try this one liner in python

list(range(10))

Now try that with range(1,11)

Thank you rproffitt. Let me get this straight: "i" is a variable that is based on the reference itself (range(10)). if it were not for range() (or another item) "i" would be meaningless?

I think you're getting it. i gets whatever is in the set of things you after the "in" keyword. It can be numbers, a list of things, and so on. No i++ here.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.