'I am a beginner.Help out with this question.The following code causes an infinite loop. Can you figure out what’s missing and how to fix it?
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?
Solution 1:[1]
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
Solution 2:[2]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | LorenzBung |
| Solution 2 | Elletlar |
