Learn the basic concepts of the programming language Python, a great language for programming Raspberry Pi and more!

This article will introduce you to the basics of the Python programming language so you can quickly start writing code for your projects. If you need a short introduction to the basic concepts themselves, take a look at Getting Started With Python.

Variables in Python

Python is a loosely typed language and therefore you don‘t need to declare variables with a fixed type and they can also change their type at any time. Furthermore, python doesn‘t support the use of access-modifiers. A variable declaration is simple and looks like this:

        VariableName = value
    

Here are a few examples:

        patientAge = 24
accepted = true
surname = “Lobowski“
    

Python doesn't have traditional static variables, like, for example, Java. Instead, it creates a copy of that variable for the class itself and one for each object created.

Methods and Function Declarations

Method and function declarations are pretty simple too. You don't need to supply a return type or an access modifier for the function. An optional list of parameters can be supplied. 

Each entry in this list consists of the parameter name and an optional default value, separated by commas:

        def functionName([param1[, param2[, (...)]]]):
    // Your code
    [return value]
    

As you can see, an optional return statement can be added and the return type is determined by the returned value. If you want to declare a static function, use the “@staticmethod“ annotation. Here are some examples:

        // If you don’t supply a default value for each variable
// write the variables with the default value at the end
// of the list
def add(one, two=10):
    return one + two

@staticmethod
def initialize():
    // Do something
    

Obviously, static methods have to be declared inside of a class (the code snippet above is just an example for method declaration).

Collections in Python

Python doesn’t implement arrays the way other languages like C and Java do. Instead, lists with a variable length and mixed data types are used. However, you can define array-like structures for numeric data types:

        import array as python_array

a = python_array.array('d', [1, 24.0, 3.14])
    

The elements can be accessed by using their index:

        print(a[0])
print(a[1])

a[0] = 2222
    

Just remember that indices start at zero. You can use len() to get the length of an array:

        print(len(a))
    

Like mentioned above, arrays in Python are different from other languages. Python arrays are not of a fixed length. You can always dynamically remove and add elements:

        // Add three elements to the end of the array
a.append(10)
a.append(20)
a.append(30)

// Remove the first three element
a.pop(0)
    

For a full list of features refer to Python's official documentation.

The array, mentioned above, is an optimized special form of the list that only accepts numeric values of the same type. Therefore a list can be used exactly the same way as an array but you are not limited to using one data type:

        li = ["Apple", 2.0, 3.14, "Banana", "Pear", [1, 2, 3, 4, 5]]
    

As you can see, “li” can contain anything at any time. All the other functions mentioned above work exactly the same way they did for arrays.

Another type of collection is the tuple. Unlike the elements in a list, the ones in a tuple can’t be changed upon initialization:

        // Note the round brackets instead of the square ones
tu = (1, 2, 3, "cat", "dog", "parrot")
    

Insert, update and delete operations won’t work but elements can still be accessed with their index.

The next important data structure is the set. The elements contained within one can’t be indexed like before but you can always add new elements and remove existing ones from the set. You can also check if a value is an element of the set:

        s = {"pie", "bread", "steak"}

print(s.pop())

s.add(30)

print(len(s))

s.pop()

print(len(s))
    

The pop()-function doesn’t take any parameters here and it returns the element that got removed. You can insert new elements with the add()-method. Again, for a full list of functions refer to the official documentation.

One last data-structure is the dictionary. This collection links two values together in a key and value relationship where each value can be referenced using a unique key:

        telephone_book = {
	"Peter":9238172,
	"Laura":1119823,
	"Mark":9952174,
	"Liz":8009822
}

print("Laura\'s phone number is:")
print(telephone_book["Laura"])
    

Values can be changed in the same way and len() will give you the length of the structure. You can add elements by using a new key as the index and assigning a value to it:

        telephone_book["Ben"] = 5557281

print("Ben\'s phone number is:")
print(telephone_book["Ben"])
    

You can use pop() together with the key to remove an object, just like with lists.

The if-condition and Loops

The if-condition is pretty straightforward and exactly what you’d expect:

        a = 20

if a > 100:
	print("a greater than 100")
elif a >= 50:
	print("a is between 50 and 100")
else:
	print("a is less than 50")

print(a)
    

You can define as many elif-branches as you like but they are, like the else at the end, entirely optional.

For-loops can be used to quickly iterate over a set of values that can be stored in any of the structures discussed above. You can use the following syntax to do so:

        for x in any_collection:
    // Do something with x
    

But they can also be used the traditional way with a starting, an ending and an increment value:

        for i in range(0, 100, 1)
    

The loop above starts at zero and counts to 99 incrementing “i” by one with each step. The start and increment values are optional. At default, the range will start with zero and increment by one. Python also allows you to use the else-keyword in combination with a for-loop:

        for i in range(0,100,1):
	print(i)
else:
	print("Loop done!")
    

The code inside of the else-block will be executed after the loop finished.

The last important structure is the while-loop which will run as long as a defined condition is met:

        i = 0

while i < 100:
	print(i)
	i = i + 1
else:
	print("Loop done!")
    

This while-loop will do the exact same thing as the for-loop above. Two important keywords that can be used inside of loops are “break” and “continue”. “Break” will exit out of the loop and “continue” will skip the code that follows it and start with the next iteration of the loop.

Daniel Hertz
Hi! I am a software engineer and owner of nerdhut.de who loves to experiment with electronics, gadgets and tech in general.

Categories