SchoolWhool
Quizzes and saved progress, freeSign in freeSign in

Python 1.1Free video10 minLesson 1 of 6 in Module 1

Why Python?

Say what Python is and why it is used for AI and machine learning, and know where Python code is written and run.

Free sample. Everything in this module opens with a free account.

Watch or read the lesson: Why Python?

01What Python is

Take a look at these seven lines of code:

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
model = LogisticRegression(max_iter=1000).fit(X_train, y_train)
print(model.score(X_test, y_test))
0.9736842105263158

They load a dataset, train a machine learning model, and then check how accurate that model is. The number at the bottom is that accuracy: the model got about 97% of its test examples right. Just seven lines.

You probably don't understand much of this code yet, and that is completely fine. By the end of this course you will be able to write every single line yourself, and, more importantly, you will understand what each line does and why it is needed.

Before getting into machine learning and AI, though, you need something more fundamental: the language all of this is written in. That language is Python.

A programming language

So what exactly is Python? Python is a programming languageKey termPrecise rules for writing instructions a computer can carry out.. If you are completely new to programming, a programming language is a way of giving instructions to a computer. People use English to communicate with each other; we use programming languages to tell computers what to do.

The difference is that a computer needs very precise instructions. You can't tell a computer to "figure something out" and expect it to know what you mean. You have to write instructions that follow a specific set of rules, and when you put those instructions together, you get a programKey termA set of instructions for a computer, written as text..

So the seven lines at the top of this page are a program. Throughout this course you will write lots of programs like that.

Three things that make Python different

Python is not the only programming language. There are Java, C++, JavaScript and plenty of others. So what makes Python different? There are three things worth understanding.

High level

First, Python is a high-level programming language. Don't let the term put you off: it simply means that Python handles a lot of the complicated work behind the scenes.

When you write a Python program, you don't normally have to worry about where a value is stored in the computer's memory, or how the processor executes each instruction. Python takes care of those low-level details for you. Instead of dealing directly with the hardware, you can focus on what you actually want your program to do, and that makes programming much easier, especially when you are starting out.

General purpose

Second, Python is a general-purpose language, which means it is not limited to one kind of task. You can use Python to build websites, automate repetitive tasks, analyze data, or train machine learning and AI models.

That is one of the nice things about learning Python. You are learning it for machine learning and AI, but the skills you develop here will be useful in plenty of other areas too.

Interpreted

Third, Python is commonly described as an interpretedKey termExecuted one statement at a time by a program called the interpreter, so each line's result can be seen straight away. language. What does that mean?

When you write Python code, you normally don't have to compile it by hand into a separate executable file before running it. Instead, you use a program called the Python interpreter to run your code.

And in an interactive environment, you can execute a small piece of code, see what happens straight away, and then try something else. Here is a cell that stores three grocery prices and adds them up:

bread = 2.25
milk = 1.25
eggs = 3.50
total = bread + milk + eggs

Running it shows nothing, because it only stores values. To see the total, run one more small piece of code:

total
7.0

You see the result right away. Now you can try something else, building on what is already there:

total * 2
14.0

Run a little, see the result, try something else. That is especially useful when you are learning, and it is exactly how you will work throughout this course.

A little history: Python 2 and Python 3

Python was created by a programmer called Guido van Rossum, and it was first released in 1991. So Python has been around for quite a long time, and over the years it has gone through several major updates. Today, we use Python 3.

That matters for a practical reason. While you are learning, you will probably search online for examples and tutorials, and sometimes you will come across code written for Python 2. Python 2 is an older version that officially reached the end of its support in 2020, and some of its syntax is different.

For example, in Python 2 you could write a print statement without parentheses:

print "hello"
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?

That line is Python 2 code, so Python 3 refuses to run it. In Python 3, you write print with parentheses:

print("hello")
hello

So if an old tutorial uses print without parentheses, check whether it was written for Python 2 before you copy the code.

02Python for machine learning

Now for a really important question: why use Python for machine learning in the first place? Why not Java, C++ or some other language? There are a few reasons, but the biggest one is its libraries.

What a library is

Imagine you want to train a machine learning model. You could try writing all the mathematics and algorithms yourself, from scratch. But that would take a lot of time, and there is a good chance you would make mistakes along the way.

Fortunately, you don't have to. Other developers and researchers have already written a lot of this code and made it available for everyone to use. That is essentially what a libraryKey termPublished code your program can import and use: NumPy, pandas, Matplotlib, scikit-learn, TensorFlow, PyTorch. is: a collection of code that you can bring into your own program instead of writing everything yourself.

Here is what that looks like. The first line brings the NumPy library into your program, and the second line uses some of its code:

import numpy as np
print(np.sqrt(16))
4.0

np.sqrt calculates a square root. You never wrote a square root function; you imported one that someone else had already written. And Python has an enormous ecosystem of libraries like this for data science, machine learning and AI. Here are the ones you will come across in this course.

NumPy

NumPy helps you work efficiently with arrays of numbers. An array holds many numbers together, and you can work on all of them at once. Here are the three grocery prices as a NumPy array, doubled in a single step:

import numpy as np
prices = np.array([2.25, 1.25, 3.50])
prices * 2
array([4.5, 2.5, 7. ])

