In the process of learning and developing the use of language looping statements, various shapes are often printed to verify the proficiency of the looping statements, followed by the use of Python to print a variety of shape exercises.
In the following example: variable i controls the outer loop (number of graphic lines), J controls the number of spaces, K controls the number of asterisks (*)
1. Printing triangles
1.1 Printing Right Triangle
#/usr/bin/pythonrows = Int (Raw_input ('Please input a rows:')) I=j=k=1ifRows >= 3: forIinchRange (0,rows+1): forKinchRange (0,i):Print '*', # Note Here ",", must not be omitted, can play the role of non-newline K= K+1Print '\ n'I= I+1Else: Print('Please enter a number, greater than or equal to 3,thank you!')
1.2 Print Hollow equilateral triangle
#/usr/bin/pythonrows = Int (Raw_input ('Please input a rows:')) forIinchRange (0,rows): forJinchRange (0,rows-i-1): Print " ", J+ = 1 forKinchRange (0,2*i+1): ifK = = 0orK = =I:Print "*", Else: ifI+1==rows andk%2==0:Print "*", Else: Print " ", K+ = 1Print "\ n"I+ = 1
2. Print Diamond
2.1 Printing a solid diamond
#/usr/bin/pythonrows = Int (Raw_input ('Please input a rows that rather than 2:')) forIinchRange (0,rows): forJinchRange (0,rows-(i+1)): Print " ", J+ = 1 forKinchRange (0, (rows-1) *i+1): ifK>=2*i+1 : Print " ", Else: Print "*", K+ = 1Print "\ n"I+ = 1 forIinchRange (0,rows-1): forJinchRange (0,i+1): Print " ", J+ = 1 forKinchRange (0,2* (rows-1)-i)-1): Print "*", K+ = 1Print "\ n"I+ = 1
2.2 Print Hollow Diamond
# Print a hollow diamond first print the upper part rows row, in print the lower half of the rows-1 line
#/usr/bin/pythonrows = Int (Raw_input ('Please input a rows:')) forIinchRange (0,rows): forJinchRange (0,rows-(i+1)): Print " ", J+ = 1 forKinchRange (0, (rows-1) *i+1): ifK = = 0orK = =I:Print "*", Else: Print " ", K+ = 1Print "\ n"I+ = 1 forIinchRange (0,rows-1): forJinchRange (0,i+1): Print " ", J+ = 1 forKinchRange (0,2* (rows-1)-i)-1): ifK = = 0orK==2* ((rows-1)-i)-2: Print "*", Else: Print " ", K+ = 1Print "\ n"I+ = 1
# Some friends on the Internet print the upper half of the Rows-1 line, then print the lower half of the rows
#/usr/bin/pythonrows = Int (Raw_input ('Please input a rows:')) forIinchRange (0,rows): forJinchRange (0,rows-i):Print " ", J+ = 1 forKinchRange (0,2*i-1): ifK = = 0orK = = 2*i-2: Print "*", Else: Print " ", K+ = 1Print "\ n"I+ = 1 forIinchRange (0,rows): forJinchRange (0,i):Print " ", J+ = 1 forKinchRange (0,2* (rows-i)-1): ifK = = 0orK = = (rows-i)-2: Print "*", Else: Print " ", K+ = 1Print "\ n"I+ = 1
Use loop statements in Python to print triangles, diamonds