[Tutor] A Question about coding style
Cameron Simpson
cs at cskk.id.au
Thu Sep 16 22:46:48 EDT 2021
On 17Sep2021 07:05, Manprit Singh <manpritsinghece at gmail.com> 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 purpose of style is readability, for yourself and others.
Is it still readable? For a very short statement, probably yes.
If it a significant win over a 2 line if-statement? Maybe, maybe not.
The 2 line form makes it quite obvious that there is an if-statement
there.
Is it acceptable? That depends on the coding style in your organisation
(which can, of course, be just you).
>Second example is of a for loop, which is also written in single line
>for i in range(6): print(i) # print values from 0 to 5,is it also
>acceptable ?
Same criteria: Very short things: maybe. Is it a gain in readability?
Maybe not?
This style is uncommon. On a personal basis I tend to use styles like
this if I have several very short test/action pairs. Example:
for x, y, z in some-3-tuples...:
if x < 0: x = 0
if y > 5: y = 6
if y + z > 10: z /= 2
If there's a little collection of these it _can_ be useful to flatten
them to one line. Particularly if you're trying to get them well defined
as a group that fits in a vertical space.
But if they're mixed:
for x, y, z in some-3-tuples...:
if x < 0: x = 0
if y > 5:
call_something()
y = 6
if y + z > 10: z /= 2
I might find the visual variation annoying.
Cheers,
Cameron Simpson <cs at cskk.id.au>
More information about the Tutor
mailing list