I'm studying programming and heard that using if-else statements in Python is sloppy. What should I use when a program needs to do different things based on its input?
Are if-else statements really considered sloppy code?
Answers
No, an if-else statement is a perfectly normal way to make a decision. If there are two clear outcomes, spelling them out with if and else is often the most readable choice.
What can get messy is a long chain of conditions or several levels of nesting, especially when each branch contains a lot of unrelated work. The issue is how easy the code is to understand and change, not the presence of an else keyword.
Reply to this answer
For a long chain that checks the same value against different options, Python's match statement can make the cases easier to scan. A dictionary can also map input values to results or functions.
For example, a menu might map an action number to the function that handles it. You still need to decide what happens for an unknown number. Neither approach is automatically better than a short if-elif chain, so pick the one that makes the choices clearest.
Reply to this answer
Deep nesting is where I'd look first. If a function can't proceed because an input is invalid, check that condition near the top and return early. That leaves the main path less indented and easier to follow.
You can also move a substantial branch into a well-named function. Early returns and helper functions don't eliminate decisions, but they can make the flow easier to read.
Reply to this answer
Sometimes repeated conditionals point to a design issue. If lots of functions check what kind of object they received and then do different things, putting the relevant behavior on those objects can be cleaner. Each type can provide its own implementation of the same method.
That is polymorphism. It's useful when the variation belongs to the objects, but making a class hierarchy just to avoid one small conditional is probably overkill.
Reply to this answer
For a simple choice between two values, Python has a conditional expression such as value_if_true if condition else value_if_false. It's handy when the whole expression stays short, but a regular if-else is easier to read once the logic gets complicated.
Reply to this answer
Add your answer
Answers are reviewed before publication.
_m63~quorvex.8:
I'd ask the professor for an example of the code they meant. There might have been a particular pattern or assignment constraint behind the comment.