
Question:
An isosceles triangle is a triangle with two sides of equal length. Given an input, print an isosceles triangle according to the examples below. You would have to find the pattern.
Input: 3
Output:
#
###
#####
Input: 2
Output:
#
###
Input: 1
Output:
#
Answer:
The key here is finding the right number of spaces and asterisks (*) to print in each row. Then we can use ‘multiplication‘ in Python to repeat a character multiple times and ‘addition’ to concatenating two strings.
# the function
def isosceles_triangle(n):
for i in range(n):
# use * to repeat a character multiple times
# use + to concatenate two string
print(' '*(n-i-1) + '#'*(i*2+1))
# call the function
isosceles_triangle(5)
👍 Have fun while coding with Python!
👌 Please Subscribe to receive notifications on future challenges.
💬 If you have any questions simply write a comment down below.