Python is one of the fastest growing programming languages out there and that huge popularity is in large part down to its use as a language for machine learning. If you’re interested in machine learning or data science, picking up some basic skills in Python will give you the head start you need to succeed 🌟

🤖 Table of Contents 🤖
What is Python?
Why you should learn Python
How to get started with Python
Python essentials
Your first Python program
Fixing Bugs
Python in the wild

What is Python?

Whenever you hear someone talk about Python (in the context of computers, not reptiles), they’re referring to the Python programming language. When you “program” in Python it means you’re writing code that adheres to Python’s syntax rules.

Python is an example of what’s called a high-level language. This means your code has to be processed (or compiled) before your computer, which only understands low-level languages (aka machine language), can run it.

Most programs that let you write Python in their interface will automatically do the processing/compiling for you, but it’s useful to know what’s going on under the hood regardless.

Python is also one of the fastest growing programming languages out there and is used all over the place.

For instance, part of Google’s search engine is written in Python. Same with YouTube. Python is used to track financial interactions at banks, to program surgeon robots, and to create tools for NASA’s Mission Control Center. Even Disney uses Python to automate the repetitive parts of animating movies.

Python is also one of the most popular programming languages used for machine learning and artificial intelligence #ftw.

FYI the name Python comes from the cult-classic British comedy Monty Python – not the snake 🐍

Why you should learn Python

There are literally hundreds of coding languages out there though, so why pick Python?

Well, that’s easy – because when it comes to mastering machine learning and data science, it’s the 💣and is one of the few languages that’s simultaneously simple to write, easy to understand and powerful in practice.

Python is:

It’s a really simple and minimalistic language that’s specifically designed to be as readable and simple for the programmer as possible. And it’s one of the easiest codes to read, especially for those of us from a non-programming background.

Easy to learn
Since it’s such a simple language it’s easy to get started right away #obvs.

Free and open source
Python is an open source language which means that anyone can access copies of it, read its source code, make changes to it, and use it to make their own cool stuff. The whole philosophy of the open source movement is based on the concept of a community of users who share knowledge with each other.

A high-level language
High-level languages are (generally) designed to be easy for humans to understand so when you write programs in Python you don’t have to worry about computer-level (boring) concerns like how much memory your program is using.

Python can work on many different platforms and definitely all of the major ones like Windows, Mac, and Linux are ready to go.

Python doesn’t need to be translated into the machine’s language so you can just run the program directly and then Python translates it into the 1’s and 0’s that a computer understands. This is part of the reason why Python is so portable – you can just copy your Python program onto any computer and it works.

Full of tools
Python comes with a lot of useful tools and pre-programmed code that lets you do all sorts of cool things straight out-of-the-box. This makes it easier and quicker to build your own programs and is why Python fans say that the language comes with “batteries included”.

One of the fastest growing programming languages
Because who doesn’t want to hang with all the cool kids?

Getting started with Python

Unless otherwise stated, all projects and tutorials on Elle Knows Machines use Python 3, so if you’re going to want to try any of them yourself you’ll need to install Python on your computer.

Luckily, getting Python onto your computer is a breeze. You don’t even need any programming experience to get started 🙌

There are three different ways of installing and/or running Python on your own computer:

  1. Install Python directly and use Python’s own workspace to write and run code
  2. Install Anaconda’s distribution of Python and then use Anaconda’s workspace (called Spyder) to write and run code
  3. Use a “notebook” to run code from your browser

Each of these options has its own pros and cons and if you’re not sure which one’s best for you, you can always try alternating between the different methods until you find the fit that feels right.

How to install Python

If you’re looking to dive right in, then installing Python directly is a good way to go.

Installs of Python automatically come with IDLE which is a really fast and lightweight IDE (integrated development environment). This means that once you’ve installed Python you can get up and running without losing time waiting for a larger program to launch first.

IDLE is great when you’re doing introductory Python tutorials or working on smaller-scale projects that are specifically focused on Python development.

