0

It seems to me that the two statements below do the same exact thing in python3.

while i < x:
    print("hi")
    i+=1

and

for i in range(x):
    print("hi")

Is there a functional difference that I'm missing here?

If so, in what cases would you use one over the other?

martineau
  • 119,623
  • 25
  • 170
  • 301
Arete
  • 13
  • 2

1 Answers1

4

Usually while is used when you don't know exactly when you want to stop. For loop is used when you know how many times you want to perform something.

For example : You have a number, every loop you do some calculation and stop only when the result smaller than a given limit, you need tu use while as you don't know how many time you have to run the function.

In the other hand if you want to go thru n-element of a list, you can use a while but a for is more logical as you know the size of the list.

In your example there is no difference (or maybe only based on performances, timeit can give you more information)

Edit 1 I tried to do the same function with while and for (10000 times the sum of integer from 0 to 15) and for loop is faster. If you can use it, you should choose this one (there is also less variable to set):

Version for

s = time.time()
for i in range(10000):
    t = 0
    for j in range(15):
        t += j
print(time.time()-s) => 0.0132s

Version while

s = time.time()
i = 0
while i < 10000:
    t = 0
    j = 0
    i += 1
    while j < 15:
        t += j
        j += 1

print(time.time()-s) => 0.0202s

One important point also... with a while you can have an infinite loop, with for it's impossible :p

Nicolas M.
  • 1,472
  • 1
  • 13
  • 26
  • 3
    Strictly it's also possible to have an infinite loop with `for x in y:` - `y` can be a generator that doesn't end. – Joe P Jun 04 '17 at 23:06
  • You are right :) I never thought about that ! But you probably also need an "incorrect" while in the generator right ? – Nicolas M. Jun 04 '17 at 23:15
  • If you substitute `xrange` for `range` (in Python 2 - `range` works like this in Python 3 anyway) you get a slightly faster time. And more efficient memory utilisation. – Joe P Jun 04 '17 at 23:20
  • The loop would have to have some other way of exiting - even if it's just KeyboardInterrupt! The generator could just yield even numbers, primes, whatever, it doesn't need to end. – Joe P Jun 04 '17 at 23:23