Python exercise 018: Print asterisks and python018
[Python exercise 018]Print the example (diamond ):
* *** ************ ***** *** *
----------------------------------------------
This is simple. You only need to know the built-in method str of Python. center (width [, fillchar]) can be easily printed: str is an asterisk with varying numbers, width is the maximum width (7 spaces), and the default fill character fillchar is a space. Two for loops! The Code is as follows:
s = '*'for i in range(1, 8, 2): print((s*i).center(7))for i in reversed(range(1, 6, 2)): print((s*i).center(7))
For the output result, see the question.
[Updated on ]--------------------------------------------
Of course, it is not difficult to solve the str. center () problem. It is simply to calculate the number of spaces. The Code is as follows:
s = '*'for i in range(1,8,2): t = (7-i)//2 print(' '*t + s*i + ' '*t)for i in reversed(range(1,6,2)): t = (7-i)//2 print(' '*t + s*i + ' '*t)
++
Source: getting started with programming languages: 100 typical examples [Python]