Home > Net >  I need help writing a program that prints out two shapes next to each other using nested loops
I need help writing a program that prints out two shapes next to each other using nested loops

Time:10-04

I need two print two triangle shapes next to each other using for loops in python

CodePudding user response:

For each row you need to print

  • stars an amount of times that is the row index starting at 1
  • spaces to complete to the total size
  • then the 2 previous the other way
  • with a space in the middle, given by print between the 2 parts
def print_valley(size):
    for row in range(1, 1   size):
        print("*" * row   " " * (size - row),
              " " * (size - row)   "*" * row)

A maybe more easy to understand version

def print_valley(size):
    for row in range(1, 1   size):
        star = "*" * row
        space = " " * (size - row)
        print(star   space, space   star)

CodePudding user response:

This can be solved using a recursive approach as well. You can invert the printing of levels like the solution below.

def line_print(samples, level=0):
    if samples == 0:
        return
    line_print(samples-1, level 1)
    print(f"{'*'*samples}{' '* level*2} {'*'*samples}")

# Call the function with needed levels
line_print(5)
  • Related