0
Can we talk about how I spent 6 months nesting if statements like they were going out of style
So I've been learning Python on my own for about 8 months now, mostly through YouTube and messing around with small projects. Last week I was trying to build a simple quiz app and my code was this giant tower of nested if/elif blocks that went like 8 levels deep. I was getting so frustrated because every time I added a new question, something broke in a different part of the chain. My friend who's a proper developer looked over my shoulder and just said 'why don't you use a dictionary to map the answers?' I swear my brain short-circuited. I had no idea you could just store question-answer pairs in a dict and loop through them. That one tip basically cut my code by like 80%. Has anyone else had that moment where you realized you were making things way harder than they needed to be?
3 comments
Log in to join the discussion
Log In3 Comments
zarab2425d ago
Actually read an article about this exact thing on Real Python a few weeks back. They talked about how beginners tend to overcomplicate code because they learn concepts in isolation without seeing how different tools can replace each other. That elif tower you described is basically the programming equivalent of using a hammer for every single problem. Even for simple tasks like matching user inputs to responses, a dict is so much cleaner. Once I swapped out my own if else nightmare for a dict and a for loop, my whole project suddenly made sense. Have you tried using default dicts yet for when someone types something you didn't plan for?
7
samwalker5d ago
Default dicts are a lifesaver, they make handling missing keys feel so much smoother than writing another elif every time.
10
michaelchen25d ago
its not that deep man. dictionary mapping is literally the first alternative any tutorial shows after basic if/else. feels like you skipped past the "data structures 101" videos and went straight to nesting everything.
3