Test | Result |
triangle_stars(3) | * 1 * * 2 * * * 3 * * 2 * 1 |
triangle_stars(5) | * 1 * * 2 * * * 3 * * * * 4 * * * * * 5 * * * * 4 * * * 3 * * 2 * 1 |
n=5;
for i in range(1,n+1,+1): # note the use of the range function, to generate a list equal to [1,2,....,n,n+1]
for j in range(i):
print ("* ", end="") #note the use of the end function, which replaces the default /n with "".
print(i)
Using all your knowledge of loops so far, make the following additions to the above code:
- wrap the loop in a function triangle_stars(int), that takes an integer input of any positive value
- fix the bug in the code that causes it to print one fewer rows of stars than needed (eg with the integer 5, it should print 5 rows of stars, from 1 to 5. The code currently prints 4 rows).
- add another pair of nested for loops within the same function, which print the same thing but flipped, (ie a decreasing number of stars).
- finally, at the end of every row, print the total number of stars in that row (no 0's).
- NB that the middle row of stars should only be printed once
also note that the range function can be run to generate a count down, using the form: range(start,stop,-1), and that it should probably be used to make your upside down triangle.
下一篇揭晓答案