0

How to do loop like: for(i = 0; i < 100; i++)?

This code is in PHP, i want create this loop like in Python 3x.

Thanks my brothers for any what you do for me.

2

3 Answers 3

2

Use the built-in range function which takes an optional step and an interval [a, b) like so:

for i in range(0, 100, 1):
    # do something
Sign up to request clarification or add additional context in comments.

1 Comment

As seen in Vaibhav's answer, you can condense to one argument but I wanted to show you the existence of three, two of which are optional.
2

A range based for loop in python is not equivalent to C like for loop that is prevalent in javascript, php or languages as such which supports them. Particularly, the distinction comes in

  • when the need comes to change the iterator variable inside the loop block
  • Condition is more complex beyond a limiting condition

Ideally the best alternative is to re-write the for loop to a while loop in the similar way as you would have written in languages that supports both. For example

for(<initializer>; <cond>; <increment>) {
    // Loop Body
}

should equivalently be written as

<initializer>
while cond:
    <Loop Body>
    <increment>

so in your particular case, the equivalent of the php for(i = 0; i < 100; i++) construct in python would be

i = 0
while i < 100:
    # Loop Body
    i += 1

Using any other construct might have some surprising consequences.

2 Comments

Based on the example in the OP, he intends for a static, fixed loop. So range would be acceptable unless there is an unpredictable assignment of the sentry in the loop.
@MalikBrahimi: We have not seen is entire code, so whether it is sufficient would be too early to predict. Range based loop is equivalent to a foreach loop, that most modern languages supports to a varied way.
0
for i in range(100):
    # code here

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.