Python Forum
Better Coding request - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Better Coding request (/thread-18192.html)



Better Coding request - aankrose - May-08-2019

start = 5
for i in range(start):
    if i == 0:
        print('##')
    else:
        print('#',i*'o','#',sep='')
Output:
I am getting my Expected Output ## #o# #oo# #ooo# #oooo#
I am a Python Learner, would like to know if in what other way we can code better than above code, please suggest


RE: Better Coding request - Yoriz - May-08-2019

The first print('##') always happens only on the first iteration of the loop, the if statement has to check every time after that if i == 0:.
The first print could be moved to before the loop and the loop change to start at 1 instead of 0, then if statement would no longer be required.


RE: Better Coding request - Gribouillis - May-08-2019

aankrose Wrote:would like to know if in what other way we can code better than above code
There is also
print("""\
##
#o#
#oo#
#ooo#
#oooo#""")
but I don't know if it is better. It all depends on what you want to do next.


RE: Better Coding request - perfringo - May-09-2019

There is no need for conditional. Else clause is with i * 'o' which means that first iteration with index 0 returns no 'o'-s.

>>> for i in range(5):
...     print(f'#{i * "o"}#')
...
##
#o#
#oo#
#ooo#
#oooo#



RE: Better Coding request - aankrose - May-09-2019

My Favorite perfringo

Could you please explain me what print(f' accutally does ? i tried to find how it work , what i understand is , its kind of format , but i am now sure how print(f'#{i * "o"}#') work?


RE: Better Coding request - perfringo - May-09-2019

This is (new) string formatting called f-strings (formatted strings) available in 3.6 <= Python. You can read about it in PEP 498 -- Literal String Interpolation.

Quote:F-strings provide a concise, readable way to include the value of Python expressions inside strings.