Introduction to programming through Python
This post attempts to teach programming to absolute beginners using the Python programming language which is known for its beginner friendliness.
You can follow along by using one of the following browser code editors which requires no installation on your end.
About Programming
You can imagine programming as writing out a recipe. However, instead of using that recipe to cook food, the computer uses the recipe you’ve created to perform mathematical operations. Another term for this is computing. Each line of code can be viewed as an instruction that must be carefully followed. The computer will go through all the instructions you’ve written and follow them exactly. This is called executing a program.
The thing with computers is that they’re obedient so you can hand out orders and expect them to obey however they’re pretty dumb. You have to spell everything out for them to figure out what to do.
Now let’s learn about how a programming language is structured so you too can hand out orders to your computer to do what you want.
Variables
Variables can be understood as a space in your computer’s memory where you can store data. The reason they’re called variables is because they can vary. This means that after having put data in a variable you can later on tell the computer to remove it or replace it with something else.
Let’s look at the following code in Python. You can write this code out in your code editor and run it (Using most likely, the run button). At the end of this code’s execution you should see 1 appear as the result.
a = 1
print(a)
This program is composed of two instructions.
Your computer first executes “a = 1” which tells the computer to create a variable called “a” and store the integer “1”.
The second instruction “print(a)” tells the computer to display the content of the variable “a”.
There are many things that we can put in a variable, some of which we will discover later. We call these data types.
a = "Hello World!"
print(a)
Here is another program where instead of putting the value “1” in a variable we put in the string of characters (we use string for short) “Hello World!”.
You’re now aware that we can put in variables integers and strings. Yes “Hello World!” is in a fact a string of character containing “H”, “e”, “l”, “l”, “o”, “ “, “W”, “o”, “r”, “l”, “d”, “!”. You can notice that even the space between “Hello” and “World” is considered as a character (“ “).
Earlier on, I told you that you could change the content of variable and that is why they’re called variables. Let’s look at the following code:
a = 1
print(a)
a = 2
print(a)
The computer reads the first instruction “a = 1” which means : ‘Create a variable called “a” and store in it the integer “1”’.
After executing this, the next instruction is “print(a)” which means display the data stored in “a”. This should output “1”.
After executing the previous instruction the computer sees “a = 2”. You might be tempted to think that the computer will create another variable called “a” and store in it the integer “2”. However, that’s not the case. “a” already exists so the computer will replace what is currently in “a” which is “1” and replace it with “2”.
Finally we print the content of “a” again. It should display “2”.
Comments
Comments are pretty useful for explaining non-obvious stuff in your code to other programmers who may have to one day continue working on it. It may also be you but a few weeks later having forgotten why you did things a certain way ;).
Anyway comments are ignored by Python so they don’t affect the execution of your program in any way. Here is an example of a some code with a comment :
# This is a comment!
# Python will just skip it and execute the print statement below
print("hello world")
As you see here to make a comment you simply need to add “#” before it.
Receiving Input
You now know what variables are and how to make one (well… “declaring a variable” if you want to use the proper terminology) and change its content.
We can now make a simple program that asks the user their name and displays a greeting message to them.
To do so we need to use the “input()” statement which is something that comes built in with Python. The input
statement will pause the program, wait for the user to type in something, and will continue once the user hits enter. Look at the following code and try to run it in your editor to see what it does.
print("What is your name?")
input()
We need some kind of way to store the user’s response to our question. You guessed it we’re going to declare a variable.
print("What is your name?")
response = input()
Here we created a variable called “response” which will hold the user’s answer provided by the “input” statement. To check that response indeed contains the user’s response we can use a print statement like so :
print("What is your name?")
response = input()
print(response)
This program should display exactly what you entered after pressing the “Enter” key. We know that “response” will contain their name. We’ll use this information to print out a personalized greeting message. Replace the content of the print statement with the following :
print("What is your name?")
response = input()
# we change the print statement with the following :
print("Greetings" + response)
Ok there is a new concept I must explain here but first let’s change the “response” variable name to something else that is more telling of what we’re doing. We’ll go with “user_name”.
By the way in Python you name your variables following a convention called the snake case instead of camelCase.
So when your variable has more than one word you put an underscore between the two. If we were following the camelCase convention we would instead start the second word with a capital letter.
Carefully choosing variable names is what an experienced programmer does to make their code easy to read for their colleagues.
print("What is your name?")
user_name = input()
print("Greetings" + user_name)
You may have found it weird that we used the “+” sign between “Greetings” and “user_name”. You might have asked yourself why we’re adding text together as if they’re numbers. “+” sign has two meaning in most programming languages including Python.
It’s both used as an operator to add numbers together but also as a concatenator. What is that you ask?
Well… we use the “+” sign to concatenate meaning stitch together two string into one. Imagine that “user_name” contains my name “Nassim”. The following line of code :
print("Greetings" + "Nassim")
Will display “GreetingsNassim” as it combined “Greetings” and “Nassim” into one single string of characters. Having both words combined is a bit jarring. That’s why I suggest that we add a space after “Greetings” to make the final string look more natural.
print("Greetings " + "Nassim")
Will display “Greetings Nassim” which is pretty nice!
The final program should look like this :
print("What is your name?")
user_name = input()
print("Greetings " + user_name)
Strings
We’ve seen what strings are and even used some in previous examples. There still things I need to teach you about strings. Consider the following code :
my_text = "Hello World!"
print(my_text)
and this one :
my_text = 'Hello World!'
print(my_text)
Notice a difference? Maybe not… anyway in the first program we declared a variable which contains the string “Hello World!” in the second program we do the same thing but we use single quotes instead ‘Hello World’. Why is that?
In Python and in many other programming languages you can declare a string using either double quotes and single quotes. The reasoning behind allowing both is for the case in which you need to have double or single quotes within the text of your string. Here is an example :
my_text = "Jonathan's cat was white"
print(my_text)
You can see here that we needed to use double quotes to write this string because if we didn’t, Python wouldn’t be able to know where the string ends as it will be confused by the presence of the single quote of “Jonathan’s”.
my_text = 'Jonathan's cat was white'
The solution to this is to do :
my_text = "Jonathan's cat was white"
The same can be said with the use of double quotes within the string. For example the following string would confuse Python.
my_text = "Jonathan said : "Python is awesome!""
The solution to this problem :
my_text = 'Jonathan said : "Python is awesome!"'
Arithmetic Operations
This section should be rather straight forward for anyone who has done a little math in their life. Look at the following program which shows you how to use addition, multiplication, division and exponents in Python.
first_number = 5
second_number = 3
# displays the result of an addition
print(first_number + second_number)
# displays the result of a multiplication
print(first_number * second_number)
# displays the result of a division
print(first_number / second_number)
# displays the result of an exponent (first_number to the power of second_number)
print(first_number ** second_number)
There is an other operator I’d like to introduce which might be useful. It’s called the modulo operator (%). What it does is to give you the remainder of a division. For example if you divide 10 by 3 the remainder is 1. If you’re rusty with your math here is a detailed step by step procedure for doing 10 divided by 3 by using long division which will give you the remainder. In Python using the modulo operator looks like this :
print(10 % 3) # should print out 1
Now, let’s say we have a variable “a” that contains “10” and we want to add “5” to it. You could do this :
a = 10
a = a + 5
print(a) # should print out 15
However, there are shorthands you can use to make your code more concise. You can do the code below which equivalent to the code above :
a = 10
a += 5
print(a) # should print out 15 also
The cool thing about this shorthand is that it’s available to use for all the previous operators we’ve seen.
a = 10
a += 5 # "a" is now equal to 15
a -= 5 # "a" is back to being 10
a *= 5 # "a" is now 50
a /= 5 # "a" is now back to 10.0
a **= 5 # "a" is now 100000.0
print(a) # should print out 100000.0
You might have noticed something strange! Why do we get a trailling .0 after doing division. Let’s dive deeper.
a = 10
print(a / 2) # should print out 5.0
Earlier on, I introduced 2 data types we could store in variables. The first being the “integer” and the second one being the “string”. However, now is the time to introduce a third one called the “float” which are basically decimal numbers. If you want to learn more about this and why we call this data type “float” instead of simply using the term decimal look at this wikipedia article about floating point arithmetic.
If Statements & Comparison operators
If statements and comparison operators are one of the most important concepts of programming. It allows a program to behave differently depending on various conditions. An if statement can be viewed as setting a condition for which the computer will execute certain parts of your code or skip it if the condition is not met.
Before continuing I need to introduce a new data type called the boolean. A boolean has two possible values either “True” or “False”.
my_boolean = False
Here we create a variable which will store a boolean. In this case the boolean is False. The reason booleans are pretty helpful is that they can be used to define a condition for which certain part of your code will be executed by your computer or not. Let’s look at the following example to make this clearer :
execute = False
if execute:
print("Hello")
print("World") # should skip to this line
In the first line we create a boolean called execute. We could’ve named it anything. It doesn’t matter. However what matters is that we set that variable to be “False”.
In the next line we introduce an if statement. It contains the “if” keyword followed by a condition which here is a variable holding a boolean and finally a “:” before writing the code to be executed beneath.
What this does is that it checks the value of the variable. If it’s true it executes the line ‘print(“Hello”)’ otherwise it skips over to ‘print(“World”)`.
The Python programming language uses indentation to determine what code belongs to an if statement. You need to press the tab key to indent your code. Look at the following code :
say_hello = True
say_hi = True
if say_hello:
print("hello") # we print this because say_hello is True
if say_hi:
print("hi") # we print this also because say_hi is True
Here we have an if statement within an if statement. The code that belongs to the first if statement must be indented with a tab before each line. However, we have another if statement. The code that belongs to this second one should be indented again with another tab. So for the second print statement we had to press the tab key twice. Keep this in mind when indenting your code.
I have to note that usually your code editor will take care of this or tell you when you’re not indenting correctly.
In if statements we can use comparators as conditions. A comparator can be viewed as an operator that returns either True or False. For example what is the answer to is 5 > 3? It could be either True or False.
# We create two variables with arbitrary names.
# You can call them what you want in your code.
my_number = 2
your_number = 3
# here are a bunch of comparators you could use
if my_number < your_number:
print("My number is smaller than yours")
if my_number > your_number:
print("My number is bigger than yours")
if my_number == your_number:
print("My number is equal to yours")
Let’s stop for a second. “==” is a comparator that may confuse beginner programmers. In Python and many other programming languages you use “=” to declare a variable and “==” to check if something is equal to something else. Watch out for this when you’re writing code as you may use “=” instead “==” in an if statement and not immediately realize what you did wrong.
# this code is a continuation of the previous block above.
if my_number >= your_number:
print("My number is superior or equal to your number")
if my_number <= your_number:
print("My number is inferior or equal to your number")
if my_number != your_number:
print("My number does not equal your number")
While “>=”, “<=” are pretty easy to understand you might be confused with “!=”. As a non-programmer this might look very strange but it’s in fact something you probably have already seen in your math classes. In math when you want to say that something is not equal to something else you use this symbol “≠”. “!=” is actually supposed to represent “≠” but because there isn’t a keyboard key for it we use “!” as if it was crossing the “=” sign.
Instead of multiple if statements we can use one branching if statement. You might find this useful in some situations. Here is how it looks like:
a = 5
b = 10
if a == b:
print("both are equal")
elif a < b:
print("a is smaller than b")
else:
print("a is neither smaller or equal to b")
“elif” stands for else if but shortened to make it easy for you to write. Let’s analyze this program step by step.
We created the variables “a” and “b” that hold integers.
We have our if statement which checks if “a” is equal to “b”. It’s not the case.
Because the previous condition wasn’t met we arrive to the elif statement which checks if “a” is inferior to “b”. This is the case therefore “a is smaller than b” is printed.
The program execution is over.
What we can conclude by this is that when we using an if statement with an elif statement and an else statement we stop as soon as one of the condition is met. This is not the case if we use consecutive if statements. Even if the first if statement’s condition is met we go check the second, third, etc…
By the way we can have more than one elif statement. In fact you can have as many as you want sandwiched between the if statement and the else statement. The else statement does not need a condition because it is only executed if none of the previous condition were met.
You can also have more than one condition for an if statement by using the “and” or “or” keywords. Look at the following:
a = 5
b = 10
if a != b and a < b:
print("both conditions were met")
if a > b or a < b:
print("one or both condition were met")
By using the “and” keyword you want to make sure that both conditions are met before executing the code of that if statement.
By using the “or” keyword either one or the other or both conditions can be met. This is somewhat strange for somewhat not accustomed to programming or computer science. Usually “or” in everyday use is either one or the other not both. Keep this in mind when you’re coding so you don’t think you have a bug and spend hours searching for a solution.
The “While loop”
Loops are a pretty powerful construct in programming. They allow you to tell the computer to repeat the same set of instructions multiple times.
Here is a program that uses a while loop :
keep_saying_hello = True
while keep_saying_hello:
print("hello")
This code is going to run infinitely. We created a variable called “keep_saying_hello” which holds a boolean with the value “True”.
What “while keep_saying_hello:” does is to repeat the execution of the indented code below until “keep_saying_hello” is “False”.
The issue is that “keep_saying_hello” will never become “False” because we never change its value within the loop.
Here is another program that uses the while loop but does not run infinitely:
counter = 10 # our counter. we set it to 10 arbitrarly
while counter != 0: # while our counter's value is not equal to 0
print(counter) # we print the current value of the counter
counter -= 1 # we substract 1 to the counter and we repeat the loop
While the “while loop” is pretty useful there is another kind which is even more prevalent called the “for loop” but before teaching it we need to learn about lists.
List
We previously learned about variables and how they could be viewed as a space in the computer’s memory where you could store data. A list is the same thing but you have multiple slots in which you can insert data. It’s one of the most widely used data structures. Let’s look at the following program :
# list are declared like variables however we use [].
my_cool_list = [] # this is an empty list
my_number_list = [1, 2, 3, 4]
my_string_list = ["hello", "greetings", "bonjour", "salut"]
# you can also put any type of data you want in list
my_general_list = [1, 2.0, True, "hello"]
# the list above contains an item of each of the previous data type we learned about.
# we print out our lists
print(my_cool_list) # should display []
print(my_number_list) # should display [1, 2, 3, 4]
print(my_general_list) # should display [1, 2.0, True, "hello"]
So a list is created by enclosing in [] a series of comma separated items that can be of any data type.
Interesting fact : In other more stricter programming languages you might not be able to put items of of different data types in the same list. They will require that you use the same data type for all items. Therefore, you could not have a list containing strings to also contain integers. You would have to create two lists. One for integers and the other for strings.
All list have what we call indexes. It’s a way for you to retrieve specific items from your list.
# a list's index always start with 0 and continues on until the last item
# of the list.
# the item "banana" is at index 0, item "orange" is at index 1,
# item "apple" is at index 2.
# In most programming languages we always start counting indexes from 0
# and not 1
fruits = ["banana", "orange", "apple"]
# if we want to store one item from the list into a variable we can do...
my_banana = fruits[0] # this will retrieve the item at index 0 and copy
# it over to your "my_banana" variable
Click here if you’re interested in learning why we use zero based numbering for indexes.
List operations
The cool thing with lists is that we can modify them after having created them much like normal variables. You can add an item by using the “append()” method and to remove an item you can use the “pop()” method. There are many more that you can learn about here. Look at this example for how to use the two methods I mentioned :
my_list = []
my_list.append(1)
my_list.append(2)
print(my_list) # will print out [1,2]
my_list.pop(1)
# will remove item at index 1 which is 2 because remember we start
# counting from 0. So item 1 was at index 0 and item 2 was at index 1
print(my_list) # will print [1]
Before moving on I just want to mention that in other programming languages you might see the term “array” being used instead of “list” however it’s basically the same thing.
The “For loop”
Now that we learned about lists, it’s time to introduce the “for loop”.
my_list = [1,2,3,4,5]
for item in my_list:
print(item)
The above code will print every single element of this list one by one. Using a “for loop” with a list like we’re doing is called “iterating through a list”
Dictionaries
Another data structure that is pretty important is the dictionary and no we’re not talking about a language dictionary. In Python, a dictionary is like a list but each index is a key that points towards a value. Here’s an example:
my_dict = { "name": "John", "age": 22, "height": 182}
print(my_dict["name"]) # will print "John"
print(my_dict["age"]) # will print "22"
print(my_dict["height"]) # will print "182"
This makes it easy to get specific data you want as long as you know what the key is.
Functions
We arrived at the last concept I’ll be teaching in this tutorial. Functions! What are they? You can view them as a way for you to reuse your code without having to copy-paste all over the place. They can also be viewed as a container containing some code that is isolated from the rest.
Let’s look at some examples to make things clearer.
# we define a function
def add_two_numbers(a,b):
return a + b
# we call the function and put the result in a variable
# note that to call a function we just write its name without "def"
# before it.
result = add_two_numbers(5,10)
# we print out the result
print(result)
result2 = add_two_numbers(9,5)
print(result2)
We first have to define a function before using it. To do so we used the “def” keyword followed by the name we want our function to have. Then we add “()” with the parameters we want to supply to our function. You can think of parameters as a way to pass data into our function.
You can see that we created the parameters called “a” and “b” and then when we called the function we put “5” and “10”. This means that the computer is going to execute the code within the function by using “a = 5” and “b = 10”.
This is what makes function really handy is that you can execute the same snippet of code with different parameters. For example I can execute the code within the function “add_two_numbers” with “5” and “10” but also with whatever other numbers I want.
Finally we use the “return” statement to return a value back to the outside world. This is important to understand. When you declare variables within a function body it is only accessible to it. Look at this code :
def my_cool_func():
a = 10
print(a)
print(a) # this won't work because the outside of the function
# does not know that "a" exist.
Here the variable “a” is local to our function “my_cool_func”. We call this a local variable. However, a function can access outside variables without needing it to be passed as parameters. It’s best practice to pass the variables you want to use as parameters if possible instead of calling them directly.
a = 10
def my_cool_func():
print(a) # will print a = 10
# remember we need to call our function for it's body to execute
my_cool_func()
While there are many more Python and programming features we haven’t seen you’re now equipped to start writing your own programs and use the internet to discover the rest of what the programming field has to offer.