Logo

Getting started with Python the right way

Audience

The target audience for this article are programmers that started with a different language and they now want to give Python a shot.
If you never programmed before, you will probably have a bit of a challenge following through as we do not explain things like data types, variables, control structures or other basic programming concepts.
In this case, we recommend Code Academy's Code Foundations introduction course to learn how to code

Even without programming experience, you are very welcome to give it a try!

Things to know from the start

You should know from the start the following, in case any of these is a deal breaker:
  • Python 2 has been retired and it is not maintained anymore. But do not be fooled, Python 2 has been awesome and prepared the world for Python 3. We are working with Python 3 here, like most of the Python developers in the present times
  • the tutorial does not show how to install Python, you will need to do that on your own
  • the tutorial has been tested on Linux only. So the commands in the terminal should work on Linux, and they should be easy enough to adapt on MacOS. On Windows you probably need to use GitBash to get closer to a Unix-like experience
  • it assummes no knowledge of Python, it starts from scratch
  • we will not rely on a specific IDE to do Python execution on debugging, but rather we will use the terminal

Why Python?

Skip this section if you're already a believer. If you're still in doubt, read on.

According to the 2019 Stack Overflow survey Python is the second most loved programming language for that year, and the most wanted.

So needless to say, it is pretty popular. This is important for two reasons... first, it must be something to it that made itclimb to the top. Second, developers will choose Python for new products to build and influence managers to choose Python.

From my experience with Python, it is just a bliss to work with. It does so much with so little effort, yet it is pleasant to read. If you haven't noticed yet, I'm a big fan of Python :) His inventor, Guido van Rossum, a Dutch mathematician and computer scientist, invested a lot of care and effort in choosing a syntax that is intuitive, concise, easy to read and powerful.

Still not convinced?

Because of versatility, Python is used in various domains:
  • Web development
  • Cloud automation
  • Linux system
  • Data science
  • Network engineering
  • Finance
I am confident I sold Python to you by now :)

Python editors or IDEs to use

By now, everyone probably uses Visual Studio Code. Right?

First, for those who do not know, an IDE (Integrated Development Environment) is a feature-rich editor that has all the tools needed (syntax coloring and completion, refactoring tools, debugger, etc) to make it easier to program in a certain language. One Python dedicated IDE that I also recommend to try is PyCharm. But you have other options as well: Sublime Text, NotePad++, etc.

For the Linux hardcore folks you must know that Emacs (see Doom Emacs, Spacemacs) and vim have very good Python support.

Let's get it on

First, let's confirm the Python version. In your terminal write
python --version

I get at this time Python 3.8.5. Any version above Python 3 will do the trick.

First thing you could do is enter the Python interactive interpreter. By just typing Python in the terminal, you will enter a Python interactive session that can interpret the code you write. In simpler words, if you want to test a few lines of Python, you can enter the Python code in the interpetor, and the interpretor will execute code either on pressing Enter or when a code block ends.

Let's see an example. Enter your python interpretor by typing python in the terminal and hit Enter.

Then write the following (please note that the signs ">>>" and "..." are displayed by the interpretor, you do not have to type them):


