Question

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.

Was it helpful?

Solution 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

OTHER TIPS

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?

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top