DEV Community

Discussion on: 3 Common Mistakes that Python Newbies Make

Collapse
 
fabiorosado profile image
Fabio Rosado

I understand where you come from with your example to check if a year is a leap year. It's a good example since you do need to use quite a few comparisons to figure out if a given year is a leap year. I will have to disagree with you that using a one-liner is a much clearer or even less redundant.

The thing is, if you encounter a code with this style in a massive code base:

if year % 400 == 0:
    return True
if year % 100 == 0:
    return False
if year % 4 == 0:
    return True
return False

Enter fullscreen mode Exit fullscreen mode

With your eyes, you can figure out what is happening there in less than a second. But when you encounter a one-liner like this:

return (year % 4 == 0 and (year % 100 != 0 or year % 400 == 0))
Enter fullscreen mode Exit fullscreen mode

You actually need to stop and in your head, you have to disassemble the logic on that statement. The same thing happens with generators, if you are creating a massive generator that makes the code less readable is better to just use the long form.

One thing worth mention is that when you do code challenges it is quite fun to try and scale down the solution to a one-liner - some platforms even reward you for coming up with a short solution, so it's good to know how to scale down a long if statement like that.

Collapse
 
rpalo profile image
Ryan Palo

Yes, this is very true. I mentioned in the article that the one-line Boolean is probably getting a little long and dense. Personally, I really like the multiple return version a lot better too. I show the Boolean version to illustrate that as one option for removing nesting. Good point about doing shortest solutions as a challenge :)