-1

I am looking for loop similar to other languages PERL/TCL/C++ in python.

Like in TCL below is the for loop

for { set i 0 } { $i < $n } { incr i} {

#I like to increment i value manually too like
if certain condition is true then increment
set i = [expr i+1] # in some cases
print i

I there similar way in python too. In python i know below is the for loop syntax

for i in var1
#How to increment var1 index manually in some scenarios
3
  • 1
    replace var1 in your example with range(0, n, 1) Commented Jul 17, 2017 at 16:25
  • @DaleWilson: It will increment by one each time. But if we want to increment based on conditions like some scenarios increment by 2 Commented Jul 17, 2017 at 16:29
  • 1
    Possible duplicate of How do I use a C-style for loop in Python? Commented Jul 17, 2017 at 16:31

3 Answers 3

2

Use:

for i in range(0, n):
 # Do something

Also, you could use:

i = 0
while i<n:
 # Do something
 i+=1
Sign up to request clarification or add additional context in comments.

4 Comments

If we want to skip some iterations manually inside for loop can we do that
Yes, but you will have the next number.
Put if-statement where you need.
The theme here is "Use the right tool for the job!" If the increment is uniform, use a for If it needs to be customized, use a while
1

Python's range function, called like range(b, e, i) will yield integers starting with b and ending at e, incrementing by i each time.

3 Comments

How to increment in if some conditions are true
Add an if block for each iteration. If the condition doesn't evaluate to True, you can use continue to move to the next iteration.
It sounds like, if you also want to be able to manually increment i, use a while loop
1

Python doesn't have that style of for loop, so use a while loop.

i = 0
while i < n:
    # ...
    if some_condition: # Extra increment
        i += 1
    i += 1 # normal increment

1 Comment

Yes while loop I am aware of. I thought there is something in the for loop that I am missing. Thanks for clarification

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.