- 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
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()
+ 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
+ 3
i=1
while i<=9:
print(i,end="")
i=i+1
if (i-1)%3==0:
print()
+ 3
wow, that was quick. Many thanks for your help.
+ 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?
+ 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
+ 1
It`s done. Thanks for remembering me.
All answers were helpful
+ 1
The second one is to further look into the print function
https://code.sololearn.com/cTiay1gR16w3/?ref=app