Learn Python: The Beginner Guide

Share this post

This post is part of the complete Guide on Python for SEO

In order to learn Python for SEO, you need to understand why you should learn Python in the first place. Then, you need to cover the basics.

This is a true beginner guide to learn Python.

Here is what you are going to learn.

Subscribe to my Newsletter

Contenus masquer

What is Python?

Python is an open-source interpreted programming language that was created by Guido Van Rossum that can be used as a general-purpose to build almost any piece of software.
Python has built its popularity by being free to use, its easily shareable packages, and its ease of integration with C and C++. 

Python 2.7 or 3.5?

There are two common versions of Python. They are quite similar, but version 2 will not be maintained past 2020.

Why people still use version 2 of Python? 

This is mainly because the Python Software Foundation wanted to start over by creating Version 3 of Python. So, if you are working with V3, you can’t work with files that are using V2. So, a lot of packages can’t be called using Python V3.

I would suggest that you get started using Python 3.

How to Install Python?

Everyone can use Python for a different application. This is why there is no single solution to help you set-up Python and the required packages. In SEO, Python will mostly be used for Data Analysis, Data Extraction, and Automation. I will thus show you what you need to get started with Python for SEO. 

Since Python doesn’t come natively on Windows, you need to install Python 3. To do this, just read the steps to install Python on Windows using Anaconda.

Using Python

Python is a programming language like C or C++. It is not software that you can start using instantly like Microsoft Word or Excel.

You will need tools to start programming in Python.

The simplest way to start using Python instantly is to use Google Colab where Python is already pre-installed.

Understand The Python Tools

In order to run a Python code or Python Script, you will need an interpreter to write, test and debug your Python commands. 

You can either use a simple IPython Shell with a text editor, an Integrated Development Environments (IDEs), or a notebook like Jupyter to do this task. IDEs, like Spyder, are easy to use interface for beginners in Python.

You can use either one of the 4 solutions, but since, I prefer to use VSCode.

Python Tool #1: IPython Shell

The Python Shell, or Python Interactive Shell, is a place where you can type Python code and immediately see the results. IPython is basically a shell, with more features.

The IPython Shell runs line-by-line. So, to run 10 lines, you will need to make 10 commands of a single line.

Combined with a text editor like notepad++, it can be a powerful tool. If you have installed Python using Anaconda, you can open the IPython Shell using Anaconda Prompt, if not using the Command Prompt native to Windows, and typing these commands.

## Install IPython with Pip (only the first time)
pip install ipython

 ## Install IPython with Conda (only the first time)
conda install ipython 

## Start using IPython
Use IPython using Anaconda Prompt

To learn more about using the IPython Shell, just look at this great guide by Codecademy.

Python Tool #2: Integrated Development Environments (IDEs)

You might have heard of applications like Python Tools for Visual Studio Code, PyCharm, Spyder, Komodo IDE. These are Integrated Development Environments or IDEs.

Basically, an IDE is an application, like word, that lets you build, compile and run Python Scripts from a single interface.

My favourite Python tool is VSCode.

Python Tool #3: Notebook

A Python Notebook, like Jupyter Notebook or IPython Notebook, is free and open-source, browser-based environments that let you write, read and share your Python code for data analysis.

If you are interested to learn more about Jupyter Notebook, you can read this complete guide on How to use Jupyter Notebook.

Python Scripts

What Are Python Scripts?

A Python script is a text file, with the extension .py (scripts.py), with a list of Python commands that are executed. You can add multiple code lines in a Python Script and execute them in a single command.

Python Scripts

Let’s say you have a Python code that needs 10 lines to be executed. 

Unlike the Python Shell, a Python Script will run the code in 10 lines and 1 command, and execute it line-by-line.

Why Use Python Scripts?

Python scripts will help you to keep a structure. When you need to make a change to your code, instead of manually retyping every step, as you would do in the shell, you simply make the change in the script and rerun the entire code.

In this guide, I will use Spyder IDE, since it is so convenient to use, and so closely resemble RStudio, that it will be easy if you want to learn R Programming later on.

Note that if you have installed Python using Anaconda as we have seen earlier, Spyder IDE will be installed on your PC.

