Write a program that asks the user for an input n
(assume that the user enters a positive integer) and prints only the boundaries of the triangle using asterisks '*'
of height n
.
For example if the user enters 6 then the height of the triangle should be 6 as shown below and there should be no spaces between the asterisks on the top line:
******
* *
* *
* *
**
*
I cannot understand how to print the part between top and end of pattern? This is my code:
n = int(input("Enter a positive integer value: "))
for i in range (n, 0, -1):
print ("*" * i)
The for
loop is for printing the reverse asterisks triangle. Obstacle is to print the middle part.
In every iteration of the for
loop You print one line of the pattern and it's length is i
. So, in the first and the last line of the pattern You will have "*" * i
.
In every other line of the pattern you have to print one *
at start of the line, one *
at the end, and (i - 2)
spaces in the middle because 2 stars were already printed out, which results in "*" + (" " * (i - 2)) + "*"
. After combining that two cases, we get the following code:
n = int(input("Enter a positive integer value: "))
for i in range(n, 0, -1):
if i == 1 or i == n:
print("*" * i)
else:
print("*" + (" " * (i - 2)) + "*")
Try the following, it avoids using an if
statement within the for
loop:
n = int(input("Enter a positive integer value: "))
print('*' * n)
for i in range (n-3, -1, -1):
print ("*{}*".format(' ' * i))
print('*')
For 6, you will get the following output:
******
* *
* *
* *
**
*
You could also handle the special case of 1
as follows:
n = int(input("Enter a positive integer value: "))
if n == 1:
print '*'
else:
print('*' * n)
for i in range (n-3, -1, -1):
print ("*{}*".format(' ' * i))
print('*')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With