If you’re looking to do anything machine learning related though, installing all of the different libraries can be a bit of a pain (and major time drain) so I generally use IDLE only when doing Python specific work.

Here are instructions on how to install Python.

How to install Anaconda

Anaconda is a piece of software that runs Python and comes pre-loaded with 250+ of the most popular Python data science packages (bundles of pre-written code).

Anaconda provides a workspace that’s pre-configured to work with all of the major machine learning libraries. It’s probably the easiest way to get started with Python for machine learning.

Anaconda’s IDE is called Spyder and has a really easy to use and intuitive interface. IMO the downside of Anaconda is that it’s a bit slower to load when starting up so I tend to use Python’s IDLE for quick tasks but Anaconda for anything specific to machine learning.

If you’re doing any tutorials or projects that are specific to machine learning, then Anaconda is definitely the way to go.

Here are instructions on how to install Anaconda.

How to use notebooks

If you want to work with Python without installing anything on your computer then your best bet is to use Colab’s cloud-based Jupyter Notebook environment.

Jupyter is an open-source web application that allows you to create and share docs that contain live code and text. Colabs are like Google Docs and Jupyter Notebooks mixed into one.

Notebooks are great for exploring and playing around with data without needing to download, install, or run anything on your own computer. Plus, if you use Google Sheets or Docs then Colab’s interface will feel pretty familiar and you can easily share with other Google users.

The downside is that notebooks are not production code so you won’t get the same output as you would if you were writing/running an actual program.

If you want to try notebooks, check out this one.

Python essentials

Python has all sorts of bells and whistles, including a whole range of syntactical constructions, library functions, and development features.

Luckily, we can ignore almost all of this – we just need enough Python to be able to manipulate data and run some pre-written machine learning algorithms.

The goal of this tutorial isn’t to turn you into a Python developer, but rather to introduce you to some of the basic elements of Python so you can begin experimenting sooner.

If you do decide you want to learn more, there are a bunch of really great free resources out there that will jump-start your new life as a Python programmer.

For our purposes (aka to begin unlocking our machine learning superpowers) we’re going to need to get some basic programming concepts under our belt.

They may seem kinda boring on their own, but they are the building blocks that will allow you to become a machine learning master in no time.

Protip: throughout this post (and across EKM) there are snippets of code that illustrate the different Python concepts. When you come across one, go ahead and run the code in your IDE or notebook to see what happens. Feel free to play around and customize the code so you really get a feel for what’s going on and how the different pieces work together.

Types of data

Spoiler alert: data is kind of a big deal. Whether it’s numbers, letters, characters, or pixels, computers run off of data. Therefore, it’s important to understand the different types of data that Python works with.

Integers and floats

In coding, whole numbers (numbers which are not fractions) are called integers (e.g. 2), while numbers with a decimal point are floats (2.5).

You can use variables to store numbers and to do math (if that’s your thing). Many, although not all, of the mathematical symbols are the same.

To do a simple calculation type the following code into your editor:

>>> x = 42
>>> y = x * 9
>>> print(y)


string value is a sequence of letters or other characters. Strings always have quotation marks at the beginning and end. So the line print(‘Hello World’) basically says “hey Python, print out the text between the quotation marks.” Anything you can type on your keyboard can be stored in a string.

So a string could be anything from: My name is Gabrielle to We are such stuff as dreams are made on to covfefe.

Boolean values

Boolean values are a pretty important to computers and they follow one important rule. They can only ever be True or False.

In computer terms, True = 1 and False = 0. Boolean values (as these True or False values are known) can be thought of as switches. If something is true, the switch is on and if it’s false, the switch is off.

In Python, the Boolean values of True and False must always be capitalized when written.


Variables store and label information – like putting something in a box with a label on the outside so you can find it again later. Variables are really useful and can be used to carry out actions such as performing a calculation, tracking a score in a game, or holding a list of information.

How to create a variable

