I am trying to print 1 to 100 using while statement. Well, that is easy
n =100
i=0
while i<n:
i=i+1
print (i)
But the problem is how to put 1 to 10 in a row, 11 to 20 in a row, and finally to 91 to 100 in a row. Could you tell me the way?
You can use zip and iter:
lst = [i for i in zip(*[iter(range(1,101))]*10)]
Change the last number to the size of the chunks you want; in this case it is 10.
Output:
>>> lst
[(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), (11, 12, 13, 14, 15, 16, 17, 18, 19, 20), (21, 22, 23, 24, 25, 26, 27, 28, 29, 30), (31, 32, 33, 34, 35, 36, 37, 38, 39, 40), (41, 42, 43, 44, 45, 46, 47, 48, 49, 50), (51, 52, 53, 54, 55, 56, 57, 58, 59, 60), (61, 62, 63, 64, 65, 66, 67, 68, 69, 70), (71, 72, 73, 74, 75, 76, 77, 78, 79, 80), (81, 82, 83, 84, 85, 86, 87, 88, 89, 90), (91, 92, 93, 94, 95, 96, 97, 98, 99, 100)]
Then print each number inside the list:
for i in lst:
for j in i:
print(j, end=" ")
print()
Output:
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50
51 52 53 54 55 56 57 58 59 60
61 62 63 64 65 66 67 68 69 70
71 72 73 74 75 76 77 78 79 80
81 82 83 84 85 86 87 88 89 90
91 92 93 94 95 96 97 98 99 100
So overall you have:
lst = [i for i in zip(*[iter(range(1,101))]*10)]
for i in lst:
for j in i:
print(j, end=" ")
print()
EDIT:
As someone mentioned this only works in python 3. It can be done in python 2 by simply changing end=" " to ,:
lst = [i for i in zip(*[iter(range(1,101))]*10)]
for i in lst:
for j in i:
print j,
print
EDIT 2:
To do this with a while loop:
counter = 1
n = 100
while counter < n+1:
if counter % 10 == 0:
print(counter)
else:
print(counter, end=" ") #Change this line to print counter, for python version 2
counter += 1
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