Why does this code:
n = int(raw_input("How many rows? "))
for row in xrange(n):
for col in xrange(row+1):
print "*",
print
Display this result (when n = 5)?
*
* *
* * *
* * * *
* * * * *
EDIT – I don’t understand how step by step it gets this form. Does col mean the number of columns? Because it doesn’t make sense as the number of columns is equal to the number of rows even though the input for columns is (rows+1).
Well, let’s go line-by-line and think like we’re the computer.
n = int(raw_input("How many rows? "))We get what the users inputs, convert it to an integer, and store the result inn.for row in xrange(n):We’re looping overxrange(n), which is more or less the same as[0, 1, 2, 3, 4](althoughxrangedoesn’t store the full list at once, and so is more memory efficient). So now we know that whenever we seerowin the future, we have to replace it with whichever one of those numbers we’re on.for col in xrange(row+1):This line is similar to the last one; nowcolis one of the values in a list counting from0to the value stored inrow. So ifrowis2on this iteration of the outer loop, the inner loop will run 3 times. The first timecolwill equal0, the second1, and the third time it will equal2. (For each of thosecolvalues,rowwill stay2, sincerowonly changes when the outer loop goes through an iteration.)print "*",This is where the*s actually get printed. The tricky bit here is the comma at the end of the line. Aprintstatement without a comma just prints something and then moves to the next line. When you add the comma, it basically prints the line but adds a space after the line instead of a new line (\n). So, since this line is called for eachcolvalue, it will print a*followed by a space on one line for eachcolvalue.printNotice that this is not inside the col loop. This statement just prints a newline. The idea here is to print a new line after each row has been printed so that the*s of the next rows are added to a new line, rather than to the previous line. If thisprintweren’t here, all of the stars would be printed on a single line.So, for each
rowvalue, this program printsrow+1number of*s on one row.In response to question edit:
I could see how
colcould be a confusing name.colis just the current column number of the*being printed. To see this more clearly, try replacingprint "*",withprint col,. You should get the following:(Remember that
range(3)produces[0,1,2], whilerange(3+1)produces[0,1,2,3].)