The Fundamentals of Coding

First coding lesson if you absolutely don’t know anything

Christophe Leborgne
The Python Coder
Published in
10 min readMay 10, 2021

--

Photo by Annie Spratt on Unsplash

Data, Instructions, and Logic

In this article, we are going to browse the three basic elements of coding: Storing data, sending instructions to the computer and inserting some logic into your scripts.

We will give you some basic examples of code, to demonstrate how the concepts we talk about are actually implemented. It is of the highest importance that you type those examples onto your own computer and launch them. Use the Python Interactive Shell or create a test.py file and launch it by typing the following command from the command line as explained in the previous post

$ python test.py

If you limit yourself to only reading the code, then you will have forgotten it tomorrow. Please type the scripts, do NOT copy them from this page. You will make typos and this is the only way to thoroughly understand how they work.

Storing Data

Atomic data

Before you can do anything with your data, you need something to hold their content. The most simple thing you can use to store data is called a variable. We declare variables by assigning them a value.

i = 0
pi = 3.1415926
str1 = 'Hello'
str2 = "World"
conditional = True

Variable names can any combination of letters, numbers and underscore signs (_). The only limitation is that the first character of a variable name cannot be a number. Be careful, variable names are case-sensitive, and thus str is not the same as STR or Str.

Variables also have a type. In python, types are integers, floating numbers, string (a character being a string of unitary length) or boolean (True or False). We define strings using both single or double quotes indifferently.

For more on variables and types, read directly from the official python documentation.

Simple Data Structures

Storing data into variables is the essence of data handling, but will soon be too limited. To store some more sophisticated data, we need some more advanced data holders. In python, the main two are lists and dictionaries.

Lists

Lists are collections of variables. They are represented using square brackets, with items separated by commas.

weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
primes = [1, 2, 3, 5, 7, 11, 13, 17, 19]

We access the elements in a list using their position in the list, called their index. The index starts at 0. So, if my list is called L, to get the first item of L, I write L[0] to get the first element of the list, L[1] for the second item and so on.

>>> weekdays[0]
'Sunday'
>>> primes[4]
7

We can access the number of elements in a list, its length, using the len() function. And we get a subset of a list, we call it a slice, using the [start:end] syntax. Note that end is not included and that you can omit start and then it is implicitly the beginning of the list. Or omit the end and then it is implicitly the end of the list

>>> len(weekdays)
7
>>> weekdays[2,4]
['Tuesday', 'Wednesday']
>>> primes[:2]
[1, 2]
>>> primes[5:]
[11, 13, 17, 19]

We won’t explain here all the many possibilities of the lists. We will discover them as we need them.

Dictionaries

Dictionaries are another very helpful data structure in python. They are lists of key/value pairs. As opposed to lists which only contain values, in a dictionary you can name or tag your data. Dictionaries are represented using curly brackets and keys and values are separated by colons, pairs are separated by commas

Person1 = {'last_name': 'Doe', 'first_name': 'John', 'age': 42}
Person2 = {'first_name': 'Jane', 'age': 29}

Keys must be unique. Trying to use twice the same key would lead to an error. We access items in a dictionary using the key instead of the index.

>>>Person1['last_name']
'Doe'
>>>Person2['age']
29

Once again, we are not going to list all the possibilities of dictionaries right now, this would too long and we will discover them when needed.

There are other data structures like tuples or sets but they are less used and we won’t talk about them in this section.

For more on data structures, please read the official python documentation

Instructions

There are oh so many! We will just quickly present the most common and we will discover some more as the new articles will come.

Display something

Just like we did in the previous article, the most basic thing we can do is displaying a value or the content of a variable. This magic instruction in python is print with what you want to print between round brackets. Be careful, the content must be of type string or you might get an error message with older versions of python.

>>> print('Hello world')
'Hello world'
>>> s1 = 'Hello'
>>> s2 = 'World'
>>> print(s1 + ' ' + s2)
'Hello World'
>>> pi = 3.1416
>>> print("pi is equal to " + str(pi))
'pi is equal to 3.1416'

In the first example above, we just print a constant and the result is quite obvious.

And, in the second example, we aggregate (in CS, we say concatenate) two string variables with a constant space in the middle using the ‘+’ operator.

Finally, in the third example, we want to display the concatenation of a constant string and a floating number. We thus have to use the str() function that will change any numerical type to its string format. If we forget to use str(), we will get an error message that says that python cannot concatenate strings and floats.

Calculation

The four usual math operators are all available of course

>>> i = 1
>>> print(i + 1)
2
>>> print(2 * i - 4)
-2
>>> print(12 / 2)
6

Be careful with the integers division. In older versions of python 5/2 was 2. Now 5/2 is equal to 2.5 and they have added the ‘//’ operator for the integer division. The remainder of the integer division, the modulo, is obtained using the ‘%’ operator

>>> 5 / 2
2.5
>>> 5 // 2
2
>>> 5 % 2
1

There are millions of things, computers can do! We are not going to describe them all, right now. Just remember that coding, is basically, writing scripts that computers can play and DO things.

Logic

We are not going to present the whole science of algorithmic here but the very basic elements of a script logic.

Conditions

Unless your script is very simple and is purely sequential, it is very probable that you will need to evaluate conditions and do something if a condition is true or something else if the condition is false. Imagine the following simple quiz game: Ask the user to enter a number between 0 and 10, if the answer is the number you had picked, say 7, then display “You win” else “Bad luck. Correct answer was 7”. In python, this would be:

answer = raw_input()
if int(answer) == 7:
print("You win")
else:
print('Bad luck. Correct answer was 7')

