Programming Tips


Programming can be daunting at first, but following good programming practice helps. All of these suggestions have the same central concept: write code that makes sense. Whether you're planning your code out or adding comments, you're making it easier to understand.

0. Plan Before You Code

Before you touch your keyboard, plan out your code. What variables do you need? What functions? What kind of loops do you need, with what criteria? What order do things need to happen? All of these are questions you should answer before you start coding.

1. Descriptive Variable Names

Giving variables descriptive names (like "temperature" instead of "t") will increase the readability of your code. You'll understand what you're doing, and so will anyone who is helping you.

2. Define Constants

It may seem like plugging in constant values where you need them is useful, but this causes two problems. The first is when you don't remember what that number is or what it means, and the second is when you need to change that value. If you have a constant in multiple places you have to change them all by hand, and you might miss one. It's much easier to just change the value of a variable you declare at the beginning of your script.

3. Organize Your Code

Imports should be the top, followed by variable and constant declarations, then function definitions, and finally the body of your script.

4. Comment Frequently

Comments are critical. By explaining what you're doing, you're able to come back to your scripts later and remember what everything does. It also helps with organization.

5. Test as You Go

If you write 250 lines of code, run it, and have an error, you have 250 lines to look through. If you write 3 lines of code, run it, and have an error, you have 3 lines to look through. Testing your code as you go lets you identify where an error is taking place, and ensures that each piece of your code is operating as expected.

6. Make functions

If you are repeating a set of instructions, instead of retyping them, put them into a function. You can easily reuse the instructions, can change them in one place, and it makes it clear what those instructions are accomplishing.