Every price is doubled at once. When you are dealing with large amounts of numerical data, that becomes extremely useful. Here is an array of a million numbers, added up:

big = np.arange(1_000_000)
print(big.sum())
499999500000

pandas

Then there is pandas. pandas is designed for working with structured data, especially tables. Here are the same three prices as a pandas table, called a DataFrame, with a column for the item and a column for its price:

import pandas as pd
df = pd.DataFrame({"item": ["bread", "milk", "eggs"],
                   "price": prices})
df
    item  price
0  bread   2.25
1   milk   1.25
2   eggs   3.50

That is a table of three rows and two columns. Now imagine a dataset with thousands of rows of customer information, sales figures or anything similar. pandas makes it much easier to load, organize, filter and analyze that data.

Matplotlib

Next is Matplotlib, a library for creating visualizations. Instead of staring at hundreds of numbers, you can turn them into line charts, bar charts, scatter plots and other useful graphs. This cell draws the three prices as a bar chart, one bar per item:

import matplotlib.pyplot as plt
plt.bar(df["item"], df["price"])
plt.show()

The output is a picture rather than text: three bars labelled bread, milk and eggs, with eggs the tallest at 3.50 and milk the shortest at 1.25.

scikit-learn

Then there is scikit-learn, one of the most important libraries for traditional machine learning. It gives you ready-to-use implementations of algorithms such as linear regression and decision trees, and many others. Using one starts with an import:

from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeClassifier

This cell prints nothing. It just makes the two algorithms available to the rest of your program.

TensorFlow and PyTorch

If you go further, into deep learning, you will come across libraries such as TensorFlow and PyTorch. They are widely used for building and training neural networks and deep learning models.

The seven lines again

Look back at the seven lines at the top of this page. Much of the heavy lifting in that example is done by scikit-learn: load_iris, train_test_split and LogisticRegression all come from it. So you don't have to write the training algorithm yourself. You will still learn how it works, and when to use it.

Readable code

Libraries aren't the only reason Python is so popular. Another big reason is that Python code is relatively easy to read.

In many programming languages, even a simple task can involve quite a bit of syntax. Python tries to keep things straightforward. Here is the grocery calculation again, as one cell:

bread = 2.25
milk = 1.25
eggs = 3.50
total = bread + milk + eggs
total
7.0

The task is "add the three prices", and the line that does it reads total = bread + milk + eggs. Python code is often short, clean and fairly close to the way you would describe the task in plain English. That makes it easier to focus on solving the problem rather than getting lost in complicated syntax, especially when you are learning to program for the first time.

Python and R

There is another language you might hear about in data science, called R. R is particularly popular in statistics and statistical computing. For this course, Python gives you the machine learning libraries you need, alongside the general-purpose features you have already met.

03Jupyter notebooks and Google Colab

Knowing which language to use is only half the story. You still need somewhere to actually write and run your code, and that is what you will set up next.

Throughout this course you will use a notebookKey termA document made of cells. A code cell holds Python that can run; a text cell holds notes. Jupyter notebook files end in .ipynb.. If you have never used a programming notebook before, the idea is simple: it is a document where you can write code, run it and see the results, all in the same place.

Cells

A notebook is divided into sections called cells, and there are two types you will mainly work with: code cells and text cells.

A code cell is where you write your Python code. When you run that cell, its output appears right below it. Every code example on this page is a code cell, and the box after each one is what appears below it when it runs.

A text cell is where you write explanations, headings or notes. For example, a notebook for the grocery calculation might have a text cell with the heading "Groceries" and the note "The total cost of three items from the shop", followed by the code cell that adds up the prices, and that cell's output, 7.0, right below it.

That means you can keep an experiment's code, its results and its explanation together, in one document, as you work through it.

Jupyter

The notebook format you will use is called Jupyter. You can recognize a Jupyter notebook file by its extension, .ipynb.

Google Colab

Normally, to run Python notebooks on your own computer, you would need to install Python and set up the tools you want to use. This course makes that much simpler by using Google Colab.

Colab is a service from Google that lets you run Jupyter notebooks directly in your web browser. So you don't need to install Python or configure a development environment just to get started. You open Colab, create a notebook and start writing code. The code runs on computers provided by Google, you can save your notebooks in Google Drive, and you can get started for free.

Open Colab

So let's open it:

  1. Go to colab.research.google.com.
  2. Sign in with your Google account.
  3. Create a new notebook.

That's it. You now have a place where you can write and run Python code: an empty code cell, ready for your first line.

The next lesson explores the Colab interface properly, so don't worry about understanding every button or menu just yet. For now, the aim is simply to get comfortable opening a notebook.

04Recap and challenge

Come back to where this lesson started: those seven lines of machine learning code. At the start of this lesson, they probably looked a little unfamiliar.

You don't need to understand every line yet. But you now know three things about them. The language is Python: high level, general purpose and interpreted. Libraries such as scikit-learn provide the algorithms. And Colab gives you somewhere to run the code.

Your challenge

Here is a very small challenge before you move on to the next lesson:

  1. Open Google Colab and create a new notebook.
  2. Inside that notebook, add a text cell and give it a title. It could be something as simple as "My First Python Notebook".
  3. Close the notebook.
  4. See if you can find it again in your Google Drive.

That's all for now. In the next lesson, you will open that notebook and write your first few lines of Python.