python classic 100 questions - printing stairs

Method 1: Use loop printing

Idea: Use two for loops to control the position of printing stairs and smiley faces respectively. The outer loop controls the number of stair lines, and the inner loop controls the number of * numbers printed in each line.

Code:

# 打印楼梯
for i in range(1, 6):
  print("*" * i)

# 打印笑脸
print("  **   **")
print(" *  * *  *")
print("*    *    *")
print("*         *")
print("*    *    *")
print(" *  * *  *")
print("  **   **")

Method 2: Use recursive printing

Idea: Use a recursive function to control the number of lines for printing stairs and the number of * numbers in each line. After printing the stairs, use the printing function to print the smiley face.

Code:

# 定义递归函数打印楼梯
def print_stair(n):
  if n <= 0:
    return
  print_stair(n-1)
  print("*" * n)

# 打印楼梯
print_stair(5)

# 打印笑脸
def print_smile():
  print("  **   **")
  print(" *  * *  *")
  print("*    *    *")
  print("*         *")
  print("*    *    *")
  print(" *  * *  *")
  print("  **   **")

print_smile()

Method 3: Use list comprehension printing

Idea: Use list derivation to control the number of lines for printing stairs and the number of * numbers in each line. After printing the stairs, print the smiley face through the printing function.

Code:

# 打印楼梯
stair_list = ["*" * i for i in range(1, 6)]
print("\n".join(stair_list))

# 打印笑脸
def print_smile():
  print("  **   **")
  print(" *  * *  *")
  print("*    *    *")
  print("*         *")
  print("*    *    *")
  print(" *  * *  *")
  print("  **   **")

print_smile()

Of course, there should be more implementation methods. This article just provides an idea. I hope everyone can brainstorm.

 

Guess you like

Origin blog.csdn.net/yechuanhui/article/details/132835387