Let’s read it, line by line. First, we use the raw_input() instruction to ask the user to input value and store the value in a variable called ‘answer’. It is going to be a string.

In line 2, we transform the string ‘answer’ to an integer using the int() function (we will see functions in a later section) then we compare it (note the two ‘=’ signs) to 7 and decide what to print. Line 2 can be read “if answer is 7 then do something” — in this case print(“You win”) — or jump directly to line 4 without executing line 3 if the condition is not met.

The general form for conditions is then

if conditional_expression:
do_something
else:
do_something_else

Note that only the first two lines are mandatory. It is not mandatory to use the else: instruction. Be very careful to the colon at the end of the if <condition>: line. You will forget it sometimes and this will lead to an error when trying to execute your code.

Note also, and this is typically pythonic, the offset of 4 spaces before do_something or do_something_else. This offset is called indentation and is absolutely fundamental in python. Everything that is aligned is at the same level and will be executed sequentially. This is how we define “blocks of code” in python. In other languages, we use opening and closing symbols to mark blocks (most of the time, they are curly braces) but in python, the only indentation is needed to mark blocks of code.

Let’s just check these two examples and see how they differ

name = raw_input()
if 'o' in name:
print('there is an o')
print('You win')

or

name = raw_input()
if 'o' in name:
print('there is an o')
print('You win')

Do you think they are the same and will end in the same result? The only difference is the indentation of the last line. If you try them, you will see that there is a difference. In the first script, you get the ‘You win’ message, only if you entered a string that actually contains an o. With the second script, you get the ‘you win’ message whether you enter a string with an o or not.

Why this? In the first script, the last two lines are indented at the same level and then they are only executed if the condition is true (the string name contains an o). If the string contains no o, the script jumps at the end of the block, in our case, the end of the script and then exits. In the second script, the condition is evaluated at line 2, if it is true, line 3 is executed and then the script carries on at the next line, here line 4.

But if the condition is false, the script avoids the block and carries on at the same level as line 2 and then carries on at line 4. Line 4 is thus always executed, whatever the condition is. On trivial scripts like this one, you will easily debug it, in case you get an unexpected result. But in bigger programs, indentation mistakes are a very common source of errors. Just be careful!

Loops

Computers are very good at doing tasks repeatedly without feeling bored. Well, that’s why they were created. They are automatons!

The for loop

In Computer Science, there are two kinds of loops. In the first kind, you know how many times you want to repeat something. For instance, for each element in a list, do … For all numbers between 0 and 10, do … The syntax for these loops is the following

days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
for day in days:
print(day)

This tiny script will result in printing all the elements of the list of days.

How does it work?

At line 1, we just set the variable days to a list of strings. Then at line 2, we loop through the list. The first time we execute line 2, the variable day is equal to ‘Mon’ and we go to line 3, and print it. Then, because we are in a loop block, the program goes back to line 2, and the variable ‘day’ is now equal to ‘Tue’. And then the program prints it and, because there are still elements in the list, we go back to line 2. And so on and so forth, until all the elements of the list have been used. As days contains 7 elements, we know beforehand that the loop will be executed seven times.

The while loop

In the second kind of loop, you don’t know how many times you are going to loop, but you know you want to loop as many as a condition is true. Here is an example:

i = 0
while i < 10:
print(str(i))
i = i + 1

Have you tried it on your computer? Do you figure out what this does? If you think it prints out the numbers from 0 to 9, you are right!

How does it work?

In the first line, we just set the value of integer variable i to 0. This is now easy for you! Line 2 is the new sort of loops, the reserved word is ‘while’. It reads “While i is strictly inferior to 10, we execute the indented block just below”.

So when we launch the script, as i is equal to 0, then the program executes the code below. Thus we print the value of the variable i, here 0, and move to the second line of the inner block. This one is weird if you have a mathematical background!

i = i + 1. Really? This is how we increment the value of a variable. The python interpreter first evaluates the right-hand side of the expression and assigns it to the left-hand side. Then now, i is equal to 1.

And the flow goes back to line 2 and re-evaluate the condition. And it is still true, so we get into the inner block again, print the value of the variable and increment it again. It is now equal to 2. We go back to line 2, and so on and so forth! When i is 9 and we get into the block, print “9” and increment i to 10 and go back to line 2 and re-evaluate the condition that is now false. And then, we exit the loop and move to the end of the script.

Infinite loops

With for loops, we know how many times we will loop through. But with the while loop, what happens if the condition never becomes false? We enter an infinite loop and the program will be stuck forever and you will have to kill it! Pressing Ctrl+C is a simple solution most of the time. Imagine you forget the last line in the last script and just type this:

i = 0
while i < 10:
print(str(i))

You will just see thousands of 0 on your screen and you will never exit the loop because the value of i will always be 0. You think it is dummy? I have been coding for more than 35 years and I still do this, sometimes. Most of the time, the infinite loops are easy to debug.

More on logic from the official python documentation.

Before we leave

It’s been a long article, and it contains the absolute fundamentals of coding in python. I hope you respected the instructions and really typed the examples we gave. I hope you made some mistakes, you then had to understand, compare with the examples, saw the missing space, or the forgotten colon or double equal sign. Doing is the only way to learn. You must try new things, type what comes to your mind, change it, and see how your program is impacted! This is how you will make tremendous progress.

--

--

The Python Coder
The Python Coder

Published in The Python Coder

Some valuable content for those of you who want to learn python or already have some years of python under your belt

Christophe Leborgne
Christophe Leborgne

Written by Christophe Leborgne

I am now a devops engineer. I have been coding for decades and recently moved to a more “ops” position. Willing to share a bit of my experience here

Responses (1)