Bhavik Joshi February 2016

How remove the Space from the bottom of the output?

I am trying to get the following output?

*
**
***
**
*

Here is my code in python

n = int(input(" Please Enter any Number: "))

j=1
while j<=n:
    print('*'* j)
    j+=1

while n>=1:
    print('*'* (n-1))
    n=n-1
    #print(n)

but the problem is it gives me the following output

*
**
***
**
*

basically I am getting an extra space after the output.

Does anyone know what is the reason behind this and what is the remedy for the same.

Answers


jofel February 2016

You need

while n>=2:

in the last loop. Otherwise a further line with zero (1-1=0) stars is plotted at the end


Anton Protopopov February 2016

Why not rewrite your while loops with for loops which is as I think more appropriate for that task with range?

n = 5
for i in range(1, n):
    print('*' * i)
for j in range(n, 0, -1):
    print('*' * j)

Resulted to:

*
**
***
****
*****
****
***
**
*

EDIT

Or you could even write it with one liner with two list comprehension and str join method:

n = 3
print('\n'.join(['*' * i for i in range(1, n)] + ['*' * j for j in range(n, 0, -1)]))

*   
**  
*** 
**  
*   

Post Status

Asked in February 2016
Viewed 3,892 times
Voted 13
Answered 2 times

Search




Leave an answer