[Tutor] Question about code readability and good coding practise

Mats Wichmann mats at wichmann.us
Sun Feb 7 09:27:31 EST 2021


On 2/6/21 10:25 PM, Manprit Singh wrote:
> Dear Sir ,
> 
> Just need your suggestions :
> 
> Consider a problem where I have to make a program that allows the user to
> give integer inputs 10 times from the keyboard and then put all these 10
> integers into a python list.
> Writing like this would be considered readable and good code ?
> 
> var =  [int(input("Enter number")) for i in range(10)]

I'll agree with @dn here.

When I first started seeing comprehensions they seemed really obscure, 
over time (not much time)  they became very readable for me, more so 
than rolling things out into loops.  So really no definitive answer on 
readability of using comprehensions in general - it may depend on 
whether you expect your audience to be experienced or inexperienced 
Python programmers.

To the specific case, when you use "input", you are taking data from 
outside the program. Such data should always be carefully validated - 
that's just basic security practice.  The line above just does too much 
hiding. I'd assert that the "readable" form for such a scenario would 
have a loop the body of which contains something like

  prompt for input
  input valid?
     add to saved data
  else
     explain problem and go again


Once again, probably in "real life" coding, you'll very rarely use input...


More information about the Tutor mailing list