Learn Python in One Article


Want to do Machine Learning or Deep Learning but don't have any programming skills yet? Then you NEED to follow this article, because it will allow you to acquire a new skill that is highly in demand on the job market: Python 

I give you here all the basics of Python, the ones that are really useful to do Machine Learning or Deep Learning.

This tutorial will cover the following:

  1. Easy Installation of Python on Your Computer with Anaconda
  2. Creation of Variables and Functions
  3. if/else, for, while Algorithms
  4. Data Structures:
    • Sequences: Lists and Tuples
    • Dictionaries
    • List Comprehension
  5. Python's Built-in Functions
  6. Useful Python modules
Python is a very simple language, and you don't need any specific knowledge to be able to follow and understand this article. So let's get started!

1. Install Python on Your Computer

To download Anaconda from the official website, click here. Remember to select the version that works with your operating system (Windows, Mac, Linux) and the most recent version of Python (Python 3).

The Anaconda browser has only one important tab, it is the Environment tab which allows you to easily add or remove packages (i.e. features)

To write a program with Python, there are 2 different text editors:
  • Jupyter Notebook: Ideal for analyzing data and quickly visualizing the results of machine learning models
  • Spyder: Preferable for developing longer and more complex programs.
Once you have completed this tutorial, you are ready to write your first code. Congratulations!

2. Variables and Functions

At the heart of any scientific program there are variables and functions.

For example, we can define a variable s and d which respectively represent the speed of a car and the distance of the trip in order to calculate the travel time t. For that, we define a function Time(s, d) = d/s

Variables

You can create variables of several different types.

  • Integers: int
  • Decimals: float
  • Character string: string
  • Boolean: bool
  • and many other types that we will see later in this article: Lists, dictionaries, etc.

To display variables, or any other information, we use the print() function

1
2
3
4
5
6
7
8
9
10
11
# this is a comment
'''
this is a comment on several lines
'''
 
x = 1 # int type
y = 3.14 # float type
name = 'Zakaria' # string type variable
 
print(name)

