-4
1  def print_range(start, end):
2     # Loop through the numbers from start to end
3   n = start
4   while n <= end:
5       print(n)
6  print_range(1, 5)  # Should print 1 2 3 4 5 (each number on its own line) 

Line 6 should print "1 2 3 4 5" (each number on its own line), but doesn't. Why is that?

LorenzBung
  • 406
  • 1
  • 5
  • 15
Joan
  • 1
  • 1
  • 2

2 Answers2

2

n always has the value of start, because it is never incremented in the while loop. In comparison to the for-loop, the while doesn't automatically change the variable you iterate over.

So, you need between lines 5 and 6:

n += 1
LorenzBung
  • 406
  • 1
  • 5
  • 15
1
 1  def print_range(start, end):
 2    n = start
 3    while n <= end:
 4      print(n)
 5      n+=1
 6  print_range(1, 5)  # Should print 1 2 3 4 5 (each number on its own line)
Elletlar
  • 2,991
  • 7
  • 29
  • 34
Chirag
  • 11
  • 3