Reputation: 53
I'm doing a beginners course on python 3 and have to form a asterisk triangle that outputs like the following.Asterisk triangle format
My attempt so far looks as follows:
def printRow(c, length) :
line = c * length
print(line)
myLen = 0
stars ="*"
n = myLen-1
spaces = (' '*n)
myLen = int(input("Enter number to make triangle: "))
if myLen<=0 :
print("The value you entered is too small to display a triangle")
elif myLen>=40 :
print("the value you entered is too big to display on a shell window")
while myLen>0 :
print(spaces, stars, myLen)
myLen = myLen-1
This is what it outputs in the shell
From this point I was quite lost, so any help would be appreciated.
Upvotes: 1
Views: 1886
Reputation: 427
This would work for you.
def printer(n):
space=" "
asterisk="*"
i=1
while(n>0):
print((n*space)+(asterisk*i))
n=n-1
i=i+1
n=input("Enter a number ")
printer(n)
There are a couple of problems with your solutions and I'm not exactly sure what you were trying to do there.You made a function called printRow but you didn't use it. Try to do a dry run of the code while debugging. Follow everything on paper. For example write what value variables will have on each iteration and what the output will be on each iteration. It will help you to figure out where you went wrong. All the best!
Upvotes: 1
Reputation: 1639
As Jeff L. mentionned you are not calling your function, so you are indeed printing one space, one star and then the new value of myLen.
Regarding the actual problem, lets try to draw line by line, from right to left. First compute the number of spaces, and the number of stars for a row. Print it, go to next row.
See code bellow :
space = ' ';
star = '*';
size = int(input("Enter number to make triangle: \n"))
def printRow(current_row, max_row) :
line = space * (max_row - current_row) + star * current_row;
print(line)
if size<=0 :
print("The value you entered is too small to display a triangle")
elif size>=40 :
print("the value you entered is too big to display on a shell window")
for i in range(1, size + 1) :
printRow(i, size);
Upvotes: 0
Reputation: 132
This is a very basic one, can be improved, but you can learn from it:
def asterisk():
ast = "*"
i = 1
lines = int(input("How many asterisks do you want? "))
space = " "
for i in range(0, lines+1):
print (lines * space, ast*i)
lines -= 1
i += 1
Upvotes: 1