1

As you should know, in Python, the following is a valid for loop in Python:

animals = [ 'dog', 'cat', 'horse' ] # Could also be a dictionary, tuple, etc

for animal in animals:
    print animal + " is an animal!"

And this is usually fine. But in my case, I want to make a for loop like the way you would in C/C++/Java etc. The for loop that looks like this:

for (int x = 0; x <= 10; x++) {
    print x
}

How could I do something like this in Python? Would I have to set up something like this, or is there an actual way to do this that I'm missing (I've googled for a good few weeks):

i = 0

while i is not 10:
    print i

Or is there a standard of how to do this? I find the above does not always work. Yes, for the case of the above I could do:

for i in range(10):
    print i

But in my case I can't do this.

11
  • 4
    Why can you not do for i in range(10)? Commented Oct 14, 2013 at 17:25
  • I'm making snake and I need to loop through the entire grid. I can't use range for this. Commented Oct 14, 2013 at 17:26
  • 4
    Why don't you want to make an 'actual' C-style loop in SQL? Well, you could, but it would be contrived and against the language's idioms and best practices. Same thing with Python. It pays to actually learn a language, not just map it 1:1 to a previously-known language. Commented Oct 14, 2013 at 17:51
  • 4
    The problem is, C does not have "an actual FOR loop" and Python does. The FOR loop, as defined in ALGOL, is about iterating over a defined range of elements. C borrowed the name, but not the required behavior. (It's impossible to get into an infnite loop in a real FOR loop, for example, whereas C's FOR loops can do for(;;).) What C calls a FOR is nothing but a WHILE loop with weird syntax, and you can implement any C FOR loop as a WHILE loop without much difficulty. Commented Oct 14, 2013 at 19:19
  • 2
    This seems like a typical case of the xy problem. You had the perfectly correct solution — using range — and "it didn't work", although "in Java it worked fine." Instead of debugging the code to find why it didn't work, you concluded that the problem is in the lack of an "actual" for loop and asked a question to that effect. The responders are answering the question you asked to the best of their ability, but that does nothing to resolve your problem, which lies elsewhere. Please find the actual problem and, if you still have a question, ask it here. Commented Oct 15, 2013 at 8:47

2 Answers 2

9

I guess from your comment that you're trying to loop over grid indices. Here are some ways:

Plain simple double for loops:

for i in xrange(width):
    for j in xrange(height):
         blah

Using itertools.product

for i, j in itertools.product(xrange(width), xrange(height)):
     blah

Using numpy if you can

x, y = numpy.meshgrid(width, height)
for i, j in itertools.izip(x.reshape(width * height), y.reshape(width * height):
    blah
Sign up to request clarification or add additional context in comments.

1 Comment

...and don't forget enumerate
9

Why would you need a C-style index-tracking loop? I can imagine a few cases.

# Printing an index
for index, name in enumerate(['cat', 'dog', 'horse']):
  print "Animal #%d is %s" % (index, name)

# Accessing things by index for some reason
animals = ['cat', 'dog', 'horse']
for index in range(len(animals)):
  previous = "Nothing" if index == 0 else animals[index - 1]
  print "%s goes before %s" % (previous, animals[index])

# Filtering by index for some contrived reason
for index, name in enumerate(['cat', 'dog', 'horse']):
  if index == 13:
    print "I am not telling you about the unlucky animal"
    continue  # see, just like C
  print "Animal #%d is %s" % (index, name)

If you're hell-bent on emulating a counter-tracking loop, you've got a Turing-complete language, and this can be done:

# ...but why?
counter = 0
while counter < upper_bound:
  # do stuff
  counter += 1

If you feel compelled to reassign the loop counter variable mid-loop, chances are high that you're doing it wrong, be it a C loop or a Python loop.

2 Comments

Well maybe I am doing it wrong. Here's what I need to do in Java: for (int x = BOX_WIDTH; x < GRID_WIDTH * BOX_WIDTH; x++) { //Do Stuff }
@Eamonn: this is easily done as for x in range(BOX_WIDTH, GRID_WIDTH * BOX_WIDTH): ... # do stuff. The stuff will be done for each value of x such that BOX_WIDTHx < GRID_WIDTH * BOX_WIDTH.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.