Loops

When you write code, you might notice that you need to execute some code several times in the same or in a similar way. This could be because you need to check the value of some variables or because you do the same thing for all elements of a list.

Why using Loops

Here are some examples of code snippets that would repeat the same action (or similar).

names = ["Thomas", "James", "Nicolas"]

print("Hello, " + names[0] + "!")
print("Hello, " + names[1] + "!")
print("Hello, " + names[2] + "!")

if (names[0] == "Henry"):
    print("One of these gentlemen is called Henry Ford, correct?")
if (names[1] == "Henry"):
    print("One of these gentlemen is called Henry Ford, correct?")
if (names[2] == "Henry"):
    print("One of these gentlemen is called Henry Ford, correct?")

The examples above are typical code lines that are repeated over a certain number of times. The first example is printing the same text with different names while the second part if comparing different entries one after the other as a sequence. For 3 entries, this is no issue, but what if there is a list with 100 entries? Or even 1000? Would you then copy the same code 1000 times? Or even worse, what if the exact number is not known in advance? How to know how many times to repeat the code?

The solution for this issue would be to use loops. A loop is repeating the same thing several times and is made of several key elements: the starting point, the end point, the step size between the iterations and the code that is actually executed.

There are two types of loops: for loops and while loops. The for loops are mainly used for repeated actions with an end point after a predefined number of so called iterations. An iteration is the single execution of the code that will be repeated. So each time the same code is running another time, a new iteration is being executed. The while loops often end due to an external (or internal) condition that is often independent from the exact number of iteration. This is often used to stop a loop after an event like a button press is triggered or when a certain measurement value has been reached. Sometimes, a while loop is used to replace a for loop but to have even more control about the end point or the step size.

For Loops

The syntax of a for loop is as such:

for i in range(start_point, end_point, step_size):
    print("Execute code here several times!")

Note that the letter i here is often used to indicate the iterator, which is a variable that changes for each iteration based on the starting point, the end point and the step size. The iterator starts with the value defined as the starting point and it will end with the value defined as the end point. Then, it will increase (or decrease) after each iteration with the value defined as the step size. Also, note that the code that should be executed is indented (shifted to the right compared to the line above) to indicate which lines belong to the loop and which are not. (This is actually very similar to the conditional statements.)

The printing example at the top can therefore be written as follows:

names = ["Thomas", "James", "Nicolas"]
for i in range(0, 2, 1):
    print("Hello, " + names[i] + "!")

The code above will start with i=0 and it will increase i by the number 1 after running the code for the first time, then it runs a second time with i=1 and the iterator will be increased again. Then it runs the code again with i=2 and after that it stops. The variable i in the print statement is used as the index to indicate which name of the list we want to print.

The second part of the example can also be replaced by a loop structure combined with a nested conditional statement:

names = ["Thomas", "James", "Nicolas"]
for i in range(0, 2, 1):
    if name[i] == "Henry":
        print("One of these gentlemen is called Henry Ford, correct?")

The code above will iterate through each name in the list and check if it is equal to the value “Henry” and if it is, it will print a message. The advantage now is, that the code can easily be adapted if the list of names will be bigger.

Just like nested conditional statements, you can have nested loops. They can be either nested inside another loop, or nested inside a conditional statement. For example you could have an if-statement and inside this statement, you could have a loop.