Don’t worry if you don’t know how to use them, I have made a simple guide on Spyder IDE for Python.

Learn Python

With Python, you can do almost anything: web development, machine learning, jc, automation, web scraping, use apis. To get you started, I will show you some basic concepts like doing arithmetics with Python and understanding variables, types, functions, and methods.

But wait.

Don’t leave before you have seen what you can do with Python packages. I promise you are absolutely going to love this.

First, let’s run over the basic concepts.

Do Arithmetics With Python

Usually, when you enter in your IPython Shell, you’ll have the opportunity to really simple arithmetics like this:

>>> 1+5

Here is a quick guide to help you master Python operators.

Operators Example
Additions (+) >>> 1+5
Multiplications (*)>>> 2*5
Exponentiation (**) : Performs Exponential Calculation >>> 4**2
Modulo (%) : Returns the remainder >>> 18 % 7
== : If x is equal y (x==y), returns true >>> x == 7
!= : If x is not equal to y (x!=y), returns true >>> x != 7
> : Left is greater than right, returns True >>> 8 > 7
< : Left is lower than right, returns True >>> 8 < 7
>= : Left is greater than or equal to right, returns True >>> 8 >= 7
<= : Left is lower than or equal to right, returns True >>> <= 7

But since there is so much more you can do in Python, we should look at basic concepts before we get going.

