Nobody writes perfect code. Anyone, no matter how experienced, can improve. So, you ask, how do I get better at writing code?
Of course, to get better at writing code, you must practice writing code. That much is obvious. Still, just writing the same poor code over and over, you're not likely to improve by much.
Writing is a different skill from reading, but reading code is necessary if you want to improve your writing. As with writing natural language, you build up your skill and confidence by reading—and not just reading your own output. So, find yourself some examples of good, clear code and read, read, read until you understand each piece.
Be careful, though. There’s lots of terrible code around. You can read terrible code, of course, and learn to analyze why it’s terrible, but your first attention should be on good code. Excellent code, if possible.
Where can you find good code? Textbooks are an easy choice, but be wary of textbooks. Kernihan and Plauger, in their book, The Elements of Programming Style, showed us how awful textbook code can be. Their little book can teach you a lot about recognizing bad code.
But bad code isn't enough. Knowing what's bad doesn't necessarily teach you what's good. Some open source code is rather good, and it’s easy to obtain, though it may be too complex for a beginning. Complex code can easily be bad code.
Hopefully, you will participate in code reviews, where you can see lots of code and hear various opinions on what’s good and what’s less than good.
Definitely ask you fellow programmers to share code with you, though beware: not all of it will be good examples. Be sure the partners you choose are able to listen objectively to feedback about any smelly code they show you.
If you work alone, use the internet to find some programming pen pals.
As you learn to discern the difference between good and poor code, you can use this discernment in your reading. After a while, you’ll be ready to start writing simple code, then work your way up to more complex tasks—all good.
And date and save all your code-writing examples, so you can review your progress from time to time.
Good luck, and happy learning!