[Tutor] A Question about coding style
Alan Gauld
alan.gauld at yahoo.co.uk
Fri Sep 17 04:18:03 EDT 2021
On 17/09/2021 02:35, Manprit Singh wrote:
> If I have to write a program, that allows the user to input a number and
> assign it to a variable b, if the number entered is a negative number,
> assign 0 to variable b.
> At last print the value of variable b. The code that i have written is
> given below:
>
> b = int(input("Enter a number"))
> if b < 0: b = 0
> print(b)
>
> See the whole if statement part is written in single line, is it acceptable
The thing about coding style is that it is subjective (within limits).
But in the real world it will be set by the organisation for which you
work. They will likely have a set of coding guidelines that you must
follow. In one place they may ban single line constructs. In another
they may mandate them. It probably won't be your choice, it will be set
by the QA team. They may even have built tools that reformat your code
to comply.
Of much greater importance is that your code does not handle errors
such as the user typing "two" instead of a numeric character. A
loop and/or a try/except would normally be involved which would
automatically make your code more complex.
while True:
try:
b = input(...)
if b<0:...
except: continue
Now we have two single lines (if and except) or not, as the rules allow.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list