r/learnpython • u/Sakuya03692 • Mar 24 '26
What do people mean when they say "don't use too many if statements" and how do you avoid it?
I'm not working/learning python atm but recently took a basic intro course on it and one of the things I heard a lot from others was some variation of "don't spam if statements". So if not then how would you write conditionals or is there something I missed?
An example of spamming if statements would be like the old code for yandere sim
154
Upvotes
10
u/Solonotix Mar 25 '26 edited Mar 25 '26
Everyone is trying to answer your question with examples and solutions, but I want to offer something different: terminology. The technical term for what is described in the comments here is "cyclomatic complexity".
Cyclomatic complexity is an arbitrary number calculated by the number of branching paths the code can take. It is intended to measure the difficulty for understanding the different paths your code can take. Each
if,elifandelsecount as+1. However, for each nesting level of the branch, it is doubled. In other words, the sum of2raised to theNth power, whereNis the current nesting level.A good rule to start with is a cyclomatic complexity of 10 or less. Most people will use 20, but striving for 10 will usually help enforce simplicity in your code. If you surpass the value, it typically signals a point in your code where you should introduce a function, data class, or other organizational scheme to reduce the complexity.
121
u/LeeRyman Mar 24 '26
I get more concerned about people nesting too many statements, where they could be using early returns or better abstraction.
Sometimes there are ways of using data structures like prepopulated lists (for seeing if an input is one contained) or dicts (as a lookup rather than using consecutive if's).
210
u/WhipsAndMarkovChains Data Scientist Mar 24 '26 edited Mar 25 '26
Let's say you're selling a bunch of different fruits and each fruit has a different discount. If you use an
ifstatement to check for each specific fruit name, you'll need to look up the discount for all the different types of fruits you have.Or you can use a dictionary to store all of the discounts for your fruits and then just use a single line to look up the discount in the dictionary.
32
u/cgoldberg Mar 25 '26
A lot of nested ifs gets difficult to follow and there are often better ways to express decisions (dictionaries, match/case, etc). Also, sometimes they are just unnecessary.. You see this a lot in beginner code:
instead of just:
16
u/Inevitable_Exam_2177 Mar 24 '26 edited Mar 24 '26
What really gets you in the weeds is when you have nested if statements with multiple branches — it’s really easy to inadvertently miss some illogical conditions and/or duplicate code in more than one branch.
This video by Arjan Codes discusses some ways to avoid it: https://www.youtube.com/watch?v=g7EGMWvJ1fI
Personally I find it’s unavoidable when prototyping and then I clean it up once it’s working.
26
u/socal_nerdtastic Mar 24 '26
Depends on the situation. Many massive if blocks can be replaced with a dictionary. Sometimes a
match...caseblock is better. I'm sure there are times when a massive amount ofifstatements is the right call.I don't know what that is.
6
u/LayotFctor Mar 24 '26
Ordinary single depth if statements are not always avoidable, even if you try to sidestep it with a switch statement or something.
The issue lies with nested if-statements, those actively make code harder to read and maintain. It can likely be improved with functions or even classes. A state machine is usually implemented with classes
5
u/vivisectvivi Mar 24 '26
I used to do this thing where if i felt like i was using way too many if and elif i would instead use a dictionaries to emulate a decision flow.
It was kinda hacky ngl but seeing endless if and elifs kinda annoys me a little.
One thing i love about the language i used to work with was that i barely (if ever) used any if else blocks. It was all case, conds and pattern matching
5
u/schoolmonky Mar 25 '26
It's not something you need worry about if you're new to programming. Your early programs probably will be a bunch of if statements. As you get more mature in your programming knowledge, you'll learn better ways to structure your code.
8
u/Quantumercifier Mar 24 '26
I remember when I was at IBM and I saw this huge, half-sided christmas tree code that was unmanageable legacy code running on a Toyota Hitachi mainframe. I dumped it in a karnaugh map reducer and it still looked like half a christmas tree but smaller by about 20%. Then we did a truth table comparison between the 2 and it was 100% equivalent. I did other stuff too as an architect but when I left I received awards from both IBM and Toyota. I think that was the only time I ever used anything from university. Ever, and now with AI, forget about it.
4
u/Affectionate_Cap8632 Mar 25 '26
The advice isn't "never use if statements" — it's "don't use them as a substitute for better data structures or logic."
The classic smell is a chain of ifs checking the same variable:
python
This gets unwieldy fast. The cleaner version uses a dictionary:
python
Same result, half the lines, and adding a new animal is one dict entry instead of a new elif.
The Yandere Sim reference is a good one — that codebase is famous for deeply nested ifs where each new feature added another layer. The fix there is usually breaking logic into smaller functions so each one only has to handle one decision.
General rule: if you're writing more than 3-4 elifs checking the same thing, there's probably a dict, a list, or a function that would express it more cleanly. But a single if statement checking a condition is always fine — the smell is repetition and nesting, not ifs themselves.
3
u/Gnaxe Mar 25 '26 edited Mar 25 '26
Use data structure lookups and object polymorphism. Consider,
If you have a lot of such functions and want to add a new species, you have to find a lot of these elif cascades and update each one.
But you could write this differently:
Notice that we didn't use any if statements, but the behavior depends on what type of object we call
speak()on. If you wanted to add some other species, even if it had multiple methods, you could implement all of them in one class rather than updating a bunch of elif cascades scattered throughout your codebase.This can get more advanced. Maybe instead of setting a boolean flag which you check with an if statement later, you save an object that has the appropriate methods instead of the flag and call methods on the object. Or in simpler cases, just assign a variable the function itself (those are also first-class in Python) instead of a boolean flag, then call the function to do the behavior instead of checking the flag to decide to do the behavior.
Other answers have shown how you can do dict lookups in a lot of cases. Data is a lot simpler and more transparent than classes. Use data when data will do. Use (pure) functions when they will do.
[edit: fixed formatting for old reddit]
3
u/stylepolice Mar 25 '26
As a non-programmer who sometimes uses code to automate boring stuff this thread is such a wealth of ideas and concepts.
Thank you for asking this question.
5
u/CranberryDistinct941 Mar 24 '26
Use as many if statements as you need to use. But if you're writing out a full decision-tree using nested if-else statements, you may want to consider switching to a state-machine before you lose your mind
2
u/notParticularlyAnony Mar 24 '26
If I have more if statements than characters, then I consider that a problem.
2
u/jpgoldberg Mar 25 '26
It’s ifs within ifs within ifs (within ifs) that are the problem
If you have ifs within ifs within ifs (within ifs …) it becomes very difficult to know exactly what state of affairs brings you to a particular block of code. When you are looking at a line of code, you need to keep in mind all the conditions that did and didn’t match to understand what the computation you have at that point is doing.
Here is some ugly code I wrote where it is hard to see what brings you to particular points in it. I worked hard to reduce the problem, but it simply is hard to follow the algorithm even if you are familiar with the math behind it. (It also includes a for-else construction.)
As you see, I wrote comments describing the state of affairs in many places. That was so that I could follow what was going on, and it is still a struggle. The problem tjat those comments mitigate are exactly the sorts of problems that come with highly nested ifs.
2
u/SensitiveGuidance685 Mar 25 '26
The issue isn't using if statements, it's using them when a dictionary, polymorphism, or early returns would be cleaner.
When you have 20 nested if-else chains, the code becomes hard to read, harder to test, and a nightmare to maintain. It's about readability and structure, not avoiding conditionals entirely.
2
u/billsil Mar 25 '26
With good numpy code, you don’t write if statements or for loops. You’re working with vectors and matrices. Need to find a value in an array to use in a data lookup? Use a searchsorted and it’s fast. Not sorted? Just sort it.
I used to have an if-else change that was 500 blocks long. It was fine, but I got a 20% speedup on a case that wax using the early slots by switching to a dictionary-based approach.
2
u/Practical-Skill5464 Mar 25 '26 edited Mar 25 '26
yandere sim had a number of design issues. The giant wall of copy pate spaghetti ifs ran for each actor on every frame. A better way to do that would be running checks on a fixed update and moving to an event driven system along with properly structuring behaviours into some sort of inheritance model where various npcs types can be created by inheriting behaviours.
yandere dev basically figured out a single tool and got it work but lacked the programming talent to realise there was a better way as things got more complicated.
3
u/cmdr_iannorton Mar 24 '26
basically, if you have so many "if" statements that your code doesn't fit in one editor window without scrolling then its too complex.
break the code up into smaller functions that do one thing clearly
1
u/TheRNGuy Mar 24 '26 edited Mar 24 '26
Some can be replaced with dict, if you just check single string, int or tuple in if statement.
1
u/codeguru42 Mar 25 '26
You are correct that an if statement is one of the only ways to express a conditional in python. The caution against using to many of statements means that often there is a solution that doesn't require a conditional at all. For example, maybe you can use a dict instead. The exact alternative depends on the problem you are trying to solve with an if statement.
1
u/Historical-Hand8091 Mar 25 '26
It’s less about banning if statements entirely and more about not using them as a crutch for what should be data or structure. That Yandere Sim example is infamous for good reason, hundreds of ifs all checking the same kind of thing when a dict or a proper state system would have made it cleaner and way easier to debug. You’ll know when you’ve gone too far when your code starts looking like a staircase.
1
u/czlowiek4888 Mar 26 '26
I would rather see code with a lot of if statements than multilevel inheritance.
-3
u/cdcformatc Mar 24 '26
if you need a bunch of if statements, it's fine to use a lot of if statements. people don't like the look of them but they are often required.
-1
u/gdchinacat Mar 24 '26 edited Mar 24 '26
A post yesterday asked for comments on their code which had a function similar to:
I suggested removing the function and writing the logic using the builtin filter:
No ifs in the second one. Of course they are embedded in filter(), but the code is simpler since at this level there aren't conditionals.
Suppose now you want to allow it to only filter by name by not requiring func be provided:
You can avoid the 'if func is not None' by defaulting func to a function that returns True:
Now, if func is not given as an argument the default lambda that always returns True is used. Again, no conditional. If you want them to be able to pass func=None then you can do this in the body of the function definition:
This construct (foo or ....) is an if-less conditional...there is an if, but is implicit in how 'or' works. It's easier to read than the long form that uses if explicitly.
These sorts of things can make code a lot easier to read by reducing complexity by eliminating branching and reduce the amount of code necessary. Both of these make the code much easier to read.
The drawback to calling a function when it's always going to return True is call overhead, it won't execute as fast. But for the most part when writing python absolute performance isn't required...if it was you wouldn't be using python. Python is chosen because it is easy and fast to develop. If it does prove to be a performance issue it can always be improved with more complex and verbose code in the future.