This exercise shows the nested loop using the variable from the outer loop. Does the nested loop always need to use the variable from the outer loop?
Answer
No, the nested loop doesn’t HAVE to use the variable from the outer loop. Although this is the most common application for a nested loop, it’s completely fine to have the nested loop perform some activity that does not involve the variable from the outer loop.
The following example shows two loops which both iterate over range() lists to produce a grid pattern. The nested loop operates independently of the outer loop variable.
for x in range(5):
for y in range(5):
print("X ",end='')
print()
The magic is in the print statement which directs the console to keep the pencil on the same line during iteration of each row (each value of x). The print statement that follows that directs the pencil to start on the next line when x changes.
We should note that x and y have reversed roles in @janneslohmeijer’s example. Technically your code would be,
for y in range(5):
for x in range(5):
print ("X ", end='')
print ()
such that the y-axis represents the row number, and the x-axis represents the column number. A minor point, but worth consideration.
That is not part of a loop, it is an argument to the print function.
You can run help(print)
or search the web for print’s documentation, to find out what print does with that argument.
I didn’t know you could do the help(print) and get instructions on different features within the print function that can be utilized… end=’’ helped me solve a hackerrank puzzle that had me scratching my head… thanks mate <3
The print statements in the inner loop have no newline characters so everything prints on one line. The last print inside of the outer loop is to reset the pencil to a new line.