How would I write a function that produces a triangle like this:
xxxxxxxxxx
xxxxx
Let's say the function is def triangle(n)
, the bottom row would have n
amount of x's
All I know how to do is make a box:
n = 5
for k in range(n):for j in range(n):print('x', end='')print()
Dude It's super easy:
def triangle(n):for i in range(1, n +1):print ' ' * (n - i) + 'x' * i
Or even:
def triangle(n):for i in range(1, n +1):print ('x' * i).rjust(n, ' ')
output for triangle(5)
:
xxxxxxxxxx
xxxxx
Dont just copy this code without comprehending it, try and learn how it works. Usually good ways to practice learning a programming language is trying different problems and seeing how you can solve it. I recommend this site, because i used it a lot when i first started programming.
And also, dont just post your homework or stuff like that if you dont know how to do it, only if you get stuck. First try thinking of lots of ways you think you can figure something out, and if you dont know how to do a specific task just look it up and learn from it.