While those "catch-all" dupe targets are not great, the question is not worth reopening.
It's a bit of a mess, and I think it would be impossible to salvage something useful for future visitors from there.
If via extended comment discussion you were able to find a solution, great. But for the next time, please try harder to isolate the issue you are having.
The problems demonstrated on the question are about extremely basic language concepts, and by carefully debugging (not mentioning checking the docs) would allow you to at least fix the code to a "it works" state, even if not pretty.
Also, in the question you say that your "refactored" code shown there produces the same output than your first attempt; and yet it's impossible that it does. And easily proved that it doesn't.
Again, by working in reducing/isolating the problems to a minimal example this kind of thing wouldn't happen. The question code has too many problems, contradictions and moving parts to be that.
I believe the question would have been better closed as either "needs focus" / "needs details/clarity" / "needs debugging details", but I imagine the gold badger closed it as a "broad" dupe both for expediency and to direct you likely useful resources to deal with the question issue(s).
In any case, it's not worth reopening just to close it for a different reason, and I've added a more specific dupe target that deals directly with one of the issues exhibited by the question's code.