Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

for loop in Python

In C/C++, I can have the following loop

for(int k = 1; k <= c; k += 2)

How do the same thing in Python?

I can do this

for k in range(1, c):

In Python, which would be identical to

for(int k = 1; k <= c; k++)

in C/C++.

Answer*

Draft saved
Draft discarded
Cancel
3
  • 4
    Nothing in the question (right back to the first revision) says anything about iterating through array or even mentions an array at all. For-loops aren't just for iterating through arrays, they're also used for counting. What if you wanted to simply print "Hello World" five times? How would you do that without a counter? 🤨 Commented May 19, 2020 at 1:21
  • That's true, but I never said "never use range". My two suggestions start with "if". Iterating "directly" rather than via an integer variable is one of the things everyone has to un-learn when coming to Python. At least 90% of the time I see a junior programmer write for i in range, the correct refactoring is to get rid of range. The accepted answer makes me believe that was true here, as well. It's also interesting to note that the idiomatic way to do "just counting" in python (for i in range(x):) is actually iterating through a list of integers, rather than incrementing a counter. Commented Aug 8, 2020 at 20:02
  • Just for fun: print("\n".join(["Hello, world!"] * 5)) Commented Aug 8, 2020 at 20:04

lang-py

AltStyle によって変換されたページ (->オリジナル) /