Make a Comment Using The Hashtag (#)

Comments in Python begin with the hashtag character (#). This way, Python does not execute anything that follows a hashtag on a line. 

This is why hashtags are so important in Python. They let you add annotations to your code that humans can understand, but that your computer will pass over.

For the remainder of this guide, I will use hashtags to display the output of Python code, just like this:

## 6

A single hashtag (#) will be used to add my own comments. 

A double hashtag (##) will be used to display the results of code.

I will avoid using the “>>>” and “In [1]” unless I need it.

Understand and use Variables

What are variables? With Python, you can make simple arithmetics like 3 + 5 = 8, but you can also make more complex calculations. 

As you go along those complex equations, you might want to store some values, along with a specific name, to help you move along your code. To “save” those values in Python, you need to create variables

Declaring a Variable

By declaring a variable, you basically attribute a value to a variable, that you can later call using the variable name. The name is case-sensitive.

If you now type the name of the variable, Python looks for the variable name, retrieves its value, and prints it out.


Let’s say you want to calculate the average score in each of your classes. You might want to create variables for each of your classes.

maths = 89.6
french = 75.9
science = 81.3
## 89.6

To find your average score, you would need to add up your classes’ scores and divide them by the number of classes. You could do this in two ways:

average = (89.6 + 75.9 + 81.3) / 3
## 82.26


average = (maths + french + science) / 3
## 82.26

Modify or Delete a Variable

Anytime that you declare a variable, it stays stored on your computer. If you want to delete a variable, use the del() function.

variable = [1,2,3,4]
##[1, 2, 3, 4]

#Change a variable
variable = [2,5,6,8]

#Delete variable
Traceback (most recent call last):
  File "<ipython-input-245-ad7925581c6b>",line 2, in <module>
NameError: name 'variable' is not defined

Understand and use Python Types

The example above only attribute numerical values to variables. However, there are many types that can be used in Python. To know what type is your value, you just need to write type(value) in your shell.

 If you want to know the type our variable average that we just created, just input type(average)

## float

What Are The Python Types?

There are many types in Python. The most commonly used are:

Float: Real number that includes all decimal points. Example: 26.26666667

Int: Integer. Example: 26

Str: Strings. Example: “Hello World”

Bool: Booleans that can only be answered by True or False Example: y = True

Note: Python Data Types Can Behave Differently

Python data types will react differently to different operators. For example, if you sum integers, the result you will get is the sum of your integers. However, if you sum strings, the result you will get is the strings pasted together.


## 2


“I am” + “ a child”
## “I am a child”

This is really important.

How the code behaves depends on the type that you are working with.

Different type = different behavior

Convert Data Types

If you want to do operations between data types, you will need to convert all data types to the same data type. To do so, refer to the guide below.

str() = Convert any type to a string

int() = Convert any type to an integer

float() = Convert any type to a floating point number

bool() = Convert any type to a boolean (true or false)

Dive Deep Into Python Lists

Like other programming languages, you can use lists to store multiple data points in Python.

Easiest Way to Build a List in Python

Let’s say that you would like to store all your Maths results as variables in Python. You could store them like this:

maths1 = 89.5
maths2 = 92.1
maths3= 32.5  
maths4 = 75.6

Or, alternatively, you could use square brackets [ ] to store your data into a list.

maths = [89.5 , 92.1 , 32.5, 75.6]
## [89.5 , 92.1 , 32.5 , 75.6]

How to Name Lists

You could also store different types of values within your list. To name your list, just add it in the square brackets.

maths = ["Q1",89.5,"Q2",92.1,"Q3",32.5,"Q4",75.6]
## ["Q1",89.5,"Q2",92.1,"Q3",32.5,"Q4",75.6]

How to Create Lists Into Lists in Python

You could add lists within a list. To create those sublists

mathssublist = [["Q1",89.5],["Q2",92.1],["Q3",32.5], ["Q4",75.6]]
## [["Q1",89.5],["Q2",92.1],["Q3",32.5],["Q4",75.6]]

Python Indexing and Lists Subsetting

In Python, subsetting is the process of retrieving just the parts of a list. Python does this by using integers. This indexing allows you to get, change or delete only a single cell of a list.

Each element of a list has its own integer attributed to.

Subsetting lists

In our list, to get the result 32.5, all I would do is call it by its integer.


or by calling it with its negative index.

Negative Indexes

Now, let’s look at how we can select data from a list using list slicing.

Basics of List Slicing

This is truly a beginner Python move to learn.


To select multiple indexes, all you have to do is to use the colon “:” within the brackets. Just understand that the first number is inclusive and the last number is non-inclusive.

maths = ["Q1",89.5,"Q2",92.1,"Q3",32.5"Q4",75.6]  

In our example, the fourth value will not figure in the output.

What Happens If You Leave Out a Value?

You can leave out either the value before or after the colon. What will happen is that the index will be considered to have a value of “0”.

Like this:

maths = ["Q1",89.5,"Q2",92.1,"Q3",32.5"Q4",75.6]  

Or like this:

maths = ["Q1",89.5,"Q2",92.1,"Q3",32.5"Q4",75.6] 

You now know how to select data from a list.

So what?

Now let’s dive into the cool stuff.

5 Insanely Useful Manipulations You Can Do With Lists


We understand what indexing and list subsetting are, and we know how to select some data from a list using list slicing.

Let’s see what manipulations we can do to modify lists using Python Indexes.

1. Change a Single Value in a List With Python

To replace values in a list using python, you need to use the square brackets that we used for subsetting a list and assign new elements to it.

Let’s say we re-took our Q3 maths exam and want to change the score.

maths[5] = 96.4
## maths=["Q1",89.5,"Q2",92.1,"Q3",96.4,"Q4",75.6]  


Now, let’s replace more than one value in our list.

2. Change Multiple Values of a List With Slice Notation

To change multiple items in a list at one time in Python, we will use the same strategy as before. All we have to do is subset vectors and assign new values.

We retried on Q3 and Q4 exams.

maths = ["Q1",89.5,"Q2",92.1,"Q3",32.5,"Q4",75.6] 
maths[4:8] = ["Q3",100,"Q4",100]
## maths = ["Q1",89.5,"Q2",92.1,"Q3", 100 ,"Q4",100]  


Believing this Python Course, you are a pro in maths.

3. Create a sublist from a list using slicing

maths = ["Q1",89.5,"Q2",92.1,"Q3",32.5,"Q4",75.6]
mathssublist = maths[2:4]

4. Subset and Calculate Values

maths = [89.5,92.1,32.5,75.6]
mathsavg = (maths[0]+maths[1]+maths[2]+maths[3])/4 


maths = [89.5,92.1,32.5,75.6]
mathsavg = sum(maths[0:4])/4

5. Add And Remove Values From a List

To add a new element to a list you can use the plus “+” operator.

maths = ["Q1",89.5,"Q2",92.1,"Q3",32.5,"Q4",75.6]
Q5 = maths + ["Q1",86.0]
## ["Q1",89.5,"Q2",92.1,"Q3",32.5,"Q4",75.6, "Q5",86.0 ]  

To delete an element in a list, simply use del().

maths = ["Q1",89.5,"Q2",92.1,"Q3",32.5,"Q4",75.6]
## ["Q1",89.5]

Python Dictionaries

In Python, a dictionary is an unordered mapping of keys matching values. This dictionary can be used for later reference, just like a real dictionary.

Create a Dictionary in Python3

A Python dictionary is created using curly brackets {}.

dictionary = {'key': 'value'}
seo_dict = {
        "SEO":"Search Engine Optimization",
        "SEM":"Search Engine Marketing",
        "NumPy":"Numerical Python",
        "SERP":"Search Engine Result Page",
        "ccTLD":"country code top-level domain",
        "DA":"Domain Authority",
        "HTML":"Hypertext Markup Language",
        "HTTPS":"Hypertext Transfer Protocol",
        "PPC":"Pay Per Click"
## "Hypertext Transfer Protocol"

Update Dictionaries

In our previous example, there is an error. HTTPs doesn’t stand for “Hypertext Transfer Protocol”, but for “Hypertext Transfer Protocol Secure”.

To modify an entry, you can replace it simply by selecting the element using the square brackets [].

##{'SEO': 'Search Engine Optimization','SEM': 'Search Engine Marketing','NumPy': 'Numerical Python','SERP': 'Search Engine Result Page','JS': 'JavaScript','ccTLD': 'country code top-level domain','DA': 'Domain Authority','HTML': 'Hypertext Markup Language','HTTPS': 'Hypertext Transfer Protocol','PPC': 'Pay Per Click'}

#Select the element
## "Hypertext Transfer Protocol"

#Select the element and replace the value.
seo_dict["HTTPS"] = "Hypertext Transfer Protocol Secure"
## "Hypertext Transfer Protocol Secure"

You could also replace a value by using the .update method.

seo_dict = {
        "SEO":"Search Engine Optimization",
        "SEM":"Search Engine Marketing",
        "NumPy":"Numerical Python",
        "HTTPS":"Hypertext Transfer Protocol"

#Update the value
seo_dict.update({"SEO":"Search Engine Optimization","SEM":"Search Engine Marketing","NumPy":"Numerical Python","HTTPS":"Hypertext Transfer Protocol Secure"})

##'Hypertext Transfer Protocol Secure'

To remove a value, use .pop().

##{'SEO': 'Search Engine Optimization','SEM': 'Search Engine Marketing','NumPy': 'Numerical Python'}

Conditions (If/Elif/Else)

Programming was originally base on a simple idea. If this happens, then do this, if not do that. This is what we call a boolean operation that is used in all programming languages. Everything can be coded with bits of zeros and ones, hence the weird code we often see “10011…”.

To code these booleans in Python, we use the if, elif and else conditions.

If Statement

Let’s see how that works. This condition can be read like this: “If this is true, then do this”.

When a condition is true:

x = 200
y = 155
if x > y:
    print("x is greater than y")
## x is greater than y

When a condition is false:

x = 200
y = 255
if x > y:
    print("x is greater than y")
## Error

When you make a program, you want to remove those errors by completing your code. Here comes the elif statement.

Elif Statement

The elif statement goes like this: “if the previous conditions were not true, then try this condition”.

When a condition is True:

x = 200
y = 200
if x > y:
  print("x is greater than y")
elif x == y:
  print("x and y are equal")
## x and y are equal

When a condition is False:

x = 200
y = 255
if x > y:
  print("x is greater than y")
elif x == y:
  print("x and y are equal")
## Error


We still get an error. We are going to close the loop using the else statement.

Else Statement

The else statement goes like this: “if the if condition is false, and all the elif conditions are also false, then do this condition”.

x = 200
y = 255
if x > y:
  print("x is greater than y")
elif x == y:
  print("x and y are equal")
  print("x is greater than y")
## x is greater than y

If Else One Liner Using Ternary Operators

The ternary operator is a simple way to convert an if / else conditional statement into a one-liner.

condition_if_true if condition else contition_if_false 

Let’s take our earlier example.

x, y = 200, 255
"x and y are equal" if x==y else "x and y are not equal"
## 'x and y are not equal'

Nested Ternary Operator

You can create nested ternary operators using parentheses ().

z = 200
"Less than 10" if z<=10 else ("11-100" if z<=100 
else ("101-500" if z<=500 else "Greater than 500"))

Built-In Python Functions

Now, let’s look at basic Python functions.

What Are Python Functions?

A function in Python is a block of reusable code that is used to perform a single specific task, and only runs when it is called.

Basic Python Functions Functions

Python has a number of built-in functions.

  • print()
  • sum()
  • len()
  • input()
  • type()


The print() function lets you print a specific result on a screen.

x = "I love SEO"
## I Love SEO

Sum() and Len()

When we want to calculate the average of our maths results, we could have passed the variable “maths” to the function sum(), that added the values, and to the len() function, that returns the length of the string.

maths = [89.5,92.1,32.5,75.6]
mathsavg = sum(maths)/len(maths) 
##This is equivalent to 
##mathsavg =(maths[0]+maths[1]+maths[2]+maths[3])/4  


The input() function in Python shows a message to the user and prompts him to do an action.

user_answer = input("What is your favorite SEO programming language?")

#Message in the console
What is your favorite SEO programming language?

At this point, the console will wait for the user to answer before running the code.


The type() function simply let you know what is the type of a selected variable.

type("data science is fun!")

Get Help

To see how a function works, all you have to do is to call the function using help() or ? before the function in IPython.

#Help on built-in function len in module builtins:
#len(obj, /)
#  Return the number of items in a container.

User-Defined Functions

A function has four parts: the def statement, the function name, your arguments passed in the parameters, the program statement.

# The part where you pass your arguments is known as "parameters"
def yourFunction(arg1, arg2, arg3):
    ## Pass your function's statements
    ##End Function
#Call the Function

Here is a great video by Datacamp to understand the basics to define your own function.

How to use Functions?

Earlier, we could have used an existing function to solve a task instead of manually coding it yourself.

All we need to do is:

  • Define your function using Def
  • Give the program statement
  • End your function
  • Call your function
  • Pass your arguments to your function()

Define the Function

To define a function in Python, you need to use the def keyword.

def myPythonFunction():

Give the Program a Statement

def myPythonFunction():
     y = 3*4

End the Function

To end a function, you can use the return statement.

Note that return does not print out the value, it returns when the function is called.

def myPythonFunction():
    y = 3*4
    return; #End Function
#If you run it this way nothing happens.

Call The Python Function

To call the Python function that you have defined, just add the name of the function after the return statement.

def myPythonFunction():
    y = 3*4

Pass Arguments to the Function Parameters

See that we have not passed any arguments to the parameter of the function… So far.

What if we don’t know the first value yet?

def myPythonFunction(x):
    y = x*4

Python Methods

A method in python is similar to a function, except it is associated with an object or a class. Depending on the type of an object, the available methods are different.

Methods are functions that belong to Python objects.

The two major differences between methods and functions in python are:

  • The method is called on an object (like str, float or int) and is dependant on that object.
  • The method can operate on the data that is contained within the class.

How to Use Methods in Python?

There are a lot of built-in methods that you can use. Remember, a method is dependant to an object. So, to use a method, you need to use dot (.) notation.



In this example, we have an object of type “list”. Thus, we need to find methods that can be applied to a list.

Then, we need to call the object, followed by a dot (.) and the name of the method.

maths = ["Q1",89.5,"Q2",92.1,"Q3",32.5,"Q4",75.6]

Useful methods

  • index(): returns the index of the 1st element of a list that matches the argument.
  • count(): counts the number of times an element occurs in a list.
  • replace(): searches a string for a specified value (or Regex), and replace the specified values with the ones provided.
  • sort(): sorts the elements of an array in place and returns the sorted array.
  • remove(): Removes the first element from a string that matches the specified arguments.
  • append(): Adds a specified element to a string.
  • upper(): Capitalize all letters.
  • lower(): Convert all letters to lowercase.
  • split(): Split a string into several elements.
  • is_integer(): Find if a number is an integer or not.

Packages: Unlock The True Power of Python

This is all very interesting, but how can a beginner start using Python for SEO or Data Science?

Python Packages…

Packages are really helpful because they are directories of Python Scripts that specify functions and methods so you can make advanced operations without even understanding what is under the hood.

To use a package, you need to:

  1. Install the package
  2. Import the library
  3. Learn how to use the package

What are the Most Commonly Use Python Packages?

For all practical uses, there are more Python packages that you can use. So, where to start?

Some of the most popular Python libraries are:

Python Package NameHow is it used
PandasData analysis and manipulation
NumPyArray processing
MatplotlibData visualisation
SeabornData visualisation
RequestsHTTP requests
Scikit-learnMachine learning library
KerasMachine learning library
TensorflowMachine learning library
Most popular python packages

1. Install Python Packages

If you have installed Python using Anaconda, you might already have installed some of the packages you want. If they are not included, you will want to install the packages yourself.

You can do this in two ways:

  • Using conda command (for conda packages)
  • Using pip command (for non-conda packages)

Pip packages don’t have all the features of conda packages. Try first to install packages with conda. If the package is unavailable through conda, you can try installing it with pip. Both conda and pip are installed natively when you install Python using Anaconda.

Install Packages Using Conda

Before we start installing packages, let’s see if we already have them installed first.

Let’s see if a specific package, such as SciPy, is already installed.

To do this, go to the Anaconda Prompt.

Type the following code:

conda search scipy

If the package is available, but not installed, you can install it by typing the following code.

conda install scipy

Install Packages Using Pip

To install the SciPy package using pip,

pip3 install scipy

You can also follow the official Python tutorial to learn how to use pip for the installation of your package.

2. Import Python Packages

Before you can start using a package, you need to import the package. You can do this either in your Python Script or straight into the IPython Shell using the “import” command.

import pandas

Alternatively, you could import a package using a shortened name to make it faster to use your code later. To do this, use the “as” command.

import pandas as pd

3. How to Use The Package?

So, to call a function for a package, you need to call the package first (as we have done earlier calling a variable), and then call the function.



A common operation that you’ll need is to import a CSV. To do this, there is a function in the pandas package called read_csv().

If you try to use only read.csv() to call your file, you’ll end-up with an error. Instead, call the package first with one of these appellations.

import pandas 

Or, use the package under a different name.

import pandas as pd

For, While Loops

You might want at some point to create action over and over without manually typing the function all the time.

The python loops will help you repeat the action until a condition is met.

This is what we call an iteration.

Python has two native loop commands:

  • while loops
  • for loops

The While Loop in Python

The while loop in Python states that you need to execute a set of instructions for as long as the condition is True.

#What user input
x = 3
while x < 10:
    print("I love SEO")
    #Increase by 1 at each iterations
    x = x+1
##I love SEO
##I love SEO
##I love SEO
##I love SEO
##I love SEO
##I love SEO
##I love SEO

The For Loop in Python

When you know in advance the number of iteration your loop should perform, you can use the favor for loop over the while loop.

Let’s say that you deeply love learning python for SEO and you want to shout it out three times.

To do this, use a for loop.

for x in range(3):
    print("I F**cking Love Using Python for SEO")
##I F**cking Love Using Python for SEO
##I F**cking Love Using Python for SEO
##I F**cking Love Using Python for SEO

Useful Resources

Python Programming FAQs

🐍What is Python?

Python is a programming language created by Guido Van Rossum that can be used for programming and scraping websites, automation and SEO.

🔥How to install Python?

Beginners should install Python using Anaconda.

What are the Best Python Tools?

The best Python Tools are Jupyter Notebook, Spyder IDE and Selenium.

❤️What should you learn first?

Beginners should start learning Python basic building blocks, Jupyter Notebook, Python libraries and APIs.


At last, you now understand everything you need to get started using Python for SEO and Data Science. Congratulations, you completed this absolute guide for Python Beginners.

4.8/5 - (5 votes)