Of course, it is possible to do arithmetic operations on numerical variables, as well as comparisons. The result of the comparisons is a boolean. Finally, you can do logical operations between several booleans.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Arithmetic
print(x + y)
print(x - y)
print(x * y)
print(x / y)
print(x // y) # whole division
print(x ** y) # x power y
 
# Comparison -> True / False
print(x == y) # x is equal to y
print(x != y) # x is not equal to y
print(x <= y) # x is less than or equal to y
print(x > y) # x is strictly greater than y
 
# Logical (less important to know)
print(x & y) # AND function
print(x | y) # OR function
print(x ^ y) # XOR function

Functions

To do simple mathematics, you can create anonymous mathematical functions using the lambda command. Usually you don't give these functions a name (but here I named it f).

1
2
3
4
f = lambda x: x**2 #is equivalent to create a function f(x) = x^2
 
# using the f function
print(f(4)) # result = 16


But most of the time we define more complex functions using the def method. When creating a function, it is important to document the code well (by adding comments) to explain the purpose and the way the function works.

1
2
3
4
5
6
7
8
9
10
11
12
def potential_energy(m, h, g=9.81):
    ''' potential_energy(m, h, g) function that computes and displays the Potential Energy of a body of
    mass m (in kg) located at a height h (in m).
   the gravity constant g=9.81 for the Earth '''
 
    E = m*g*h
    print(E, 'Joules') # prints E, in Joules
    return E
 
# using the function
resultat = potential_energy(m=5, h=10)

Congratulations! You have now mastered the basics of scientific programming

It's time to learn how to develop your first algorithms 

3. Writing Algorithms with Python

In order to create algorithms, 3 control structures are used in the programming world:

  • if/else statements
  • for loop
  • while loop

if/else statements

This is the basis of most algorithms. if/else allows to execute actions only if a condition is verified. To be more specific, the action is executed only if the result of the condition is True. We can thus mix booleans and logical operations. If the result is not True, then the next condition is tested (elif) and so on until the else is reached.

1
2
3
4
5
6
7
x = -2
if x > 0 :
    print(x, 'is positive')
elif x < 0:
    print(x, 'is negative')
else:
    print(x, 'is null')

for loop

The for loop allows you to perform actions on all elements of a sequence. The simplest sequence that exists is the range() sequence. For example range(10) produces the sequence 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.

1
2
for i in range(10):
    print(i, i**2) # prints the value of i, then i**2

while loop

The while loop allows to execute actions as long as a certain condition is satisfied (True). It's a bit like the if statement repeating itself as long as it gives True.

1
2
3
4
i = 0
while i < 10:
    print(i**2)
    i += 1 # Without this line, the algorithm would execute endlessly!

Congratulations! You now know how to write your first algorithms! There is no artificial intelligence in these algorithms yet, but by writing them, you have introduced a form of intelligence that reflects your thinking

4. Manipulating Data with Data Structures

Unlike a variable x=1 which stores only one value (here 1), Data Structures allow to store many values under the same name. In Python, Lists, Tuples and Dictionaries are the basic structures that are important to know. (There are also Sets, but they are less used)

4.1. Sequences: Lists and Tuples

Lists and Tuples are heterogeneous data structures (several types of values can be placed in them: int, string, etc.) and form what we call Sequences

Difference between List and Tuple ?

A list can be mutated (values can be added/removed) whereas a Tuple cannot. Lists are more often used than Tuples, but Tuples still have the advantage of being faster than a List.

What is a Sequence? Indexing and Slicing

In a sequence, the elements are arranged in a specific order. We can call them indexed elements. We can thus access each element by indicating its index. This technique is called indexing, and allows to display elements, or to modify them.

1
2
3
4
5
6
7
8
9
10
11
# Creating a list of cities
cities = ['New York', 'London', 'Moscow', 'Tokyo']
 
print(cities[0]) # prints New York
print(cities[-1]) # prints the last element of the list
 
 
# Replaces London by Dubai!
cities[1] = 'Dubai'
 
print(cities) # prints the whole list.

Slicing is another important technique to know: it allows to access a "range" of values in our list, creating a mini-sequence. For this, we indicate a start and an end index.

1
2
# prints values from index 1 to index 3
print(cities[1:3])

Actions on a List

You can perform many actions on a List, for example:
  • Sorting it (alphabetically or numerically)
  • Measuring the length
  • Counting how many times the same element appears
  • inserting one or more elements,
  • etc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Creating a list of cities
cities = ['New York', 'London', 'Moscow', 'Tokyo']
 
cities.append('Berlin') # adds 'Berlin' to the end of the list
print(cities)
 
cities.extend(['Algiers', 'Rome']) # adds a list at the end of the cities list
print(cities)
 
cities.insert(3, 'Paris') # inserts 'Paris' at the third index of the list
print(cities)
 
print(cities.count('Paris')) # prints the number of times 'Paris' appears in the list
 
print(len(cities)) # prints the length of the list
 
cities.sort(reverse=False) # sorts the cities list
print(cities)

Sequences in for loops and if/else statements

Sequences such as Lists and Tuples work in exact combination with for loops and if/else statements. The following code explains it all

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Creating a list of cities
cities = ['New York', 'London', 'Moscow', 'Tokyo']
 
# ==================================================================
# for loop
# ==================================================================
for i in cities:
    print(i)
 
 
# ==================================================================
# if/else
# ==================================================================
# let's test if the following city is in the list of cities
city_test = 'Dublin'
 
if city_test in cities:
    print(city_test, ' is present in cities')
else:
    print(ville_test, ' is absent from cities')


Congratulations! You have now mastered the basics of what you need to know about lists and sequences in Python.

4.2. Dictionaries

The Dictionary is another important data structure to know. It is the basis for Pandas, the most important package for data scientists.

What is a Dictionary?

A Dictionary is not a sequence: there is no order in its elements. Instead, a Dictionary is a grouping of associations between keys and values. It's a bit like having several variables and wanting to put them all in one box (the dictionary), but instead of calling them variables, we call them keys.

A key is unique, it cannot exist in two copies.

Here is how to create a dictionary:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
'''Creation of an "inventory" dictionary
the keys are the fruits
the values are the quantities '''
 
inventory = {
        "bananas": 100,
        "apples": 250,
        "pears": 175,
        "cherries": 300
        }
 
print(inventory) # prints the dictionary
 
print(inventory.keys()) # prints the dictionary keys
 
print(inventory.values()) # prints the values of the dictionary
 
print(inventory.items()) # prints the associations key: value


1
2
3
4
5
print(inventory['bananas']) #prints the value associated with 'bananas
 
inventory['bananas'] = 350 #changes the value associated with 'bananas'.
 
inventory['apricots'] = 225 #Here is how to create a new association

Some methods for Dictionaries

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
inventory = {
        "bananas": 100,
        "apples": 250,
        "pears": 175,
        "cherries": 300
        }
 
# ===============================================================
# get methode
# ===============================================================
print(inventory.get('pears')) # returns the value associated with the key
print(inventory.get('peaches', 0)) # if the key does not exist, returns a default value
 
# ===============================================================
# pop methode
# ===============================================================
value = inventory.pop('cherries') # extracts an association from the dictionary
print(value) # the value of the association
print(inventory) # the dictionary no longer contains this association
 
# ===============================================================
# fromkeys methode
# ===============================================================
fruits = ['peaches', 'oranges', 'kiwi'] # a fruit list
inventory = dict.fromkeys(fruits, 100) #create a dictionary from the fruit list, assigning a default value
print(inventory)

4.3. List Comprehension: a more advanced but very useful technique

List comprehension is nothing more than a technique to create a list in a simpler, more professional, and more efficient way. These 3 points are enough to say that this technique is important, and it is sometimes the subject of questions in job interviews!

This consists in creating a list by writing on the same line:
  • The list
  • a for loop
  • with an optional condition statement


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# ===============================================
# TRADITIONAL METHOD
# ===============================================
 
list_1 = [] # creating empty list
for i in range(10):
    if i%3 == 0: # if i is a multiple of 3
        list_1.append(i**2) # adds i**2 to the list
 
print(list_1)
         
# ===============================================
# LIST COMPREHENSION
# ===============================================
 
list_2 = [i**2 for i in range(10) if i%3==0]
 
print(list_2)


Congratulations! You have now mastered the essentials of data structure techniques (including more advanced techniques). Now we'll talk about the basic functions of python.

5. Python's Built-in Functions

Python includes many functions already implemented to help you in your work. These functions are VERY USEFUL! As a proof, among them, we find the print(), len(), zip() and enumerate() functions. Well, if I told you that there are a lot more of these functions, would you believe me?

These functions are all documented here, on the official python website.
  • Basic: abs(), sum(), max(), min(), len(), all(), any()
  • Conversions: int(), float(), str(), list(), tuple(), dict()
  • input()
  • format()
  • open()

Basic functions

1
2
3
4
5
6
7
8
9
10
11
12
x = -2
print('absolute value', abs(x))
 
x = 3.14
print('rounded', round(x))
 
 
list_1 = [0, 23, 14, -19]
print('max', max(list_1))
print('min', min(list_1))
print('length', len(list_1))
print('sum', sum(list_1))

Conversion functions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
x = 10 # int type
print(type(x)) # prints the type. this function is very useful!
 
x = str(x) # converts x to string
print(type(x)) # re-prints the type
 
y = '20' # string type
y = int(y) # converts y to int
print(type(x)) # prints the type of y
 
list_1 = [0, 61, 63, 243]
tuple_1 = tuple(list_1) #converts the list into a tuple
print(type(tuple_1))
 
print(type(list(tuple_1))) # converts a tuple into a list.

Format(): integrates values in your strings

The format() function simply allows you to integrate values in strings. Here is how to do it:

1
2
3
4
x = 28
y = 21
print('I am {} y.o, and you are {}'.format(x, y))
print(f'I am {x} y.o, and you are {y}') # another way, faster.

Open(): Open any file on your computer

The open() function is very important to open and read documents on your computer, or to write a document and save it on your computer.

This function creates a file object f on which we can use methods to perform actions like:

  • f.write() to write to the file (overwriting it content)
  • f.read() to read the file
  • f.learn() to write from the end of the file (does not overwrite the content)
Once the operations are finished, you must remember to close the file with f.close().

For better performance, you can use the with command, which does not create a reference to the file f in the computer's memory. In this case, you do not need to close the file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Create a file to write in (mode 'w')
f = open('file.txt', 'w')
f.write('Hello World!') # writes the message "Hello World!".
f.close() # closes the file.
 
 
# opens the file that has just been created ('r' mode)
 
f = open('file.txt', 'r')
print(f.read()) # prints the content of the file
f.close() # closes the file
 
 
# using the with command + a little fun with the format() function
with open('file.txt', 'w') as f:
    for i in range(10):
        f.write("{}^2 = {} \n".format(i, i**2))

Congratulations! You now know the most important functions of Python. Now we'll start the last step of this training: Python modules 

6. The Most Useful Modules of Python

In python, every program you write is called a module. It is a file that gathers different functions and variables. It is possible to import your modules into other programs you might write, in order to benefit from the functions you have already developed.

But what is even more interesting is to import modules that have already been developed for you. For example modules that allow you to do mathematics or statistics easily! All these modules are documented here, on the official Python website. As you can see, there are a LOT of them, I would even say too many ! That's why I'll guide you through the most important modules:

Basics: math and statistics

1
2
3
4
5
6
7
8
9
10
11
12
import math
import statistics
 
print(math.pi) # pi number
print(math.cos(2*math.pi)) #cos(2*pi)
 
# Creating a list
nombres = [3, 5, 1, 0, 2]
 
print(statistics.mean(nombres)) # mean "average"
print(statistics.variance(nombres)) # variance
print(statistics.stdev(nombres)) # standard deviation

Random: the random number module

The random module is one of the most useful in Python: here is a short list of actions you can do with this module:
  • Generating random numbers
  • Generating lists filled with random numbers
  • Shuffling a list randomly
  • Selecting an item randomly from a list
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import random
 
random.seed(0) # sets the RNG to 0
 
print(random.random()) # Creates a float number
print(random.randint(0, 10)) # Creates an integer (from 0 to 10)
 
 
# Generates a random list of length 5
random_list = random.sample(range(100), 5)
print(random_list) #prints the list
 
 
# Selects a random item from the list
print(random.choice(random_list))
 
# Shuffles the list randomly
random.shuffle(random_list)
print(random_list)

Glob: Access the files on your computer

The glob.glob() function is great! It returns a list of all the files in your working directory (or any other directory on your computer). With this list, you can use the open() function in a for loop, which allows you to open all the files in a directory and perform actions on them.

1
2
3
4
5
6
7
import glob
 
filenames = glob.glob("*.txt") #lists all files with the .txt extension
 
for file in filnames(): #selects one file after the other in filenames
    with open(file, 'r') as f: #opens the file
        print(f.read()) #prints file's content

Congratulations! You have successfully completed the course!