Since a variable is used to store data, it needs a good name that will remind you what information is being stored within it. Then you need to decide what you’re actually going to store in that variable – this is the variable’s value. If the variable was a box or container, the value would be the contents.

To create a variable, or assign a value to the variable, type the name of the variable that you want to create, followed by an equals sign, followed by the value itself.

>>> kittens = 15
>>> kittens
>>> puppies = 3
>>> kittens + puppies
>>> kittens + puppies + kittens
>>> kittens = kittens + 6
>>> kittens

If you decide to assign a new value to a variable, Python will forget the old value. This is called overwriting the variable.

How to name a variable

You can name a variable anything you want as long as it follows three golden rules:

  1. It can only be one word
  2. It can only use letters, numbers, and underscores (_)
  3. It can’t begin with a number

Variable names are case-sensitive. It’s good Python etiquette to start variable names with a lowercase letter.

Flow control

Since programming is all about getting computers to do what you want it’s important to be able to clearly outline what it is that you actually want them to do. While you could do this by making a list of instructions for your program to work through one after the other, this isn’t very efficient. Luckily, Python has ways of letting us tell our programs to do things like skip some instructions, repeat others, and choose one out of several to run.

Making decisions

Every day computers have to make hundreds, if not thousands, of different decisions.

Computers are continually asking themselves questions that usually involve comparing one thing to another. So, a computer might ask whether one number is bigger than another, or whether a statement is True or False via a Boolean value.

Logical operators

#Funfact: no matter how hard you try, you just can’t make a computer be illogical. Everything in programming is fundamentally based on logic. Any time your computer does something wacky, unexpected, or downright annoying, you can basically guarantee that there is a logical explanation. This means that the code used to denote logic in Python is pretty important.

A few key logical operators include:

Operator Meaning
== Equal to
!= Not equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to

You can also use the Binary Boolean operators and, or, and notto determine whether something is True or False.


Part of the reason that decision making is so important to computers is that they need to make decisions about which parts of a program to run.

The ability to make decisions is what allows computers to do different things in any number of different situations.

The way that decisions are made is through what is called branching.

Think of it like paths branching off into side paths, where each one leads to a different destination. Again, logic is crucial here.

If statements

The most common type of branch is the if statement. If an if statement is True, then the following block of code will run. If it’s False, then the following block of code will be skipped. In Python, an if statement looks like this:

is_hot = input('Is it hot outside? (yes/no) \n')
if is_hot == 'yes':
    print('Get an iced latte')

Else statements

You can follow an if statement with an else statement.

An else statement will only happen if the condition of the if statement is False, so the computer will make the following decision: “if this condition is true, execute this code. If not, execute that code.”

greetings = input('How are you? (good/bad)\n')
if greetings == 'good':
    print('Rock on')
    print('That sucks')

Elif statements

You can use an elif statement to provide more than two possible paths for your program to choose from. The elif statement, or “else if”, follows an if statement (or another elif statement) and will execute only if all of the previous conditions were False.

name = 'Jane'
age = 18
if name == 'Alison':
    print('Hey, Alison. Want to get a cocktail?')
elif age < 21:
    print('No kids allowed')

You can also put an else statement after the final elif statement. If the condition of all previous if statements and elif statements are False then the else clause gets executed.

weather = input ('What\'s the weather going to be today? (rain/snow/sun) \n')
if weather == 'rain':
    print('Bring an umbrella')
elif weather == 'snow':
    print('Brr, winter coat it is')
    print('Wear sunscreen')


A loop runs the same block of code over and over again – so you don’t have to. Loops are the magic bullet for lazy people everywhere because they get the computer to do boring, repetitive tasks indefinitely, or until they are told to stop.

While loops

A while loop will run as long as the while statement condition is True. A while loop is similar to an if statement, except when the computer gets to the end of a while clause, the program jumps back to the beginning of the while statement, whereas when a computer gets to the end of an if clause it continues executing the rest of the code.

hey = 0
while hey < 5:
    print('How ya doin?')
    hey = hey + 1

For loops

