Debloating code from superfluous conditional statements!

Hello everyone!

I am a beginner programmer here that has just completed their second python project, the time calculator.
I have come here to ask for advice because I have noticed that I have a bad habit of frequently using conditional statements, sometimes even when they may not be necessary, and those in turn cause my code to easily become bloated.
I would like to write cleaner, better code, and wondered if you guys had any suggestions.

Bearing in mind that the code I write does work, and that I have only started programming recently (two weeks ago) , the information that I have inferred so far specifically on how to write other code in place of if else statements and debloat my coding is the following:

-lambda functions are your friend, especially when you need to sort and filter lists

-dictionaries can also be your friend (https://towardsdatascience.com/dictionary-as-an-alternative-to-if-else-76fe57a1e4af)

-write out in comments what the different parts that make up the program will do, jotting out notes and writing a quick draft", so as to get a better picture of what your end will “product” will be like, and that so that you can focus on your programming task more easily.

As I am sure that there are a lot more tricks/ knowledge to learn when it comes to de-bloating and writing more succinct code, and so I would love to hear any tips and tricks the freecodecamp community has to give on the matter.
Happy coding!

I wouldn’t say that if-else statements automatically mean code is bloated. Long chains of if-else statements tend not to be very ‘pythonic’, but a simplier if-else can sometimes be clearer than refactoring tricks to avoid using an if. Simplicity and readability is better that setting a rule for yourself to avoid if-else.

Other languages might use switch-case but Python doesn’t natively support those - hence some workarounds with dictionairies or functions for long chains.

But honestly, you can also just use if-elif-else chains. They are not bad or anything, so don’t sweat it.

1 Like