-6

If I have the code

i = 0
while i < N:
    print("Hello")
    i += 1

how many times will Hello be printed out? (assume that N is a defined integer)

Answers:

  1. 0
  2. N
  3. N-1
  4. N+1
  5. more than N+1

and why? I never get this so I would appreciate of somebody could explain.

Jared
  • 25,627
  • 7
  • 56
  • 61
Eri.
  • 465
  • 2
  • 6
  • 14
  • It would be printed N times. i starts at 0. Your condition demands that the loop exit if i is not less then N. But because your index starts at 0, it will be printed exactly N times. Try replacing "Hello" with the variable i. I think that will put things in perspective. – Gabriel Samfira Jul 06 '13 at 20:49
  • Have you tried to work it out starting from your understanding of the `while` loop? – user4815162342 Jul 06 '13 at 20:49
  • This is easy to try: http://ideone.com/N6SU1N – Lasse V. Karlsen Jul 06 '13 at 20:52
  • 1
    This feels like a test question... – JcKelley Jul 06 '13 at 20:54
  • 1
    It's not a freaking test question dude... – Eri. Jul 06 '13 at 20:58
  • 1
    Relax lol, everyone has to start off somewhere. In time loops will become second nature, and don't be disheartened by any nasty comments. They come from people who have forgotten that they once had to get their head around this. – Adrian Trainor Jul 06 '13 at 21:06

3 Answers3

5

The best way to figure it out is to go through it by hand for a few manageable values of N. For instance, if N is 2:

  • i == 0 and 0 < 2 → print "hello", increment i
  • i == 1 and 1 < 2 → print "hello", increment i
  • i == 2 and 2 < 2while-loop condition is no longer satisfied → loop ends

So for N = 2, "hello" is printed 2 times. See the pattern?

arshajii
  • 127,459
  • 24
  • 238
  • 287
2

Hello will be printed out N times. assume N is 3.

1st iteration i = 0 i is less than N

print hello
i = i + 1; // i = 1

2nd iteration i = 1; i` is less thanN (3)`

print hello
i = i + 1; // i = 2

3rd iteration i = 2; i is less than N (3)

print hello
i = i + 1; // i = 3

4th iteration i = 3; i is equal to N (3) break loop

Adrian Trainor
  • 267
  • 1
  • 9
2

As the other answers described, it would print N times, because it starts at 0 and goes until it is just before N, not equal to N.

In reality, though, this is very redundant in Python. A much easier way to do this, making it a bit more readable (and hopefully easier for you to understand):

N=3
for x in range(0,N):
    print "This is loop %d" % (x)

This loop will print from 0 to N, which is really just N amount of times.

JcKelley
  • 1,954
  • 1
  • 15
  • 30