Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Better Coding request
#1
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
Reply
#2
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.
Reply
#3
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.
Reply
#4
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#
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#5
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?
Reply
#6
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.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  how can I correct the Bad Request error on my curl request tomtom 8 5,045 Oct-03-2021, 06:32 AM
Last Post: tomtom
  ImportError: cannot import name 'Request' from 'request' abhishek81py 1 3,917 Jun-18-2020, 08:07 AM
Last Post: buran
  mini coding request randy 1 1,934 Mar-02-2020, 09:14 PM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020