A for loop loops the code for a set number of times. You can set the number of times that you want the code to run in a range function which counts all the numbers from the first number to one less than the second number.

print('Hi, my name is')
for i in range(5):
    print('Slim Shady (' + str(i) + ')')

Infinite loops

If you want your computer to run a while loop for as long as the program is running you can make an infinite loop. Do this by setting the loop condition to the constant value of True. Since True can never change on its own, the loop will never stop.

If you don’t literally want your code to loop for infinity you can always put in a break statement that will cause the condition to change to False.

while True:
    print('Please type your name.')
    name = input()
    if name == 'your name':
print('Nice to meet you.')

If you find yourself accidentally inside of an infinite loop (whoops!) you can escape by pressing CTRL+C/CMD+C. You might have to do it a few times but eventually your program will stop.


Functions are shortcuts that mean you don’t have to type out the entire name of a block of code every time you want to use it.

A function has a few different components: when you want to use a function you call it. You can make your own function when you define it.

A parameter is the piece of data that you give to the function to use and the data that you pass back from the function to the rest of your code is called the return value.

To call a function you type the function’s name followed by a set of brackets that contain any parameters that you want the function to work with. If your function doesn’t need parameters you can always leave the brackets empty.

Built-in functions

Python has a bunch of functions that are already built-in, all you have to do is call them. Some examples that we’ve already seen are the input() and print() functions. Input() lets the user give data to the program by typing it in while print() displays the results, or output, on the screen.

Making your own functions

You can also make your own functions. Since you’re probably going to use your functions multiple times as you write your code it’s important to give them a descriptive name.

Here’s an example of code where we’ve made our own function:

def hello(name):
    print('Hello ' + name)


Data structures

Python provides a few different ways of structuring your data. Being able to structure your data in multiple ways allows you to create more complex programs and to work with and manipulate lots and lots of data with relative ease.


A list stores data and contains multiple values called items. Python stores items in an ordered sequence and separates each item by a comma (aka comma-delimited). Lists are cool because not only can you store them in variables (labeled boxes), but you can also store lists within lists which is useful if you want to create a data hierarchy.  Lists are also good when you have a lot of things that you might need to change often.

To create a list, surround the items that you want to store with square brackets:

>>> cant_leave_house_without = ['iphone', 'lip gloss',
'hand cream', 'notebook', 'sunscreen', 'water bottle']
>>> stuff_on_my_desk = ['macbook', 'coffee cup',
'camera', 'phone charger', 'notebook', 'cactus']

Python assigns each item in a list a number starting from 0 #justbecause. To find an item in your list, type the name of the list and then add the item’s position in the list, putting that inside square brackets. Like this:

>>> cant_leave_house_without[0]
>>> stuff_on_my_desk[5]

This is also known as slicing.


The tuple data type is just like the list data type, except tuples are inmutable. This means that they can’t have their values modified, appended, or removed.  And they look different.

>>> my_details = ('Gabrielle', '', 2018)


Like lists, dictionaries are labeled collections of values. But unlike lists, the data held in a dictionary is unordered. To get a value from a dictionary you use what’s known as a key.

>>> favorite_shows = {'Amy': 'Stranger Things', 'Karl': 'House of Cards', 'Suzie': 'The Office'}
>>> favorite_shows['Amy']
'Stranger Things'

Your first Python program

No matter what language you’re learning, odds are the first program you’ll write is “hello world” so here we go 🎉

What we’re doing:
This simple program will display the message “Hello world!” and then ask for your name. Once you’ve typed your name, it’ll say hello again but this time include your name in the greeting.


  1. Launch IDLE or Spyder.
  2. Open a new file by clicking on File > New File or using the hotkeys CTRL + N on a PC or CMD + N on a Mac.
  3. In the editor type the following code:
# This program says hello and asks for your name

print('Hello world!')
print('What is your name?') 
yourName = input()
print('Nice to meet you, ' + yourName)
  1. If you’re working in IDLE, save the file and then hit F5. If you’re in Spyder select all of the code that you’ve just written and hit CTRL + Enter / CMD + Enter. You’ll see your program in the console on the right hand side of your screen.
