DEV Community

Discussion on: 3 Common Mistakes that Python Newbies Make

Collapse
 
vlasales profile image
Vlastimil Pospichal

This is a bit faster, because the first condition is met most often:

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

Shorter version:

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

Shortest version:

return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
Collapse
 
rpalo profile image
Ryan Palo

That’s a good point! I feel like that order would be more intuitive for students as well! It does have the slight downside of using “negative comparisons” but I think the ease of understanding definitely outweighs that. 😁

Collapse
 
vlasales profile image
Vlastimil Pospichal

Negative comparisons are needed to eliminate else from source codes.

Thread Thread
 
rpalo profile image
Ryan Palo

I’m not 100% sure that else is a bad thing. But I agree that using negative comparisons isn’t a terrible thing. Maybe more of a “all things being equal, try to use positive rather than negative if possible” kind of thing.

Thread Thread
 
vlasales profile image
Vlastimil Pospichal

Eliminating else made my source code cleaner and faster. I use else in ternary operator only. I transformed structure if-else into ternary expression in many times.

Some languages (XSLT for example) are without "else". This inspired me.