Lesson Python Song-day teacher training third question:
Code written with "*" triangle
The answer should be only two lines of code:
#三角形输出
n = eval(input())
for i in range(1,n+1,2):
print("{0:^{1}}".format("*" * i,n))
Digital input 13, out
Code analysis:
n = eval(input())
Call the eval () function, the evaluation function, the outermost string of open double quotes become digital
for i in range(1,n+1,2):
print("{0:^{1}}".format("*" * i,n))
The key is to use the groove within the groove, determined Videos "*" number of the external grooves {}, n to determine the line width, line broadest width as each row
Further: How to output a diamond?
#三角形输出
#菱形输出
n = eval(input())
for i in range(1,n+1,2):
print("{0:^{1}}".format("*" * i,n+1))
for i in range(n-1,1,-2):
print("{0:^{1}}".format("*" * (i-1),n+1))
Triangle becomes a rhombus, primarily then draw an inverted triangle, then the bottom line less than positive triangle.
for i in range(n-1,1,-2):
print("{0:^{1}}".format("*" * (i-1),n+1))
This is printing
Add these two lines similar meaning and draw an equilateral triangle, it is mainly pay attention for in the reverse order. From large to small, can reverse the front and rear, the step size will be changed to -2.
When printing, for in changed from n-2, may be used.
for i in range(n-2,1,-2):
print("{0:^{1}}".format("*" * (i),n+1))
Such subsequent print function to print, can start directly from i.
Print a problem, because in that case, one is not included.
It will come out of this pattern:
* The last line is not so modify the code again, the 1 to 0, test.
#菱形输出
n = eval(input())
for i in range(1,n+1,2):
print("{0:^{1}}".format("*" * i,n+1))
for i in range(n-2,0,-2):
print("{0:^{1}}".format("*" * (i),n+1))
The final output of the results:
perfect.