iterations = 4
if iterations > 1:
    for i in range (1, iterations, 1):
        print(his is iteration number " + i + "!")

A very interesting case for nested loops inside loops would be if you want to go through a 2D matrix for example:

points = [[1, 3], 
          [1, 5], 
          [3, 1],
          [2, 2]]
for i in range(0, 3, 1):
    for j in range(0, 1, 1):
        points[i][j] = 0.0

The code above will set every element inside the given 4×2 matrix to 0.0 as it goes through both loops. This is often used for vision application to go through an image matrix.

The for loop can not only be used to go through a range of numbers, but it can also be used to go through a list directly. So instead of using for i in range(0,2,1) you can also write for i in names which will then go through each element of the list and execute the code. This is especially useful when the length of the list is not known and this is a very elegant way to solve this. (It is also considered the Pythonic way to use the for loop.)

names = ["Thomas", "James", "Nicolas"]
for name in names:
    if name == "Henry":
        print("One of these gentlemen is called Henry Ford, correct?")

Note that the example above uses a different name for the iterator as i is not very descriptive. Also, you now don’t use names[i] but the variable name used for the iterator name.

While Loops

While loops are slightly different and probably less obvious. They can perform the same task with some more manual intervention than a for loop. Just like the for loops, a while loop also has a starting point and an end point. The starting point is the first time that the loop is being executed. The end point is the last time that it is being executed. Unlike for loops, there is not necessarily a fixed amount of iterations that the while loops are running through. The loop ends after a certain condition is not fulfilled anymore. The only explicit parameter that a while loop has is a condition that is specified at the beginning. This condition must have a boolean state, either true or false.

The syntax is as follows:

condition = True
while (condition == True):
    print("Execute code here several times!")

The above loop will run forever. This is because there is no possibility that the condition that is checked before each new iteration will ever change its state. As a result, the condition will be always true and the loop will never end.

You can see now why some people recommend to avoid using while loops as they have the possibility to result in an endless loop. The result is a dead lock, a state that can’t ever be left.

Also you can see, why the while loop is less obvious as it requires implicitly some additional elements that are not explicitly required by the syntax such as a way to end the loop if necessary and possibly some way of keeping track of the number of iterations. For a better understanding, you can recreate the functionality of a simple for loop as well:

iterator = 0
end_value = 5
while (iterator < end_value):
    print("Execute code here several times!")
    iterator = iterator + 1    # change the number of iterations

The code snippet above shows how you can recreate a for loop manually. Sometimes, this gives you more control how the loop should react. Most of the time, though, you will not use while loops with a counter, rather you will use it with some kind of check to compare boolean values, string values or number values which will change the loop condition so the loop will finish. For example when a button is pressed, an electro-mechanical state of a sensor has changed or if the user has given a certain input.

The following example will ask the user to input his password and then check if it is correct. It will do it an infinite amount of time as long as the input that has been given is incorrect:

password_is_correct = False
password = ""
while (password_is_correct == False):
    password = input("Please enter the correct password! ")
    if (password == "123456"):
        password_is_correct = True
    else:
        password_is_correct = False
        print("Wrong password: Access Denied! Try again!")
print("Hurray, the password was correct!")

Sometimes, an infinite while loop is exactly what you want. This is rather common for the main program of a piece of software as it should not just stop but keep going forever. This is generally true for robotic systems that often use while loops to describe their main program and then run forever until they are shut down or run into an error. In this case, shutting down the loop means to change its input condition to false. However, there is another way to leave a loop without changing its input condition: the break keyword.

Breaking a loop

The break keyword can be used to exit the loop immediately. This means that the loop will not reach its end but it will exit at the spot where the interpreter encounters the break statement. Leaving the loop with a break is usually done in combination with a conditional statement.

Here is an example on how to use the break statement:

password_is_correct = False
password = ""
counter_trials = 0
while (password_is_correct == False):
    password = input("Please enter the correct password! ")
    if (password == "123456"):
        password_is_correct = True
    else:
        password_is_correct = False
        counter_trials += 1
        print("Wrong password: Access Denied! Try again!")
    if counter_trials >= 3:
        print("Maximum of trials reached, locking the device!")
        break
    print("End of this loop has been reached successfully!")

The example above shows a simple algorithm that asks for a password by using a while loop, just like in an example before. In addition to that, there is a condition that the password may not be more than three times incorrect. In this case, the loop will exit through the break statement. This simple case could also have been resolved by simply changing the variable “password_is_correct” to True, but this would have three major consequences:

  1. The variable “password_is_correct” would have a value that does not match the situation.
  2. The program would need to run code (here the input condition validation) even though this is not necessary.
  3. The rest of this loop would still be executed, even though this might not have been the intention.

When to use a break often depends on the intentions of the program and how the loop should be exited. Often, there are several possibilities to obtain the same result.

There is also a way to skip parts of the loop, this is done with the continue statement.

Continue

In some cases, you don’t want the loop to be finished at a certain point, but you also don’t want it to go through the rest of the code inside the loop. A break would be interesting to use but nit quite do the job in this case. The continue statement will make the loop skip the remaining part of the code and then continue in the next iteration.

Consider the following example where the loop simply goes through numbers 0-19 (20 is excluded) and prints the odd numbers and skips the even numbers.

for counter in range(20):
    if (counter%2==0):
        continue # skip even numbers and continue loop
    print(counter) # will not be printed if counter is even

The example above will continue with the next loop iteration after it reaches the continue statement, this means that the print statement will not be executed.

Loops are for many applications very useful, especially when you need to repeat code several times. While loops are especially useful when you want to repeat an action for an undefined amount of times, for example when the exact number of iterations is not known yet, or if there is no fixed number of iterations. Loops are a critical element for robotic applications too. When a robot needs to move forwards until it approaches a wall in front, the while loop condition will be based on the state of a sensor of the robot. There are many more examples, different for each situation.

Another interesting way to avoid the repetition of code is the use of programming functions.

Continue learning about functions or go back to revisit conditional statements.

Conditional Statements

What are conditional statements? Basically, it expresses code that is being executed only when a certain condition has been fulfilled. They are also known as “IF statements“. It can be explained by the following sentence: IF this has happened, DO the following, ELSE, do the other thing.

The keyword IF is being used to define the condition, followed by the action that needs to be done. It is possible to define an alternative action in case the condition is not fulfilled. The alternative action is defined after the ELSE keyword. The syntax in Python is as follows:

if <condition>:
    <primary action>
else:
    <alternative action>

Please note that the above code example contains pseudo-code inside angle brackets (<>). Pseudo-code is a common practice to show the idea of the code without implementing real functioning logic. Also, always make sure the condition is ended with a colon (“:”). This tells the computer that the definition of the condition has ended and the definition of the actual code starts. Omitting the colon will result in errors.

With the help of this conditional statement, it is possible to change the flow of the program, depending on the state of some event or element. The if statement can be divided into two major parts: the condition and the actions that are executed.

The condition can be a simple variable or an expression. The condition will be checked whether it is True or False. This means that the type of the condition is a boolean. So, the condition can be a variable in which a True/False value has been stored or it can be the result of an expression like a comparison or even the result of multiple comparisons combined with the keywords AND or OR. Here are two examples:

battery_is_full = True

if battery_is_full:
    <primary action>
else:
     <alternative action>

sensor_left = 0.2
sensor_right = 0.5

if (sensor_left < 0.1 AND sensor_right < 0.1):
    <primary action>
else:
     <alternative action>

The AND and OR keywords are elements for binary logic that will verify the state of several boolean states combined. The OR will result in True if at least one of the elements is True and the AND will result in True if all elements are True.

The next part is the action that should be executed when the condition is true. This can be any type of code. The only thing that you need to pay attention to is that the code representing the action must be indented. This means that there are some white spaces on the left side of the code compared to the line indicating the condition. This is to represent that the code is inside a code-block. These blocks are essential for the computer to understand which part still belongs to the actions under the if statement and which excluded from the if statement. This means that the blocks are necessary for the logical structure of the program, but also they keep the code organized. It is rather simple to see which part belongs to the action under the conditional statement and which does not. The non-indented code will then be executed regardless of the condition.

It is even possible to have another if statement inside the action part of an if statement. This procedure is called nesting. A nested if statement would be as follows:

battery_is_full = True
battery_voltage = 4.8

if battery_is_full:
    if (battery_voltage > 4.5):
        <nested action>
    else:
        <alternative nested action>
else:
    <alternative action>

Nesting blocks inside each other is a very common technique to make more complex decision algorithms. This can lead to some difficult to read and difficult to understand code which is more likely to contain logical mistakes. You could try to break the nested structure into smaller pieces:

battery_is_full = True
battery_voltage = 4.8

if (battery_is_full AND battery_voltage > 4.5):
    <primary action>
else:
    <alternative action>

if (battery_is_full AND battery_voltage < 4.5):
    <primary action>
else:
    <alternative action>

In the above example, there is no nested structure anymore, making the code a little more readable. However, there are some disadvantages. What would happen if the battery_is_full variable would be False? Then, the conditions for both if statements would be false and for both cases, the code under the ELSE part would be executed even though in the nested part, there was only one ELSE that would be executed. To differentiate the cases where battery_is_full = False would be covered, you would need to have four conditional statements under each other. You see, the code would be more explicit, but also more lines of code and more to type in order to cover the same logic. Also, you can see that the conditions are now more complex than with the nested structure. These are some things that you might want to consider before writing the code.

The final part of the conditional statement is the alternative code that is being executed. It is defined after the ELSE keyword followed by another indented block of code. This block defines the code that is being executed if the condition is False and the first code block is not executed. This part is not mandatory and can be skipped.

battery_is_full = True
battery_voltage = 4.8

if (battery_is_full AND battery_voltage > 4.5):
    <primary action>

if (battery_is_full AND battery_voltage < 4.5):
    <primary action>

There is one last thing that can be used to make the code more efficient. In the case above, the two conditional statements are verified even though they are mutually exclusive, meaning if one is true, the other can’t be true as well. This means that the second statement is obsolete when the first one is already being executed. (To be fair, for the example above, this makes no difference, but when the conditions are getting much more complex and there are many more situations to verify, this can be time-consuming for the computer.) To avoid this, there is a combination of IF and ELSE that helps you combining the advantage of a nested structure with the advantage of a flat code structure: ELIF. The ELIF part can be used between the IF and the ELSE part of the conditional statement. There can be as many ELIF parts as you need. The ELIF keyword is followed by another condition, just like the IF keyword in the first part.

battery_is_full = True
battery_voltage = 4.8

if (battery_is_full AND battery_voltage > 4.5):
    # battery is full
    <primary action>
elif (battery_is_full AND battery_voltage < 4.5 AND battery_voltage > 3.3):
    # battery is still usuable
    <alternative action 1>
elif (battery_is_full AND battery_voltage < 3.3):
    # battery start to be empty, set battery_is_full to False
    <alternative action 2>
else:
    # battery is empty
    <alternative action 3>

The above structure keeps the code somehow organized and with the comments, it is rather easy to keep track of all possible statements. Also, the list of different cases can go on and on without creating a nest in a nest in a nest… There is no one-size-fits-all solution for code, but sometimes one solution has more advantages. In general, you can go for the more structured method over the more efficient method as most computers are very efficient. And the more structured the code is, the easier it is to understand, modify and maintain.

Continue to learn about loops or go back to revisit inputs and outputs.

Inputs and Outputs

In the following section you will learn how to manage the inputs and outputs of a Python command line program. Also, in this part you will write your very first Python program. Please not that this guide is written for Python 2. For this part, there are some differences between Python 2 and Python 3 which will be explained in this guide.

Outputs

Let’s start with the outputs. Why? Because it is easier to start with that. The outputs of a basic Python program will occur through the terminal in form of text. This text will be handled inside Python as a string. With the following code, the string can be printed on screen:

print "This message will appear on screen"

This is a print statement. As its name says, it prints something. This something is the indicated text in double quotes (” “). This text is nothing else than a data string, just like the variable type. Instead of the double quotes, you can also write single quotes (‘ ‘).

It is also possible to print the text that has been stored inside a variable directly:

name = 'Shacky'
print name

The output of these lines would be simply the content of the variable name. A last thing that you might need to know is that you can also combine (concatenate) strings to form a more complex message.

name = 'Shacky'
serial_number = 39271947

print "My name is %s and I my serial number is %d." % (name, serial_number)

As you will see, the %s and the %d will be replaced by the values of the variables specified at the end. the %s is used for strings, the %d for integers and if needed, %f will be used for a float.

An alternative method would be to use the .format option. This is a more modern method for formatting the variables:

name = 'Shacky'
serial_number = 39271947

print "My name is {0} and I my serial number is {1}.".format(name, serial_number)

This method allows you to use the same variable several times by indicating the index of the variable in between curly brackets ({1}).

You could also simply add the elements with a plus sign between the individual elements. This would also work fine, but it is considered bad practice. Here you would need to include the white space before and after the quotes as otherwise the values of the variables would be sticking to the words before and after the inserted variable.

name = 'Shacky'
serial_number = 39271947

print "My name is " + name + " and I my serial number is " str(serial_number)

Now you are able to output text. This can already be used to make very simple programs that would simply display you some text and numbers. This could be used to display the results of some calculations or to display the time. When using the Python language in inter active mode, the print statement might not be very useful for this task though.

Note

The code shown above is valid for Python 2. The print statement has a slightly different syntax for Python 3. Instead of giving the argument in double quotes after the print keyword, you hand it in between parentheses. In this way, the print statement is handled like a function. The double quotes are still mandatory for string messages.

print("Hello World")

Now you are able to understand the hello world program that was already shown in the Programming Languages page.

As you can also write the parentheses for the Python 2 syntax, even though they are not mandatory, there is nothing wrong in writing them. This makes it easier to write Python programs regardless if it is version 2 or 3.

Inputs

The inputs of a basic Python program are given through the terminal. The terminal will prompt you to enter a value, often with a message, and when hitting enter, it will hand the input to the Python program. Sometimes, this is simply used to stop the program at the end so that the user can see the output on the screen before the window closes.

There are two main types for receiving the inputs in Python. There are the input() and the raw_input() functions. These functions return the value that has been entered in the terminal window as a string. The raw_input() function gives you the value as a simple string while the input() function tries to interpret the content as a Python command. Usually, you want the raw_input(). Also, you probably want to store the content of this function inside a variable. Inside the parentheses you can enter e string that will be shown on the screen so that the user knows what input is expected.

name = raw_input("Please enter your name and press ENTER")

The above example will show the message: “Please enter your name and press ENTER”. When entering your name and pressing ENTER on the keyboard, the input will be stored inside the variable called name. The fact that the message mentions the ENTER key is only for information to the user, it does not influence the actual key mapping. The ENTER key is always the one that needs to be pressed for continuing the program.

Note that the value obtained from the raw_input() will always be given to you as a string value. When you want to get an integer or float, you need to convert it first into the correct variable type.

speed = int(raw_input("Enter speed in RPM: "))
voltage = float(raw_input("Enter the voltage (Range -> 0.0 .. 5.0 V): "))

The raw_input() command is very useful to provide a really simplistic user interface. It can tell the user what is expected and combined with the print statement, it can display the output of your program.

Basic I/O Python Program

Now you can combine the previous segments to make a very simplistic program that will ask the user for the name, the age and then returns the number of years until the user turns 100. This simple program might appear silly to you, but it is the first step towards bigger programs.

#!/usr/bin/env python
print("Hello, this program will tell you when you will be 100 years old.")

name = raw_input("Please tell me your first name: ")
age = int(raw_input("Please tell me your age: "))

years = 100 - age

print("Hi {0}, in {1} years, you will be 100 years old.".format(name, years))
raw_input()

The above program will ask the name, the age and will then return the remaining years. The very first line is called the hash-bang, or she-bang and it tells the computer that this is a python program. The very last line will prevent the program from exiting before the user had the possibility to read the message.

That’s it, when you copy this code into a text editor and safe it for example as calculateAge.py you can run it with:

python calculateAge.py

You just made your very first Python program. Congratulations. The next part will explain how you can implement code that verifies if a certain condition is met. Depending on that, you can make your program decide what it should do. These are called conditional statements. If a condition is true, it will do something, if it is false, it will do something else.

Continue learning about conditional statements or go back to revisit arithmetic expressions.

Arithmetic Expressions

Arithmetic Expressions? What? This is nothing more than a fancy word for “calculating”. Though, it covers a little more than only working with numbers. Arithmetic expressions can be used with number data types, booleans and with strings.

Addition and Subtraction

The most basic and most intuitive arithmetic expressions are addition (indicated with a plus “+”) and subtraction (indicated with a minus “-“). They can be used for integers and floats.

a = 5 + 3
b = 7.3 + 32.9
c = 43 - 3.6

Note: In the examples, the results of the calculations are stored in variables as you have not seen how to use the results directly, but basically you can also use the result of an arithmetic expression as an input for functions or use them otherwise.

The addition expression can also be used on strings. Obviously you can’t calculate with words and characters, but you can add them together to form a new string. This is called “concatenation”.

first_name = "Harry"
last_name + "Hendrickson"
full_name = first_name + last_name

Note: In this example, the resulting string would be “HarryHendrickson” as there is no white space between the words. This needs to be added separately. You could add a pair of (double) quotes containing a single white space character to separate the two words.

full_name = first_name + " " + last_name

Note: You can’t add a number and a string. Here it is important to distinguish a number (e.g. 5) from a number in form of a string (e.g. ‘5’) as they will not work together. The reason for this is that Python will not be able to know if you want to use the string as a number (e.g. to create 10 as a result) or if you want to use the number as a string (e.g. to create the string ’55’ as a result).

Multiplication and Division

Another very intuitive expression is multiplication (indicated with an asterisk “*”). Multiplication is used to multiply numbers to get the resulting product.

a = 2 * 4
b = a * 3.4
c = 15 * (-0.5)

Like with addition, you can use the multiply operator for strings as well. Here, the string will be repeated the amount of times specified by the number after the multiplication symbol.

a = "ha"*3
b = 5*'Nope! '

The examples above will result in “a = ‘hahaha‘ ” and “b = ‘Nope! Nope! Nope! Nope! Nope! ‘ “.

The division (indicated with a forward slash “/”) behaves differently for integers and floats and also different for Python 2 and Python 3. As you are learning Python 2 in this guide (as it is used in ROS), it does make a difference if you divide integers of floats. (For Python 3, there is basically no difference.)

When using the division operator with floating point numbers, the result will be exactly what you expect. The result is the result of the first number divided by the second number. The result will be a float type number regardless if the resulting number has a decimal value or not. This holds even true if only one of the numbers is a floating point number and the other is an integer type.

a = 10.5 / 2.0
b = 4 / 2.0

In the above example, “a = 5.25” and “b = 2.0”. Everything as you would expect. In Python 2, when dividing an integer by another integer, the result will always be an integer.

c = 10 / 2
d = 7 / 2

In the above example, “c = 5” and “d = 3”. Wait what?! As you can see “c” is being calculated as it should, but the variable “d” is wrong? What is happening is, that the result is being forced to be an integer value which means that everything behind the decimal point will be lost, thus “0.5” is just being lost. (In Python 3, the result would simple be a float instead.)

Modulo

Okay, not it will become a little more complicated. The modulo operator is very useful to verify the property of some numbers like to see if it is an even number or not. It is only used for integer type numbers and represents the remainder of an Euclidean division which is defined by:

a = b * q + r

where “q” is the quotient and “r” the remainder. “a” is the initial number that is divided and “b” is the number that “a” is divided by. In other words, if “a” is divided by “b”, the result is “q” if “a” is dividable by “b”. If not, “q” would be a number with a decimal value. But in the formula above, “q” is always an integer which means that there is a remainder “r” that will be left out. If “r” is zero, “a” can be divided by “b”.

The modulo operator is indicated with a procent sign (“%”). To stick with the same variable names as the example formula:

r = a % b
pizza_left = 8 % 3

One example where you also can use the modulo operator is to keep values within a specific range. For example, when a wheel is spinning, it will turn 360 degrees before it returns to the same position. So if it rotates 380 degrees or 20 degrees, the position is the same. Hence:

resulting_angle = 380 % 360
number_of_rotations = 380 % 360

As you can see, the integer division and the modulo operator can go quite well hand in hand.

Exponentiation

Exponentiation is a way to calculate a number multiplied with itself a certain amount of times. This can be part of a formula such as A = r²*Pi which equals to:

 area = r * r * pi

This is quickly done for a small exponent such as given above (the exponent is equal to 2). For the propper way to write exponentiation, the exponent can either be expressed with the math module (you will see about modules later) or by a simple build in notation with two asterisks.

area = radius**2 * pi

The above solution would be the prefered way to express exponential expressions.

Square Roots

To calculate the square root, again you could use the math module of Python or you can use a simple trick. When you think about the square root of a number, you can also express it as a number with the exponent of 0.5 which will get you the same result.

area = radius**0.5

This notation will probably be the most simple one.

This is about everything you need to know about the necessary tools for creating arithmetic expressions in Python 2.

Continue learning about inputs and outputs or go back to revisit complex data types.

Complex Data Types

After investigating the most basic data types for variables, you can now proceed with a little bit more advanced data types.

The more advanced types are:

  • Tuple
  • List
  • Set
  • Dictionary

Tuple

Let’s start with tuples. They are the simplest composed data type in Python. By “composed” I mean that they can contain different values at the same time while without mixing them together. They are described within parentheses “( )” around the values, separated by commas. Tuples can contain any kind of data types, even other tuples, lists or dictionaries and you can mix the data types used within a tuple.

rotation = (0.123, 0.426, 0.783)
greetings = ("Hello", "Good Morning")
employee = ("Steve", "Johnson", 42, ("glasses", "brown hair", "green eyes"), True) 

If you want to access the individual elements of a tuple, you need to write the name of the tuple followed by square brackets “[ ]”. Inside the brackets, you give the index (i.e. position inside the tuple) with an integer starting with zero as the first element.

pitch = rotation[0]
appearance = employee[3]
eye_colour = employee[3][2]

Good to know about tuples is, that their individual elements can’t be modified. Once created, they remain the same. If you want to change an element, you need to create a new tuple. Read more about tuples on the W3Schools website.

List

Next, let’s talk about lists. A list is made to list things, similar to tuples. The main difference is, a list can be modified. They are described within square brackets around the values, separated by commas. Also here, the data types inside a list can be of any type including other lists.

names = ["John", "Jane"]
position = [1.2, 3.0, 0.5]
matrix_2x2 = [[0, 1],[0, 1]]

If you have a list in a list, it might be interesting to write it like a table. (The same actually applies for tuples.)

matrix_3x3 = [[0, 1, 1],
              [0, 1, 0], 
              [1, 0, 1]]

A list can be modified which means that you can access each element of the list and change it without the need to make a complete new list. Again, the indexes are given in square brackets and start with zero.

matrix_3x3[0][0] = 0
names[1] = "Sarah"
position[2] = position[2] + 1

If you want to replace an element, the above method is fine ,but what about extending the list by adding an element at the bottom? There is a function built into the list. You can use it with:

list_name.append()

The element that you want to add to the list needs to be specified in the parentheses at the end.

names.append("George")

Lists have even more functions that ca be accessed like this such as “remove” or “insert”. Read more about lists on the W3Schools website.

Set

A set is similar to a list. The main difference is, that a set is not having any order. The are described within curly brackets “{ }” around the values, separated by commas.

books = {"Sherlock Holmes", "Tom Sawyer", "Lord of the Rings"}
interesting_pages = {12, 23, 54, 62, 102}

In a list, the elements are neatly stored one after the other and their position remains the same. In a set, this is not a case. This means that the following sets are actually the same.

books1 = {"Sherlock Holmes", "Tom Sawyer", "Lord of the Rings"}
books2 = {"Sherlock Holmes", "Lord of the Rings", "Tom Sawyer"}
books3 = {"Tom Sawyer", "Sherlock Holmes", "Lord of the Rings"}

As you can’t access the individual elements of a set, you can’t change them either. Though, you can add elements to the set.

books.add("Moby-Dick")
interesting_pages.add(201)

The lack of a numbered structure also means that there is no way you can use an index to access the elements. What is the use of this then? Until now, you have not seen the necessary tools to use sets, but you can use sets to see if a value can be found within a set or you can apply an algorithm to each element of a set. Read more about sets on the W3Schools website.

Dictionary

Dictionaries are comparable to sets. They also have no order so you can’t use an index to retrieve the elements. However, dictionaries have “keys” with which the elements can be accessed by. The are described in curly brackets starting with the name of the key in quotes followed by a colon “:” and then the value. If the value is a string, it is also inside quotes.

vehicle = {
    "type": "car",
    "brand": "Fiat",
    "model": "Punto",
    "year": 2015,
    "last_repair":{"what":"oil change", "when":2019}
    }

Like the other complex data types, dictionaries can contain all other data types as well. You can access and change the value of an element by referring to its key. The same way you can add new keys to the dictionary.

last_time_in_garage = vehicle["last_repair"]["when"]
vehicle["model"] = "Picanto"
vehicle["color"] = "red"

Dictionaries can be a good choice for storing data of a physical object, depending on the needs of the program. Read more about sets on the W3Schools website.

Note:

Sometimes you need to create a variable such as a list or a dictionary before you will know what you store inside it. In these cases, you can create an empty variable and fill it later. This can be done by leaving the respective brackets empty. Note that there is no use of creating empty tuples. This is also why it is not possible.

list_entries = []
dictionary_entries = {}

Another thing that is good to know is that you can get the number of entries in a tuple, list, set or dictionary.

length_of_tuple = len(tuple_entries)
length_of_list = len(list_entries)
length_of_set = len(set_entries)
length_of_dictionary = len(dictionary_entries)

This is everything about the standard data types that you need to know to have a solid foundation before you start with the actual programming part. The next step is to get to know the different types of operators to start calculating in Python.

Continue learning about arithmetic expressions or go back to revisit the basic data types.

Variables

The first element that you need to know about programming is the concept of variables. A variable is basically a space in your computer’s memory to save data during run time (i.e. while the program is running). This is similar to a human that is thinking something. The fact that he is keeping the thought in the back of his mind is comparable to the program storing data in a variable.

Variables

For making the concept a little bit more visual, you can think of a variable as something like a bucket. Inside this bucket, you can store data. The question is not, what is this data? And here comes the tricky part. In a bucket, you can fill whatever you want (even if it does not really fit inside and sticks a little bit out of the bucket). With a variable, you can not do the same as in programming languages like C or C++, every variable is made to store a specific type of data like numbers or words. (Python is a little bit less strict in this regards, but you should still know about this.)

This means that in C, if you want to store a number inside a variable, this variable needs to be made for that number type. You can’t simply store a word inside that variable. Also, it is not possible to store a number inside that variable if the number is too big. You could compare this like there were buckets especially made for numbers. Let’s say these buckets have a square shape. A square shaped number will fit inside the bucket, but a round shaped word will not fit inside as the bucket is not made for round shaped objects.

One thing that you also should notice is that the variable must exist before you store data inside of it. Similarly, you first need to have a bucket to place something inside the bucket. This is usually called, the variable is initialized and this is also where you define what type of data it is allowed to store.

The ‘variable for each type’ thing holds true for most languages out there, but Python is a little different. Remember what the programming languages guide said about Python? Python is doing some things for you, in this case, it will allow to fit every data type into every variable no matter what. It just doesn’t care about these rules as this is all happening in behind the scenes. Also, Python does not care about the initialization thing either. (What a rebel.)

Using Variables

An important thing about variables: each variable has a name. This name must be unique inside the scope of that program as otherwise, the computer might confuse the variables if they are all called the same name. The syntax is generally similar to the following:

variable_name = variable_value
_variable = _value

Variables are often named with the words all lower case and separated by an underscore. The name can be anything you like but there is one rule: it must start with either a letter or an underscore. This means it can’t start with a number or a special character in front.

You can also assign the value of a variable to another variable.

variable1 = something
variable2 = variable1

In this example, the variable called variable1 will have the value something and the variable2 will have the same value as variable1, thus something.

Continue learning about basic data types or go back to a general explanation about programming languages.

Basic Data Types

Now, let’s discover the most basic data types that are available out there. These are:

  • Integers
  • Floating Point Numbers
  • Boolean Values
  • Strings
  • Characters

Integers

Let’s start with Integers, or Int for short. An Integer is nothing else but a whole number (i.e. 0, 1, 2, 50, -73, -101). It is usually used for counting. Or quantifying in discrete steps. In Python you assign an integer as follows:

value = 15
number_of_wheels = 4
height_in_cm = 10
x = 7

Floats

Next, a Floating Pint Number, or Float for short, is a number with a decimal part (i.e. with a decimal point). Floats are usually used to store continuous information such as measurement values. The decimal part still can be zero though. (Note that the decimal point is a dot and not a comma.)

temperature = 52.6
voltage = 4.692
a = 3.0

Booleans

The next category are Booleans, or Bools for short. A bool can only contain one of two values: True or False. They are usually used to describe the state of a binary property such as if a condition is true or if a device is turned on.

battery_is_full = True
motor_is_on = False

Strings

The next type are Strings, sometimes called Str. A string is basically a word or even a sentence. These words can be anything you like. Also, because Python would not know if you want to assign a word into a string variable or the value of another variable, you must specify the value inside quotes (‘ ‘) or double quotes (” “). There is no difference between the different types of quotes, but you are allowed to use a quote inside a sentence if it is the different kind of quotes that you use to specify the string (like ” it’s “).

greeting = "Hello Dave's RoboShack!"
robot_name = 'Shacky'

Characters

The last type is called a Character, or Char for short. It has pretty much the same properties like a string except that a char is maximum one letter long. Basically it is a string with one single letter.

initial = "D"
subject = 'B'

In Python, there is not really a use for chars. In C for example, a string is nothing else than a list of chars. (Lists are covered in the next part of this guide as they are already a little bit more complex data types.)

Note:

It is pretty easy to confuse strings and numbers. How? Let’s see:

a = 2
b = 3.5
c = '32'
d = "2.3"

In the examples above, it might seem clear which of these variables are strings and which are ints or floats due to the quotes. But if you work with them in a program, it is quite easy to oversee this which can turn into quite some headaches when debugging. Even though it looks like they are the same, they are not. Later, you will see how you can convert a string into a number type and the other way around to work with them.

Continue learning about complex data types or go back to revisit variables.

Programming Languages

If you want to learn about programming, you first need to know about programming languages.

A programming language is human-readable code that is written by the programmer. It’s main property is to be understood by humans while the computer doesn’t understand it at all. Computers use machine-readable code to understand what they need to do. As computers these days work in a binary system, they can only understand two different states: 0 and 1. In a computer, everything is ruled by zeros an ones which is the only logical way to work for a machine, but not for humans. As this is causing a communication problem for the programmer, there is a tool that can translate human-readable code into machine-readable code. This tool is the compiler.

The compiler translates the instructions that the programmer is writing into zeros and ones so that the computer understands what you want. So the basic steps are: the programmer writes the code, he compiles it and then the computer can execute it. Depending on the compiler and the length of the code, this can take seconds, minutes or even hours. In order for the compiler to translate the code, it is important that the code is written in a very specific manner including keywords that need to be used, a structured syntax how to present the code and a certain consistency of certain patterns. These things combined form a programming language.

Each language has slightly different elements that make the language unique. This can be the keywords, the syntax or the way the compiler translates the code. Each language will therefore require its own compiler in order to work.

Probably the most prominent programming language is the C Programming Language, or C for short. It has been developed by Dennis Ritchie and it is used for programming operating systems, software for computers and even for hardware. An important extension to the C language is C++ (called C-plus-plus) developed by Bjarne Stroustrup. Those languages are quite similar to each other and have the advantage of fast execution once the program has been compiled. The disadvantage is, that they require a steep learning curve and long development times due to the fact that you need to manage everything on your own and the program need to be compiled before execution.

Another language that has become extremely popular is called Python and has been developed by Guido van Rossum. This language is not compiled but interpreted instead by a interpreter. The interpreter is a program that will translate the human-readable code during the execution of it. This makes the development process much faster as you don’t have to compile the code before testing it. At the same time, Python is simplifying the programming process a lot as it will take over some tasks automatically (such as memory allocation, etc. ). Unfortunately, this results in slower software when running it compared to a compiled language. Python is very easy to read and write compared to C and therefore it is often recommended as the first programming language for becoming developers.

Below, you will see an example how a program will look like when using the C language. The example shows the Hello World program written in C. This is often considered as the easiest example of a valid program and often used to demonstrate the syntax of a program.

#include <stdio.h>
int main() {
// printf() displays the string inside quotation
printf("Hello, World!");
return 0;
}

Now you can compare this to the Python version of the same program.

#!/usr/bin/env python
print "Hello World"

As you can see, there are quite some differences. A small side note: programming languages develop over time and get new features in each new version. This means that each version will have some differences. The Python code above is written following the rules of Python 2.7 while the latest version Python 3.8 will have a slightly different syntax.

This guide will mainly focus on covering Python 2.7 as it is used in many applications even though it is not the latest version. (Some people just never wanted to switch over to the newer version and keep using 2.7 instead.) Also, the Robot Operating System (ROS) is also using version 2.7 of Python.

Continue learning more about variables or go back to the overview.