+ 6

Best practice for nesting loops?

From a best practice perspective, how many loops should you nest in each other? I ask because I'm in the process of making a simple text game in python with plot options in loops to take input. I plan to make it short but if I made it 5 tiers with 2 options, I would have 32 branches, which would be mental as one block of code. Should I separate each branch into a subprogram/function? Or should I be grouping the branches in a more efficient and easily readable way than one huge chunk?

25th Oct 2018, 1:07 PM
Rob Bailiff
Rob Bailiff - avatar
7 Answers
+ 9
Tyrant Thanks, I was thinking that about three was starting to get a bit too much
25th Oct 2018, 2:03 PM
Rob Bailiff
Rob Bailiff - avatar
+ 7
Mike Utty Nice suggestion. I will have a play around and see how it works for me
25th Oct 2018, 2:58 PM
Rob Bailiff
Rob Bailiff - avatar
+ 4
thanks Rob Bailiff for the likestorms
29th Oct 2018, 4:17 AM
Webster
Webster - avatar
+ 4
Cybernaut And thank you too 😁
29th Oct 2018, 6:48 AM
Rob Bailiff
Rob Bailiff - avatar
+ 1
I think you should group the branches,at most you should nest at least 3 loops if you want to keep track of your program...Don't go higher than 3 nested loops,it'll confuse you...
25th Oct 2018, 1:27 PM
Mensch
Mensch - avatar
+ 1
https://code.sololearn.com/cml421W77zgg/?ref=app Maybe try something like this. It is a way to mimic a switch statement.
25th Oct 2018, 2:29 PM
Mike Utty
Mike Utty - avatar
+ 1
Also for functions that won't be called more than a couple times, you can use lamdas inside the dict. If the functions get called often though lambdas would start to cost a bit more because it would have to generate a new func at each call so only use the lambda way sparingly.
25th Oct 2018, 2:39 PM
Mike Utty
Mike Utty - avatar