Can anyone please help explain what the hell is going on with this code and why it is printing ‘Hello Hi’ two times every time?Questionable Code
Advertisement
Answer
The submitted code is doing 2 things. First, in :
for x in range(0,4): print(x)
The code is iterating through (0,1,2,3), and printing its current value. This seems to be intended.
Then, within this loop, in:
for x in y: print(y)
The code is iterating through the elements of y, which is [“Hello”, “Hi”], and printing y back each time. So the loop iterates twice, and each time it prints out all of y, so it prints [“Hello”, “Hi”].
Your question leads me to believe that you are trying to produce code that prints the elements of y seperately, and so something like this may be what you are looking for:
y = ["Hello", "Hi"] for i in range(0,4): print(i) for j in y: print(j)
This will output:
0 Hello Hi 1 Hello Hi 2 Hello Hi 3 Hello Hi