How can I make a triangle of hashes upside-down in python

Question:

I have to do a hash triangle using this function:

def line(num=int, word=str):
   if word == "":
       print("*" * num)
   else:
       print(word[0] * num)

Here is the code i have:

def line(num=int, word=str):
    if word == "":
        print("*" * num)
    else:
        print(word[0] * num)

def triangle(size):
    # You should call function line here with proper parameters
    
    while size > 0:
        
        line(size, "#")
        size -= 1

the output is this:

######
#####
#### 
###  
##   
# 

but it should be this:

#
##
###
####
#####
######

how can i modify it so it prints that?

Asked By: Wolfie

||

Answers:

You are starting from size and going to 1 you should do the opposite:

i = 0
while i <= size:
    i += 1
    ...

Also for i in range(1, size + 1) would be more pythonic 😉

Answered By: yjay

Slightly adjusted your code

def line(num=int, word=str):
  if word == "":
    print("*" * num)
  else:
    print(word[0] * num)

def triangle(size):
  # You should call function line here with proper parameters
  charPerLine = 1
  while charPerLine <= size:
      line(charPerLine, "#")
      charPerLine += 1
        
        
triangle(5)
Answered By: Gro
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.