简体   繁体   中英

Printing pattern using for loop

Hello I need to print a pattern using # and - by writing an iterative code Eg printpattern(3) should give output #-#—-#—-- Not sure how to add a # in front each time Tried using a for loop and ended up with #-#--#--

heres what i got:

def printpattern(number):
    count="-"
    x="#-"
    for i in range(1,number):
        count=x+count*i
    return count

The Following should work...

n = int(input("Enter n : "))

for i in range(n):
   res = "#-"

   for j in range(i):
      res += "-"

   print(res, end="")

You could try adding the '#' before adding the '-' symbol 'n' number of times. The sample code would look something like this:

inp = int(input("Enter size: "))
a='#'
b='-'
pat=''

for i in range(1,inp+1):
   pat = pat+a
   pat = pat+(b*i)

print(pat)
def printpattern(number): count = '' for i in range(1, number + 1): count += '#' + ('-' * i) return count if __name__ == '__main__': print(printpattern(3))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM