General Python Programming Advice

Here is some advice that you should keep in mind while writing your code. These tips should make it easier for you to write readable and maintainable code. The most important thing about computer code is, that you will be able to understand it even after a longer period of time. Also, you will probably read more code than write it, so make sure it makes sense to both, a different person and yourself 6 months from now.

Meaningful names

Use meaningful names for variables and functions. Have a look at the following example:

def a(h, w):
    result h*w

The above function most likely takes the height and the width of an object and calculates the rectangular area of this object and returns it. This function might even come with a comment explaining what it does. But just imagine you are at the bottom of your code and there is just this function used as such:

if a(5, 12) < 35:
    print("Too small!")

What was the use of the function a() again? Do I really need to look it up? This is even worse when you import the functions from a different file, then you cannot just scroll up to have a look.

Try to avoid such a vague name pattern and use descriptive names that make sense.

def area_rectangle(height, width):
    result height*width

if area_rectangle(5, 12) < 35:
    print("Too small!")

If you now look at the code, it does make more sense, even without any comments. Also, if you have several functions with a similar goal, you may want to use a certain naming patters such as area_rectangle() and area_circle which makes it clear by their names that they have some similarities. The same applies to the names of variables. r is not the best variable name for the radius of a circle, therefore, use radius_circle instead, or something else that is more descriptive.

You may even want to add the measurement unit inside the name such as battery_level_mV so you will immediately see that this value is given in mili-volts instead of volts.

Avoid hard-coded values

When you implement some code with numbers or strings inside that code, you could either type the values you want into the code, or you could use a variable instead. If you implement the code by typing the actual values, these values are called hard-coded as you cannot easily change them.

Why is this bad? When you have a value that changes during the development phase, you will need to find this value in the code on each instance you use this value, and replace it. This can be a very time-consuming process while hard-coded values do not have any real advantage.

In some programming languages, you can implement these values as constants which are variables whose value cannot be changed. In Python, constants do not exist so it is common practice to use a variable written entirely in capital letters.

MIN_VOLTAGE = 1.2
MAX_VOLTAGE = 1.7
PI = 3.141592
SOFTWARE = "Python"
SOFTWARE_VERSION = "2.7.17"
DEFAULT_STATE = False

In case the value will change inside the code, you should use a simple variable instead of a constant. The advantages are that you can easily change the value of these constants without searching in the code and you can see in the code what this value actually means. If there are hard-coded values, these numbers do not always make sense. Compare the following:

if voltage_mV > 1.2:
    print("Enough power left!")
if voltage_mV > MIN_VOLTAGE:
    print("Enough power left!")

The second version of that code is more likely to make sense to the reader than the version with hard-coded values.

When using constants, they are usually stored at the top of the document so they are easier to find. An alternative to constants would be to use a configuration file which would be more advanced already. Common formats for config files are JSON (JavaScript Object Notation) format or YAML (Yaml Ain’t Markup Language) format.

Comments

The use of comments in code is often discussed among developers. Why using them? Why not using them? When to use them? There is no absolute answer to this topic, but here are some guidelines that you can apply.

Avoid comments

Don’t understand this wrongly. Comments are great to describe the functionality of your code, but you should still try to limit the number of comments that you insert into your code. Why? Because it clutters the code and it can be misleading. Why can it be misleading? Well, the code is the part that actually does what is says, so if there is a change in the code, the code will still tell the truth, but when the code changes, the comments are often untouched. This means the comment tells something different as the code executes. In that way, the code can lie.

Have a look at the following example:

if light_sensor_mV > 300:
    # sets day_time to True
    is_day_time = True
else:
    # sets day_time to False
    is_day_time = False

Now it can occur, that you may change the sensor, or make a different circuit which then inverses the behavior of the sensor. You change your code so it does work properly again. But as you only verify if the code is correct, you may not realize that the comments are not matching what the code does:

if light_sensor_mV < 300:
    # sets day_time to True
    is_day_time = False
else:
    # sets day_time to False
    is_day_time = True

The issue is, that when you re-visit your own code after several months, you forget that you changed the code and then you only see that the comments and the code do not match. What does that mean? is the code wrong? Do you need to change the code? So you can now either trust the comment and change the code or you can trust your code, not knowing if it worked or not, and change the comment. This creates some ambiguity that is unnecessary and can easily be solved by removing these comments. There, it helps that your variable names and function names have a good descriptive name so that you don’t need any comments to figure out what they mean.

To make it short: Comments can lie, code cannot lie.

Write meaningful comments

But this does not mean you should never use any comments. The goal is to avoid unnecessary comments. A comment is appropriate if it adds value to the code.

There are situations where a code is simply not necessary:

# set radius to zero
radius = 0
# set center to (0, 0)
center_x = 0
center_y = 0

def print_hello():
    # prints "Hello"
    print("Hello")

The above code contains comments that are totally unnecessary. Except from the risk that the comments could be misleading, these comments here do not add value. Some developers would go so far to say that, if you have the urge to write a comment to explain the code, the code itself is not well written. I would not go so far, but I would recommend thinking if that comment is really useful or not.

Comments that can add value include explanation why you set a certain value, explain the general functionality of a complex function or add notes to remind you to add a new feature later. Some text editors even highlight the word TODO for that matter.

max_battery_voltage_mV = 3300
min_battery_voltage_mV = 2700
battery_voltage_mV = voltsensor_battery.read()

# check if voltage is enough to drive back
if battery_voltage_mV > min_battery_voltage_mV:
    # TODO: implement functions to continue
    print("Continue driving!")
else:
    # TODO: implement functions to drive back
    print("Driving back!")

You can see that the above code has a comment explaining why there is a check of the voltage and there are comments explaining what needs to be done in the near future. When these features are implemented, these TODO comments should be removed.

Before writing a comment, think whether it adds value to your code or not.

Commenting code

When testing your code or testing a new feature, you will likely comment out some code to see how the program reacts to these specific lines. This is totally fine while developing, but when there are still lines of code that are commented out after you finished your work, this will also lead to confusion. People will most likely not use this code as it is not needed, why else would it have been commented out earlier? At the same time, people will not remove this code, because why else was this code not deleted earlier? This code might be needed later? Maybe not? Other people don’t know. And you also will nit remember after a longer break.

Some people recommend to remove the code as soon as you don’t need it anymore, to avoid this confusion. By using a version control system like git, the code that has been removed is never really lost anyways. Other developers don’t like the idea of radically removing code, they might need it later. So if you want to keep the code ready to re-integrate again, add a comment explaining why you put that code into comment. Yes, this will clutter the code even more, but at least there is no confusion about why there is code into comment.

When adding some test code such as additional print statements, you may also add a comment to explain that this code is for debugging only. This makes it easier to clean up your work when it is finished and working.

Use functions

This might sound obvious, but sometimes people tend to forget to implement some specific code as a function. This might happen, because the code is just a few lines that are repeated and implementing a function seems a little bit too ambitious. Then, you want to change that code and then you need to change it several times inside your code. If this code was implemented in a function, you could easily change it one single time and then it would be fine again.

For example if you want to calculate the distance between two points:

from math import sqrt

point1 = (2, 5) # in cm
point2 = (3, 7) # in cm
distance1 = math.sqrt((poin2[0] - point1[0])**2 + (poin2[1] - point1[1])**2)

point3 = (5 -2) # in cm
point4 = (0, 3) # in cm
distance = math.sqrt((point4[0] - point3[0])**2 + (point4[1] - point3[1])**2)

In the above code, the coordinated of the points are indicated in centimeters but you want to have the distance in meters. You now need to add the conversion twice:

from math import sqrt

point1 = (2, 5) # in cm
point2 = (3, 7) # in cm
distance1 = math.sqrt((poin2[0] - point1[0])**2 + (poin2[1] - point1[1])**2)
distance2_m = distance1/100 # add conversion here

point3 = (5 -2) # in cm
point4 = (0, 3) # in cm
distance = math.sqrt((point4[0] - point3[0])**2 + (point4[1] - point3[1])**2)
distance2_m = distance2/100 # add conversion here

If you implemented a function for this, you would simply need to add the unit conversion once and the actual code would be much cleaner:

from math import sqrt

def calculate_distance(point1, point2):
    distance = math.sqrt((poin2[0] - point1[0])**2 + (poin2[1] - point1[1])**2)
    distance_meters = distance/100
    return distance

point1 = (2, 5) # in cm
point2 = (3, 7) # in cm
distance2_m = calculate_distance(point1, point2)

point3 = (5 -2) # in cm
point4 = (0, 3) # in cm
distance2_m = calculate_distance(point3, point4)

The function does not much more than the actual code, but it is easier to maintain. You can simply add or remove parts of the function and then the changes are consistent for each time you use this function. Functions are a powerful tool, so don’t hesitate to use them. Also, using functions allows you to use a meaningful name that might be more descriptive than the actual formulas used in the code.

Separate different levels of abstraction

What is a level of abstraction? When writing code, you might realize that some code is more abstract than other code. By abstract, I mean that some code is closer to the actual hardware than other pieces of code.

For example, if you have a micro-controller and you change the state of one pin from LOW to HIGH, this would be considered very low level behavior as this is very close to the real hardware and is not abstract at all.

Instead, if you use a function that simply sends a message through the serial port or just use the print() function, this is considered to be very abstract code as you do not need to worry which bits and bytes are changed in order to make your message appear on the screen or on another device. This code would be very abstract and it would probably be implemented through a set of lower level functions that do the work for you.

motor_enable_pin = True # low level code
print("Motor enabled!") # high level code

The actual advice is to keep same level of abstraction together. No high level code together with low level code in one function. How to do that? Implement a function that makes an action more abstract. In the above example, there is the changing of the voltage level of a hardware pin next to a print statement. In this case, you may want to re-organize the code as follows:

def main():
    enable_motor() # high level code


def enable_motor():
    enable_motor_pin() # mid level code
    print("Motor enabled!") # mid level code


def enable_motor_pin():
    motor_enable_pin = True # low level code

Now, in the above code, there are three functions that are responsible to enable the motor and to write a message on the screen. You may not find this very intuitive as you actually write much more code which is not doing more than the two lines earlier, but in the end, the code is more structured and easier to read.

In the end, you could say that, by writing more, you end up reading less. You only need to look at the abstraction level that you actually are interested in. If you only want to make sure the message you write on the screen is correct, you do not need to worry about which pin has been enabled or which other actions have been taking in order to enable the pin. Of course, the above example is very short. In a real world example, each function will contain more code and then the use of functions of different abstraction levels will make even more sense.

Keep it clean

Avoid the “Quick and Dirty” approach as you probably end up rewriting it several times and then spend more time as if you had done it the “Nice and Clean” way.

By “Quick and Dirty”, I mean to ignore all the advice above just because it is too much work to think of good variable and function names and not putting any value adding comments because “you know what it does”. You might end up with code that will be used more often than you could imagine and you end up wondering why this code is such a mess.

I once was told to write some code the “Quick and Dirty” way because the code should do a small task and then I would not have to bother with that code ever again. I ended up working over 8 month with that same code and I wished I just made it “Nice and Clean” in the first place instead of trying to improve it each time that I re-open the code.

If you are not sue about certain topics, you can go back to Object-Oriented Programming.

Functions

After you saw how to use loops, what do you use when you want to repeat the same code several times? Sure, a loop! But what if you want to run the same code, but only once every now and then? Just copy the code every time you want to run that code? Why not use a function?

What are functions?

A function can be seen as a mini program inside your program. They are very useful to avoid coping and pasting the same blocks of code over and over again. The difference to a loop is that a function is usually used to group some functionality together and repeat the same algorithms at different places inside your program instead of repeating it several times after each other like a loop does.

You probably know the concept of a mathematical function such as: f(x) = x². This kind of functions can also be used in programming:

def f(x):
    return x**2

The above function is representing the function f(x) = x². The key word def is used to indicate that there will be a new function definition. After the key word def, the name of the function is defined, in this case simply ‘f’. Inside the parentheses is the parameter that can be given to the function. This is a way to give your mini program some input. A function can have several input parameters, they are then separated by a comma. Then the definition ends with a colon and the next lines that are indented. Everything inside the same level of indentation is part of that function definition. The last element of the function is the return key word. The variable(s) after the return key word are given as an output of your function.

You can call the function as follows:

y = f(3)

Now, the return value will be stored inside the variable y. Like this, a simple formula such as a²+b²=c² could be easily implemented as:

a_squared = f(a)
b_squared = f(b)
c_squared = a_squared + b_squared

In case you as: Why using a function for such a simple thing? Well, you probably will not use it for such a thing. Most likely, you will use it for more complex calculations. Also, you will hopefully not call the function ‘f’ and the input parameter not ‘x’. Let’s have a look at another function. The following will calculate the surface area of a rectangle with two input parameters:

def rectangle_surface_area(height, length):
    return height * length

The above function has a descriptive name, and the parameters are explicitly telling what they are supposed to be. This is often seen as good practice for writing functions.

A function can be more than a simple line of calculations. It can even contain print statements, loops and even other functions.

Small Example

The following function will ask the user to input his name and his age.

def ask_personal_data():
    name = input("Please enter your name: ")
    age = input("Please enter your age: ")
    return name, age

The function will then be used as such:

user_name, user_age = ask_personal_data()

if user_name == "John":
    print("Hello John! Did you know that this is a very common name?")
else:
    print("Hello!")

As said, the above function will ask the user to type the name and the age and then the function returns both values. The user will see something like this:

Please enter your name:
Jacob
Please enter your age:
25

Advantages of functions

With this function, you can now use it everywhere in your code to perform the same tasks again and again where they are needed. One advantage is that they make the program sorter and easier to read. Another advantage is, that you only need to modify the code one single time instead of modifying it on each occasion where you use the same algorithm.

Increased Maintainability

Let’s have a look at the following example of a driving robot:

motor_speed = 0.2 # m/s

sensor_input = 540 #assume: 0 -> 0 meter and 1024 -> 2 meter
distance_to_wall = sensor_input * 2 / 1024
if distance_to_wall <= 0.2:
    print("You need to stop now!")
    motor_speed = 0

# read user input

sensor_input = 370 #assume: 0 -> 0 meter and 1024 -> 2 meter
distance_to_wall = sensor_input * 2 / 1024
if distance_to_wall <= 0.2:
    print("You need to stop now!")
    motor_speed = 0

# calculate battery voltage

sensor_input = 210 #assume: 0 -> 0 meter and 1024 -> 2 meter
distance_to_wall = sensor_input * 2 / 1024
if distance_to_wall <= 0.2:
    print("You need to stop now!")
    motor_speed = 0

Now let’s see how this could be reduced with a function:

def calculate_distance(sensor_input, motor_speed):
    sensor_input = 540 #assume: 0 -> 0 meter and 1024 -> 2 meter
    distance_to_wall = sensor_input * 2 / 1024
    if distance_to_wall <= 0.2:
        print("You need to stop now!")
        motor_speed = 0
    return motor_speed

motor_speed = 0.2 # m/s

motor_speed = calculate_distance(540, motor_speed)

# calculate battery voltage

motor_speed = calculate_distance(370, motor_speed)

# read user input

motor_speed = calculate_distance(210, motor_speed)

Now you might ask: where is here an advantage in number of code lines? The first option only has 4 lines more than the second option. Yes, this is correct, the difference is not that big indeed.

However, imagine you decide not to use the distance in meters as you will always get small decimal values but instead, you want to use centimeters instead. In the first option, you need to modify the calculation of the distance three times. In the second option, you only need to do it once. Also, if you use the same calculations 20 times inside your program, you don’t always think of each time you used it and you might forget it at one spot and then there are mistakes in the code. Or imagine you have a different sensor with a range from 0 to 2048 bits instead of 1024. This means many changes all over the code or only one single change in the function.

Increased Readability

Not convinced yet? The following function will not save you many lines, but the calculation inside is not very self-explanatory. The function name will tell you more about what you are calculating.

# import the square-root function from the math module
from math import sqrt

def distance_between_points(x1, x2, y1, y2):
    distance = sqrt((x2-x1)**2 + (y2-y1)**2)
    return distance

Functions can also be used simply to structure your code into logical chunks or to give meaningful names to the algorithms that you program, even if you know you will use this algorithm only once in this program.

Modularity

Also, you might notices the line from math import sqrt. This line imports a function from another python file, so you can use it in your code as well. This means functions make the software more modular and reusable. There are many more functions that you already saw like the input() function, the print() function (yes, technically in Python 2, the print function is not a real function but a statement but in Python 3 it is a function) and here the sqrt() function.

So you have been using functions all along until now, without really noticing it. And this is why people use functions, to make their lives easier and keep the complexity hidden in other places. You can define the functions inside the same file as the main program or in a separate file and then import the functions from this file.

Importing functions from other Python files (so called Python modules) allow developers to make an Artificial Intelligence (AI) application with less than 50 lines of code. The total code behind this can then be several thousands of lines, but the part that the developer is writing is only a few lines long.

Additional Notes

Using functions can make life easier, even though they appear more difficult at first. One thing you need to consider is, that they require an input and an output in case they should modify a value such as in the example above:

motor_speed = calculate_distance(210, motor_speed)

The example without the function could always use the motor_speed variable while when sing functions, you need to hand this variable over to the function as a parameter as otherwise, there will be an error that the function is not defined. This is due to the fact that variables can have different scopes. Also, if you want to change the value of a variable, you need to return it as otherwise the actual variable has not been changed. When calling a function with input parameters, the functions makes a copy of the variable values and does not change the original variables. Again, this has also to do with the scope of the variables. Later, you will learn more bout variable scopes.

In case you want to dive even deeper into the topic of functions, have a look at the article Concise Notes on Functions in Python.

Continue learning about Object-Oriented Programming (OOP) in Python or g back to revisit loops.

Programming

If you want to develop a robotic system, a computer application or a phone application, you will need to know how to program. Even if it is not necessary to develop software, I would highly recommend to get to know at least the basics.

First of all, a program is a written list of instructions that need to be followed in a specific order to reach the goal. This can be the TV program showing what show is being released at what time, the program of a play in the theater that tells you which parts are played before the break or a software program telling the processor when to do which instruction.

The following guides will tell you more about software development and programming. They will tell you in a nutshell what software is, how it is written and different elements to it.