Printing in a pyramid in Python

I cannot remove the spacing in for -loop, because the numbers are not suitable for creating a template.

My code is:

 for i in range(1,5): for j in range(1,i): print(j) 

But my desired result is:

 1 12 123 1234 
+3
source share
8 answers

Try the following:

 print(j, end='') 

end by default is \n (see print() ). Also, remember to print a new line at the end of each iteration of the outer loop:

 for i in range(1,6): # notice that I changed this to 6 for j in range(1,i): print(j, end='') # added end='' print() # printing newline here 
  one
 12
 123
 1234

EDIT I just noticed that you are using Python 2.7. In this case, you can use print j, instead of print(j, end='') and print instead of print() . Note that print j, will leave spaces between j s. If you do not want this, you can import sys and use sys.stdout.write(j) instead (see sys ).

Also, if you want to use the Python 3 print function as shown above, you can always

 from __future__ import print_function 
+5
source

One line solution if you are interested:

 print('\n'.join([''.join(['{}'.format(i) for i in range(1,j)]) for j in range(2,6)])) 1 12 123 1234 
+1
source
 for r in range(1,5): for c in range (1,r+1): print c, print 

here printing without an argument causes printing in the next line

+1
source

To get all the numbers on one line, you will need to use one print statement for each line. One way to do this:

 for i in range(1, 5): print(''.join([str(n) for i in range(1, i)])) 

Saving nested for loops you could do:

 for i in range(1, 5): temp = '' for j in range(1, i): temp += str(j) print(temp) 
0
source

Try:

 def RTN(): x = 1 num = int(input('Type any integer besides 0: ')) if num == 0: return 'Try again!' while x < num + 2: print('') for y in range(1, x): print(str(y) + ' ', end = '') x += 1 
0
source
 for a in range(3): for b in range(5,7): print ("*",end =' ') print ( ) 
0
source

x = input ('enter some numeric value')

s = ''

for i in the range (0, x):

  for j in range(0,i+1): s=s+str(j+1) print s s='' 
-2
source
 def pentagon(num): j = num for i in range(0, num + 1): print('{}{}'.format(' ' * j, ' *' * i)) j -= 1 pentagon(2) 

exit

  * * * 
-2
source

Source: https://habr.com/ru/post/1497494/


All Articles