❯ python
Python 3.8.5 (default, Sep  5 2020, 10:50:12)
[GCC 10.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> i_learn_python = True
>>> if (i_learn_python):
...     print('Hellooo Python!')
...
I am excited
>>>

What we did above is defined a variable called "i_learn_python". And we assigned a boolean value of True.

Now what follows is the if statement, which will execute the code below only if the expression in the paranthesis is True. More technically speaking, Python will evaluate the expression in paranthesis from a boolean perspective and if it is True it executes the first code block inside the if.

Python code blocks

One of the innovations that Python came up with, that created a lot of controversy at first, is that for delimiting code blocks we use the indentation (spaces or tabs). In other words, the code block after the if (condition): needs to be indented a few spaces to the right, to be the first if code block. That code will e executed only the condition of the if is true.

The standard is to use 4 spaces for an indentation level. See the official recommendation: PEP 8 indentation

In other words, to begin a new block of code you indent 4 spaces to the right. After you finnish that block of code, you then go back left 4 spaces.

All modern Python IDEs will help you do that. For this reason I would not recommend writing Python in something as simple as Notepad.

I recommend using the Python interpreter (later in the article we will take about an alternative interpeter called IPython) for learning, quick testing and experimentation of Python code.

But in the same time, while building your program, or if you have larger chunks of code to test, I recommend writing it to a file with the extension py.

So let's write the code below in a file called hello_python.py

Then execute the code with
python hello_python.py

Python data typing

Python is a dynamically typed language and what that means is the type of a variable is given by the value you give to that variable. So you do not have to specify the type of a variable. For example name = 'Hocli' declares a variable name of type String because the value assigned is a string: Hocli

That saves some time when writing your program (as opposed to a static typing language), so you get things done quicker.
On the downside, type errors are not caught at compile time, as there is no compiler to check the type correctness of your variables. Any type issues will be seen directly at run-time.

A good programmer always writes tests for programs that matter, so that those bugs and other logical errors have less chance to happen. Right, guys?

Python is also a duck typing language. The relaxed way to describe this is: "If it walks like a duck and it quacks like a duck, then it must be a duck".

What that really means is that an object that implements the methods of a particular class/type, can be used as if it belonged to that class and type. It doesn't have to necessarily be of a specific type, needs only to act like one.

Data types

Let's see the most used data types present in Python:

  • bool - that is short for boolean and is a datatype with only two possible values: True or False
  • int - this is a numeric datatype given to integers, for example: 3
  • float - this is a numeric datatype given to floating point numbers, for example: 2.5
  • str - also called a string, is informally speaking any piece of text, or more formally a string of characters
  • list - also called an array or collection in other languages is an ordered list of elements, that you can change
  • tuple - is also an ordered list of elements but one that you cannot change
  • dict - or dictionary is a list of key-pair values
When learning, but also in your program, sometimes you want to know the type of a value of an expression, easy to do using the function type() like this:
>>> type(3)
<class int>

In Python 3, the concept of type and class is interchangeable, so for most of the purposes you can say they are the same. So you can say the value 3 is of type int or of class int.

Tehnically speaking, there are other data types as well, but these are the most common. Let's see some examples of working with different data types in Python and the operations between them:

first_name = 'John' # data type
last_name = 'Doe' # data type string
age = 39 # data type int
is_programmer = True # Boolean
salary = 70000


# + for string is called concatenation

name = first_name + ' ' + last_name  # name is 'John Doe'.

 # a simple debug technique is to print variables and expressions in your program to see their values while executing

print(name) # John Doe


# Arithmetic operators

age = age + 1 # adds 1 -> age is 40
age += 1 # adds 1 -> age is 41
age -= 3 # substracts 3 -> age is 38

salary += salary * 0.1 # adds 10% to salary -> salary is 77000
taxes = salary / 10 # 10% taxes. you wish ;)


# this here is a boolean operator
# modifies True to False and False to True

not is_programmer # False


# Most common Boolean operators
#

# or result is True if at least one operands is True

True or True # True
True or False # True
False or True # True
False or False # False

# and result is False if at least one is false

True and True # True
True and False # False
False and True # False
False and False # False

Working with strings

Strings in Python can be enclosed in single quotes eg: 'my string', double quotes eg: "my string" and the two forms are equivalent.

You can escape strings within strings with backslash \.

    
# Comments begin with a hash
# Convention is that variables, function names, and other identifier names 
# that are made from multiple words are sepparated by underscore and lower-case

learning_website = 'Hocli'
relaxing_website = "Hocli"

print(learning_website == relaxing_website) # True


name = 'O\'Connor'
print(name) # O'Connor

name = "O'Reilly" # no need to escape single quotes inside double quotes
print(name) # O'Reilly
    

Another form of writing srings in Python is using multiline strings or string literals. They are enclosed inside three single quotes or double quotes. The multiline strings allow you to write longer strings (think paragraphs) that can span multiple lines, without the need to close the string and re-open the string again or worry about concatenation.

Example:
    
s = '''
First line
second line
third line
'''

    

Working with lists

We're going to explore what lists are and the most common operations with lists A list in python is an ordered collection of elements and those elements can be objects or any type of values. Definining a list of numbers looks like this: mylist = [1,2,3] Now since lists are objects (for programmers novices there an object is a more fancy data type), then they have methods, meaning functions attached to them. No need to know the object-oriented theory behind to play with lists methods

lists are iterable

Let's start here, what means iterable? The way I understand it, iterable is something you can iterate on, that means take one element at a time from a collection of elements, save that element into a variable, and execute a block of code. In Python you iterate using a for..in loop. Let's see an example:
    
for item in [1,2,3]:
    print(item)
    
As usual, the block of code that belongs to the for loop is the indended one, and item will become one by one each element from the list. Remember this form of for, as you'll be using it a lot in Python.

Getting elements by index and the slicing syntax

If you've programmed before you know that basically an index is the order count of an element in a list, starting from zero.

In other words:

  • index 0 corresponds to the 1st element in our array
  • index 1 corresponds to the 2nd element in our array
  • index n corresponds to the n+1th element in our array

The last element in the list has the index being equal with the (length of the array) - 1 In Pyton, you can use negative index and that means you count from the end of the list. Let's see an example:
    
mylist = [1,2,3,4,5,6,7,8,9,10]

print('getting elements by positive index')
print(mylist[0]) # prints 1
print(mylist[1]) # prints 2

print('getting elements by negative index')
print(mylist[-1]) # prints 10
print(mylist[-2]) # prints 9
    
Python has an interesting way of extracting parts (slices) of a list, and save them to new lists, called the slicing syntax. The general form of slicing syntax is: mylist[start:stop:step]
  • start is the index of the first element that WILL be included in the list
  • stop is the index of the element after the last element included. So is stop is 3, then element with index 2 is included but element with index 3 is not
  • step means the distance between the indexes of the slice. it defaults to 1.
Now, there are different ways to think about it to make it easier when you work with slices, and I'll describe below what works for me, and combine that with missing start and stop cases:
  • You can think of the start parameter as the number of the elements left out of the slice from the beginning of the list So for example [3:10] if we just focus on 3, the start, means the slice begins after it leaves out the first 3 elements of the list
  • You can think quickly subtract stop-start and find out how many elements your slice has. For example [3:10] means you leave 3 elements out of the list and then you include 7 elements
  • A missing stop means select list elements until the end . For example you can think of [3:] as leave out the first 3 elements of the list, and then go all the way to the end
  • A missing start means select the first stop elements
Let's see some examples:
    
mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

mylist[2:10] # [3,3,4,5,6,7,8,9,10]
mylist[2:] # same [3,4,5,6,7,8,9,10] -> selects all the elements except the first
mylist[2:5] # [3,4,5] -> leave first 2 elements out and then select 3 elements
mylist[:4] # [1,2,3,4] -> select first 4 elements
mylist[:-2] # [1, 2, 3, 4, 5, 6, 7, 8] -> select all elements but the last two
mylist[2:-3] # select without the first 2 elements and the last 3
    

lists are mutable

What does that mean? That means that you can change the respective value (object) once it has been created. Let's see some examples in which we modify an existing list by using list methods or slicing and concatenation:
    
mylist = [1, 2, 3]
mylist.append(4) # [1, 2, 3, 4]
mylist.append([5, 6]) # [1, 2, 3, 4, [5, 6]] -> appends a new element which itself is the list [5,6]
mylist.extend([7, 8]) # [1, 2, 3, 4, [5, 6], 7, 8] -> extends the list with more elements
mylist.remove(8) # [1, 2, 3, 4, [5, 6], 7] -> removes all elements with value 8. in our case one element
    

More on iteration

When you iterate over a list, the variable that you use in iteration will become each element of the list, one by one, in our case the variable item:
    
for item in mylist:
    print(item)
    
Although less often, there are cases when we want to take both the index and the element each in its own variable. Then we use the function enumerate on our list variable.
    
for index, item in enumerate(mylist):
    print(index, item)
    

Working with dictionaries

The name of the type dict and comes from dictionary, which is basically a list of key-value pairs. We would use that when we want to describe a more complex data type that has some kind of attributes.

For example:

    
person = {
    'first_name': 'John',
    'last_name': 'Doe',
    'age': 25
}

for key in person:
    print(key)

for key, value in person.items():
    print(key, value)

print(person['first_name']) # 'John'

    
As you can see, when you directly iterate (use the for loop) over a dictionary what you are actually iterating over are the keys of the dictionary. If you need both the key and value for each iteration, you need to call the method .items() on that dictionary.

More on dictionaries

Assuming you have a variable called mydict, you can delete an element from a dictionary using del mydict[key].

You can update a dictionary by using the update() method on the current dictionary The method is receiving another dictionary as argument, that will add keys and values over the existing dictionaries. Let's see some examples:
    
person = {
    'first_name': 'Maria',
    'last_name': 'Doe',
    'age': 27
}


# this will add a new key salary, and will overwrite age
person.update({
    'salary': 80000,
    'age': 28
})


# deletes the key last_name
del(person['last_name'])


assert person == {
    'first_name': 'Maria',
    'age': 28,
    'salary': 80000
}

    

Control structures: if, while, for

Perhaps the most common control structures in Python are if, for and while

The if construction has the if...else and if...elif alternatives when more conditional branches are used.

The simplest form of if construction is:
    
if condition:
    print('do something')
    print('do something else')
    

In the example above, if the expression represented by condition evaluates to true, then the block of code under the if line, indented, is executed. Otherwise, nothing happens in this case since this is a simple if.

We have the if...else form that looks like this:


    
i_learn = True # change this to False to test

if i_learn:
  print('I have a job') # prints this
else:
  print('I have to learn')

    

We sometimes have the case where our program needs to do block1 of code if condition1 is true.

But if condition1 is not true, and then condition2 is true, it needs to do block2 of code. If none of the conditions above are true, it will do condition3.

And this can go on with multiple conditions. The execution will check each condition, one by one


    
number = 1

if number == 1:
    print('number is 1')
elif number == 2:
    print('number is 2')
elif number == 3:
    print('number is 3')
else:
    print('number is other number')

    
The for construct is used to take one element at a time from a collection of elements, or more technical from an iterable. An iterable is any data type that you can iterate over, or apply a for loop over. Let us see the example:
    
lang_friends = {
    'python': 'Guido',
    'javascript': 'Brendan',
    'c': 'Dennis',
    'rust': 'Graydon',
    'lisp': 'John'
}


phrases = []

# in this example, each iteration over lang_friends gives us a tuple of
# 2-values that we can assign directly to two variables (lang and friend)
for lang, friend in lang_friends.items():
    phrases.append(f'I learn {lang} and my friend is {friend}')


# this is a normal iteration over the elements in a list
for phrase in phrases:
    print(phrase)

    

The while construct will execute the block of code indented under it as long as the while condition is true. Obviously, the corresponding block of code needs to change the condition to false at some point, otherwise the program will keep looping without a break.

    

x = 0

# this program will print 0, 3, 6, 9

while x < 10:
    print(x)
    x = x + 3