Hello world!
What is your name?
Nice to meet you, Gabrielle

Boom! You’ve just written your first program.

Here’s a breakdown of the building blocks that were used in this program:


You might have noticed that the first line of code starts with a hashtag (#). We’re not Instagramming this bad boy though, in Python this means all text on that line is a comment.

Python ignores comments, so you can use this as a way of writing notes to yourself or others. This is useful if anyone else reads your code and wants to know what you’re doing or if you forgot what you wanted your code to do in the first place.

You can also put a # in front of any line of code when you’re testing it out to temporarily remove it from what’s being read and executed – like saying “ignore this bit”. This is called commenting out code and you can remove the # later when you’ve got everything up and running as you want it.

Python also ignores the blank line after you comment. Go wild and add as many blank lines as you want. Or not. It’s your call.

Print() function #1

The second, and most used, element in the Hello World program is the print() function. This displays a string value on your screen.

Input() function

The next part of your program asks the user to provide an input. Whatever the user enters here gets assigned to the yourName variable as a string.

Print() function #2

Once the program has the user’s name it joins the phrase ‘Nice to meet you’ with the variable that contains the user’s name. This is then printed on the screen.

Fixing bugs

A computer will only do what you tell it to. This means that when you write code you have to be explicit with what you’re trying to do or else you’re likely to end up with what’s called a bug.

Bugs are errors in a computer program that cause it to produce incorrect results or behave in unexpected ways. Most bugs come from mistakes or errors made in the program’s code. Creating bugs are a totally normal part of programming, even professional programmers make them all the time and end up spending a lot of time “debugging”.

When something goes wrong with your code, Python will show an error message that tells you what type of error occurred and where to look in your code to fix it. These messages can be very long so don’t panic. Usually, the most actionable info is at the very top, so start from the beginning of the error message and then work your way down.

FYI bugs are much easier to fix the sooner you find them, so it’s good practice to stop frequently and check your code works like you want it to.

If there’s a problem, have a go fixing the line in question and run it again!

Here are a few common types of error messages:

Syntax errors

These indicate that you typed something incorrectly. Check through your code for typos or incomplete Python syntax. Are you missing a bracket or quotation mark? If you have a pair of brackets or quotation marks, do they match?

Indentation errors

Indenting is a key part of the Python syntax and is required to indicate what block of code a statement belongs to. Likewise, the amount of indentation matters – missing or extra spaces could cause unexpected things to happen.

If a line of code ends with a colon (:) the next line has to be indented. Every line in a particular block of code must be indented by the same amount and while Python automatically indents after colons you should still check that everything is lined up properly, especially if you’re copying and pasting code from the internet.

Type errors

Type errors happen when you mix up different types of data, like numbers and strings.

Example of code that would cause a type error: hot_day = '20 degrees' > 15

Python will spit out one of these error messages when your code asks Python to do something that doesn’t make sense, like comparing two totally different types of data or finding a number in a list of letters.

Name errors

Name errors occur when your code uses the name of a variable or function that hasn’t been created yet. Always remember to define your variable and functions before you use them! To prevent name errors it’s good practice to define all functions at the top of your program.

Logical errors

Logical errors are probably the most annoying kinds of errors to debug because Python doesn’t give you an error message telling you what to look for, you’ll just be able to tell that something’s gone wrong. The code might be syntactically correct but if you forget to put an important part of the program in place or put the components of code in the wrong order your program will start acting crazy.

If your program doesn’t do what you expect it to, start reading through your code carefully, checking the logic of what you’re telling the computer to do. You’ll get better at catching these kinds of errors the more experienced you become.

Python in the wild

That was a whistle-stop tour of the most basic elements of Python. If you’re interested in learning more there are some amazing (and free!) resources out there that will walk you through coding with Python, from simple projects to super complex programs.

September 2, 2018