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:
- Easy Installation of Python on Your Computer with Anaconda
- Creation of Variables and Functions
- if/else, for, while Algorithms
- Data Structures:
- Sequences: Lists and Tuples
- Dictionaries
- List Comprehension
- Python's Built-in Functions
- Useful Python modules
1. Install Python on Your Computer
- Jupyter Notebook: Ideal for analyzing data and quickly visualizing the results of machine learning models
- Spyder: Preferable for developing longer and more complex programs.
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 typey = 3.14 # float typename = 'Zakaria' # string type variableprint(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 | # Arithmeticprint(x + y)print(x - y)print(x * y)print(x / y)print(x // y) # whole divisionprint(x ** y) # x power y# Comparison -> True / Falseprint(x == y) # x is equal to yprint(x != y) # x is not equal to yprint(x <= y) # x is less than or equal to yprint(x > y) # x is strictly greater than y# Logical (less important to know)print(x & y) # AND functionprint(x | y) # OR functionprint(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 functionprint(f(4)) # result = 16 |
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 functionresultat = 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 = -2if 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 = 0while 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
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
1 2 3 4 5 6 7 8 9 10 11 | # Creating a list of citiescities = ['New York', 'London', 'Moscow', 'Tokyo']print(cities[0]) # prints New Yorkprint(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 3print(cities[1:3]) |
- 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 citiescities = ['New York', 'London', 'Moscow', 'Tokyo']cities.append('Berlin') # adds 'Berlin' to the end of the listprint(cities)cities.extend(['Algiers', 'Rome']) # adds a list at the end of the cities listprint(cities)cities.insert(3, 'Paris') # inserts 'Paris' at the third index of the listprint(cities)print(cities.count('Paris')) # prints the number of times 'Paris' appears in the listprint(len(cities)) # prints the length of the listcities.sort(reverse=False) # sorts the cities listprint(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 citiescities = ['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 citiescity_test = 'Dublin'if city_test in cities: print(city_test, ' is present in cities')else: print(ville_test, ' is absent from cities') |
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" dictionarythe keys are the fruitsthe values are the quantities '''inventory = { "bananas": 100, "apples": 250, "pears": 175, "cherries": 300 }print(inventory) # prints the dictionaryprint(inventory.keys()) # prints the dictionary keysprint(inventory.values()) # prints the values of the dictionaryprint(inventory.items()) # prints the associations key: value |
1 2 3 4 5 | print(inventory['bananas']) #prints the value associated with 'bananasinventory['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 keyprint(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 dictionaryprint(value) # the value of the associationprint(inventory) # the dictionary no longer contains this association# ===============================================================# fromkeys methode# ===============================================================fruits = ['peaches', 'oranges', 'kiwi'] # a fruit listinventory = dict.fromkeys(fruits, 100) #create a dictionary from the fruit list, assigning a default valueprint(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!
- 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 listfor 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 listprint(list_1) # ===============================================# LIST COMPREHENSION# ===============================================list_2 = [i**2 for i in range(10) if i%3==0]print(list_2) |
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?
- 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 = -2print('absolute value', abs(x))x = 3.14print('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 typeprint(type(x)) # prints the type. this function is very useful!x = str(x) # converts x to stringprint(type(x)) # re-prints the typey = '20' # string typey = int(y) # converts y to intprint(type(x)) # prints the type of ylist_1 = [0, 61, 63, 243]tuple_1 = tuple(list_1) #converts the list into a tupleprint(type(tuple_1))print(type(list(tuple_1))) # converts a tuple into a list. |
Format(): integrates values in your strings
1 2 3 4 | x = 28y = 21print('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)
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 filef.close() # closes the file# using the with command + a little fun with the format() functionwith open('file.txt', 'w') as f: for i in range(10): f.write("{}^2 = {} \n".format(i, i**2)) |
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 mathimport statisticsprint(math.pi) # pi numberprint(math.cos(2*math.pi)) #cos(2*pi)# Creating a listnombres = [3, 5, 1, 0, 2]print(statistics.mean(nombres)) # mean "average"print(statistics.variance(nombres)) # varianceprint(statistics.stdev(nombres)) # standard deviation |
Random: the random number 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 randomrandom.seed(0) # sets the RNG to 0print(random.random()) # Creates a float numberprint(random.randint(0, 10)) # Creates an integer (from 0 to 10)# Generates a random list of length 5random_list = random.sample(range(100), 5)print(random_list) #prints the list# Selects a random item from the listprint(random.choice(random_list)) # Shuffles the list randomly random.shuffle(random_list)print(random_list) |
Glob: Access the files on your computer
1 2 3 4 5 6 7 | import globfilenames = glob.glob("*.txt") #lists all files with the .txt extensionfor 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 |

Post a Comment