-2

I just started to learn loop and the output of my code triggered me.

The python outputted "9" after I coded "print(number)" and I do not know why.

I tried to figure out but I do not know if it a defult setting or a math concept.

The following is my code.

for number in range(10):
  print(number)
  print("Hello")
  print("Hi there")

for x in range(5):
  print(x)

fav_movies = ["A", "B", "C", "D"]
print(fav_movies)

for movies in fav_movies:
  print(movies)
  print(number)

print(number)

The following is the output.

Hello
Hi there
3
Hello
Hi there
4
Hello
Hi there
5
Hello
Hi there
6
Hello
Hi there
7
Hello
Hi there
8
Hello
Hi there
9
Hello
Hi there
0
1
2
3
4
['A', 'B', 'C', 'D']
A
9
B
9
C
9
D
9
9

Thanks for reading this.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
rnh
  • 1

1 Answers1

1
for movies in fav_movies:
  print(movies)
  print(number)

Here's is your issue: the value of number was set in the first loop, and its final value was 9 (because range(10) goes from 0 to 9). Since you didn't modify the value of number after the first loop, it remains 9 during the third loop.