- 2

[SOLVED] need help with a problem in python

I try to print the following: 123 456 789 or at least: 1 2 3 4 ... My code: i=1 while i <= 9: print(i) i = i+1 if i % 3 == 0: print("\n") Output: 1 2 3 4 5 6 7 8 9 How can I print this in 3 similar blocks? Thanks

13th Dec 2018, 12:03 PM
Michael
Michael - avatar
8 Answers
+ 5
You are almost there. Instead of updating i first and check for %3, you should switch the two statements so it checks the current plotted i print(i) if i%3 == 0: print("\n") i=i+1 You could also use a nested loop and the end property of the print function: while i <= 9: for a in range(3): print(i,end="") i=i+1 print()
13th Dec 2018, 12:13 PM
Matthias
Matthias - avatar
+ 6
You're on the right path, just a rearrangement would do the trick: i = 1 while i <= 9: print(i, end="") if i % 3 == 0: print() i = i+1
13th Dec 2018, 12:12 PM
Kishalaya Saha
Kishalaya Saha - avatar
+ 3
i=1 while i<=9: print(i,end="") i=i+1 if (i-1)%3==0: print()
13th Dec 2018, 12:16 PM
Rishi Anand
Rishi Anand - avatar
+ 3
wow, that was quick. Many thanks for your help.
13th Dec 2018, 12:29 PM
Michael
Michael - avatar
+ 2
Michael, as your problem is solved, it will be very kind of you if you can (i) Mark best answer, and (ii) edit your question title to begin with a [SOLVED] so the other sololearners won't need to pump in?
13th Dec 2018, 12:53 PM
Gordon
Gordon - avatar
+ 2
Thank you, Michael. Further to the above solutions, may I supply two examples for your as enrichment: The first one is how you can do this without the end property of print function : https://code.sololearn.com/cHFcyI9FD9eR/?ref=app
13th Dec 2018, 1:05 PM
Gordon
Gordon - avatar
+ 1
It`s done. Thanks for remembering me. All answers were helpful
13th Dec 2018, 1:04 PM
Michael
Michael - avatar
+ 1
The second one is to further look into the print function https://code.sololearn.com/cTiay1gR16w3/?ref=app
13th Dec 2018, 2:06 PM
Gordon
Gordon - avatar