Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using print function to print a pyramid

I’m completely new to programming in python, and I have a small exercise, as you can see, I want to write a code that can display the results below, I have tried many times but did not get the desired result.

Disired output :

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

I wrote this in the C language and it works, but in python I don’t understand why it doesn’t.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

for i in range(9):
   for j in range(i):
        print("* ")
   print("\n)

My code gives this result :

* 


* 
* 


* 
* 
* 


* 
* 
* 
* 


* 
* 
* 
* 
* 


* 
* 
* 
* 
* 
* 


* 
* 
* 
* 
* 
* 
* 


* 
* 
* 
* 
* 
* 
* 
* 

>Solution :

By default, print creates a new line. You can instead write

print("* ",end='')

From the documentation, the syntax of print is :

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

You may also avoid using the second loop :

for i in range(1,n+1):
     print(i*'* ')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading