Course Module • Jillur Quddus
2. Quick Introduction to Python
Python Taster Course
Python Taster Course
Jillur Quddus • Founder & Chief Data Scientist • 1st November 2022
Back to Course Overview
Introduction
In this module we will study the fundamental building blocks of the Python programming language, namely:
- Basic Data Types and Variables - strings/text, numbers and booleans.
- Basic Operators - arithmetic and comparison operators.
- Basic Control Flow - if statement.
- Basic Functions - print function and user-defined functions.
The source code for this module may be found in the public GitHub repository for this course. Where code snippets are provided in this module, you are strongly encouraged to type and execute these Python statements in your own Google Colaboratory/Jupyter notebook instance.
1. Getting Started
1.1. Desktop-based IDEs
To start writing Python code, as a bare minimum one could use any text-editor of their choice such as Notepad or Notepad++. However it is normally more convenient and efficient to use an Integrated Development Environment (IDE). An IDE is an application that provides you with a place in which to write code, and also comes bundled with a wide range of useful features such as code autocompletion and automatic error checking. There are numerous IDEs available for Python, some open-source and some commercial, including but not limited to:
1.2. Web-based Notebooks
In addition to desktop-based IDEs, notebooks are web-based applications that allow you to write and execute snippets of code and visualise the outputs immediately, all contained within your internet browser. As such, they are a great tool for beginners learning a new programming language for the first time. Example web-based notebooks include:
There also exist cloud-hosted services that provide web-based notebooks meaning that no local installation of 3rd party software is required. The benefits of these cloud-based services include zero configuration, installation and setup, free access to GPUs, and easy sharing and collaboration of notebooks between developers. However these cloud-based services only provide limited resources in their free tiers (typically between 512MB and 1GB of RAM), and do not guarantee uptime, performance nor security. Examples of free and cloud-hosted services that provide web-based notebooks supporting Python include:
- Google Colab (requires a Google account as notebooks are saved to Google Drive)
- My Binder
1.3. Google Colaboratory
As described above, Google Colaboratory (Colab) is one example of a cloud-hosted service that provides web-based notebooks supporting Python. For the purposes of this taster module, we shall use Google Colab to write and execute Python code all via our internet browser.
1.3.1. Software Requirements
As we are using Google Colab in this taster module, this means that no 3rd party software is required to be installed on your local desktop or laptop computer in order to follow this module. All that is required is:
- An internet browser (Google Chrome is recommended) and a stable internet connection.
- A Google account (free).
1.3.2. Creating a Notebook
To create a new notebook in Google Colab, please follow the steps below:
- Open your internet browser and sign into your Google account.
- Navigate to (and bookmark) Google Colab at https://colab.research.google.com.
- Select "Google Drive" from the popup modal.
- Select "New notebook".
Selecting "New notebook" will automatically create a new notebook in the root of your Google Drive in a folder called "Colab Notebooks". By default, this new notebook will be called "Untitled0.ipynb". If you wish to go back to this notebook at any time after closing your internet browser tab or window, you can do so either via Google Colab or by double-clicking this .ipynb file in your Google Drive.
Assuming that you have followed steps 1 - 4 above successfully, you will be presented with a web interface as illustrated below.
1.3.3. A Quick Tour
The most commonly-used features of the Google Colab notebook web interface are described below, cross-referenced using the numbers in the image in section 1.3.2 above.
Please explore the Google Colab notebook web interface further to familiarise yourself with its full suite of features.
- Notebook File Name - click to rename your notebook. By default, notebooks are named "Untitled.ipynb". For the purpose of this taster module, please rename your notebook to "Quick Introduction to Python.ipynb".
- Cell - in Google Colab, Python code is written in cells. To execute a code cell, select the code cell that you wish to run and simply press the "play" button directly to the left of that cell. If the Python code in that cell prints an output, then that output will be displayed directly underneath the cell in question.
- New Code Cell - to add a new code cell to your notebook, simply press the "+ Code" button in the toolbar. This will create and insert a new code cell directly under the currently selected cell.
- Manage Cells - to move a cell up or down, select the cell that you wish to move and then press the up or down arrow in the cell toolbar. To delete a cell, select the cell that you wish to delete and then press the delete cell button (denoted by the bin icon) in the cell toolbar.
- Save - to save your notebook, select the "File" option from the main menu and press "Save". Alternatively you can press CTRL+S on your keyboard.
2. Basic Data Types
We are now ready to start learning the basics of Python! The first concept we shall learn is that of basic data types. Modern programming languages provide us with the ability to represent and manipulate different types of data. The three most basic data types are strings, numbers and booleans which we shall introduce and explore in the following subsections.
2.1. Strings
In computer programming, a string is a sequence of characters. A string is used to represent text in computer programs. To get started with strings, please enter the following three lines of code into a single code cell in your Google Colab notebook, and then run the cell.
# String / text
my_first_string = 'Hello world!'
print(my_first_string)
Let's study the code above line-by-line:
- Line 1 - any line of code that starts with the hash
#
character denotes a comment in Python. Comments in computer programming are a means to describe what your code is doing and to highlight anything of particular significance to other developers who may be studying your code. Comments are ignored by Python for the purposes of executing your code. - Line 2 - in this line, we define a new Python variable and assign it a string value. A variable in Python is simply a name that references a value, similar to when you study algebra at school and write something like
x = 1
. In that case, the name of the variable isx
and it is assigned the numeric value of1
. In the example above, we created a new Python variable calledmy_first_string
and assigned it the string valueHello world!
. To define a string in Python, we enclose the text within either single quotes'
or double quotes"
. - Line 3 - in this line, we print the value that is referenced by our
my_first_string
Python variable to the screen, using Python's in-builtprint()
function. Assuming that your code cell executes successfully, you should see the textHello world!
printed to the screen.
To learn more about strings in Python, please refer to the Control and Evaluations Part 1 module of our Introduction to Python course. And to learn about advanced string operations in Python, please refer to the Data Aggregates Part 1 module.
2.2. Numbers
Representing numbers in Python is even easier than strings. You simply define the name of the Python variable and assign it a numerical value, as follows:
# Numbers
my_first_number = 10
my_second_number = 3.14159
In the example above, we defined a new Python variable named my_first_number
and assigned it the integer (whole number) value of 10
. We then defined another Python variable named my_second_number
and assigned it the decimal number of 3.14159
. In this case, because we did not use the print()
function, nothing gets printed to the screen when we run the code cell.
To learn more about numbers in Python, please refer to the Control and Evaluations Part 1 module of our Introduction to Python course.
2.3. Booleans
When we develop computer programs, we often want our programs to execute a specific set of one or more actions based on whether certain conditions are met or not. In other words, we want our programs to automatically respond to changes to its environment. For example if we were developing a driverless car, we would want the car to stop if the traffic light is red. In this case, the condition that we want to test is to ascertain whether the traffic light is red or not. If the traffic light is red, we can state that the condition is evaluated as true, otherwise the condition is evaluated as false.
In computer programming, booleans are data types that can only have two values - True
(representing the value of 1, meaning true or on) or False
(representing the value of 0, meaning false or off). Booleans are used to represent the evaluation of one or more conditions. Using our traffic light example, we may wish to define a boolean Python variable named is_traffic_light_red
. If the traffic light is red, then is_traffic_light_red = True
, otherwise is_traffic_light_red = False
. Our driverless car can then use this boolean variable to determine and execute a course of action - in this case, we would naturally want our driverless car to stop. A couple more examples of booleans are provided in the following code snippet.
# Booleans
my_first_boolean = True
my_second_boolean = False
In the example above, we defined a new Python variable named my_first_boolean
and assigned it the boolean value of True
(in Python, the value of true always starts with an uppercase letter). Then we defined another Python variable named my_second_boolean
and assigned it the boolean value of False
(in Python, the value of false also always starts with an uppercase letter).
To learn more about booleans in Python, please refer to the Control and Evaluations Part 1 module of our Introduction to Python course.
2.4. Naming Rules
In Python, the following rules must be adhered to when choosing names for your variables:
- Variable names can only include letters, numbers and the underscore
_
character. - Variable names cannot start with a number.
2.5. Naming Conventions
There also exist conventions which, though they do not need to be adhered to strictly unlike rules, are highly recommended to follow when choosing names for your variables:
- Variable names should be all lowercase (variable names are case-sensitive in Python).
- Different words in variable names should be separated by the underscore
_
character. - Variable names should be short and meaningful.
Provided below are some example variable names that are compliant with both the naming rules and conventions.
# Examples of compliant and good variable names
first_name = 'Jillur'
last_name = 'Quddus'
age = 30
male = True
print(f'{first_name} {last_name} is {age} years old.')
2.6. Python Memory
To finish this subsection, we will very briefly discuss how Python manages variables. Python is an in-memory language, meaning that variables and the values they reference are stored in the computer's memory. Python does this by communicating with the machine's operating system to manage its space in memory. Fortunately as a beginner Python programmer, you do not have to worry about memory management as it is managed on your behalf.
3. Basic Operators
In section 2 above, we studied how to represent basic data types in Python. In this section we shall study how to operate upon these values. In computer programming, operators are used to perform operations on variables and values. Two of the most basic groups of operators are arithmetic operators and comparison operators which we shall introduce and explore in the following subsections.
3.1. Arithmetic Operators
Arithmetic operators perform common mathematical operations on numerical values. Arithmetic operators include (but are not limited to) the addition +
, subtraction -
, multiplication *
and division /
operators as demonstrated below.
# Arithmetic operators upon values
print(3 + 7)
print(10 - 6)
print(2 * 3)
print(10 / 2)
In the example above, arithmetic operators are operating upon numerical values. All operators can also operate upon Python variables as follows.
# Arithmetic operators upon variables
x = 2
y = 10
z = x * y
print(z)
To learn more about arithmetic operators in Python, please refer to the Control and Evaluations Part 1 module of our Introduction to Python course.
3.2. Comparison Operators
Comparison operators compare two values, with a boolean value being returned. The comparison operators are the equal to ==
, not equal to !=
, greater than >
, less than <
, greater than or equal to >=
and less than or equal to <=
operators as demonstrated below.
# Comparison operators
print(10 == 100)
print(15 != 20)
print(2 > 10)
print(10 < 100)
print(10 >= 10)
print(20 <= 19)
To learn more about comparison operators in Python, please refer to the Control and Evaluations Part 1 module of our Introduction to Python course.
4. Basic Control Flow
In computer programming, control flow is the order in which the computer executes statements and instructions. In this section we shall study conditional statements - a means by which control flow is regulated.
4.1. Conditional Statements
Conditional statements allow our computer programs to perform different sets of one or more actions dependent on the evaluation of one or more conditions. We can develop conditional statements by combining the if
statement with the comparison operators that we studied in section 3.2. above. To get started with if
statements, please enter the following lines of code into a single code cell in your Google Colab notebook, and then run the cell.
# If statement
age = 30
if age >= 18:
print("You are allowed to vote in UK elections.")
Let's study the code above line-by-line:
- Line 1 - a simple comment.
- Line 2 - in this line, we define a variable named
age
and we assign it the numerical value of30
. - Line 3 - in this line, we introduce the
if
statement for the very first time. We are testing the condition of whether the value referenced by ourage
variable is greater than or equal>=
to the value of18
. If statements start with the keywordif
followed by one or more conditions that we wish to test using comparison operators. Theif
statement always ends with the colon:
character to indicate that a conditional set of actions is about to follow. - Line 4 - this line represents the block of code that will be executed if the
if
statement evaluates toTrue
. In our case, this line will be executed if the value referenced by ourage
variable is greater than or equal to18
. The block of code to be executed if theif
statement evaluates toTrue
must be indented, that is preceded by a standard and consistent number of spaces (usually two spaces). If we want our computer program to execute more than one line of code if theif
statement evaluates toTrue
(i.e. conditionally execute multiple actions), then they must share the same minimum indentation level - this is how Python knows what constitutes a single logical block of code in control flow.
If you run the code above, you will see that
You are allowed to vote in UK elections
is printed to the screen. Re-run the cell with different values assigned to theage
variable and see what happens.
We can extend the if
statement with the else
keyword. By introducing else
, we can regulate control flow even further and instruct our computer program to execute a block of code in the event that the condition evaluates to False
. Let us extend our example above as follows.
# If-else statements
age = 30
if age >= 18:
print("You are allowed to vote in UK elections.")
else:
print("You are NOT allowed to vote in UK elections.")
Let's study the new lines of code above line-by-line:
- Line 5 - in this line, we introduce the
else
keyword. If theif
statement evaluates toFalse
, then the block of code immediately before theelse
keyword is ignored, and the block of code immediately following theelse
keyword is executed. Note that theelse
keyword is also followed by the colon:
character to indicate that another conditional set of actions is about to follow. - Line 6 - this line represents the block of code that will be executed if the
if
statement evaluates toFalse
. As before, the block of code must be indented and if there are multiple lines of code to be conditionally executed as part of a single logical block, then those lines must share the same minimum indentation level.
To learn more about conditional statements in Python, please refer to the Control and Evaluations Part 2 module of our Introduction to Python course.
5. Basic Functions
In computer programming, functions are (relatively) small blocks of reusable code that are designed to perform a single and specific task. The code inside a function is only executed when that function is called. Functions are useful in that they allow you to avoid writing the same code over and over again. A function has three parts - inputs, a body, and outputs. A function may receive zero or more inputs. It then runs the block of code defined in its body which may use the inputs that the function has received. The function may then return zero or more outputs. In the following subsections we explore an in-built function provided by Python before then studying how developers can define their own custom functions.
5.1. Print Function
As we have already seen in this taster module, the in-built Python print()
function simply prints the given value to the screen (or other standard output device). Given an input (such as a string or a number), the body of the print()
function will covert the input into a string. It will then print that string to the screen, as demonstrated in the following example.
# Print function
name = 'Jillur Quddus'
print(name)
In the example above, the input given to the print()
function is the variable named name
. The print()
function then simply prints the value assigned to this variable to the screen. In this case, because the value is already a string then there is no need to perform any conversion.
To learn more about the Python
print()
function, please refer to the Control and Evaluations Part 2 module of our Introduction to Python course.
5.2. Custom Function
Python also provides us with the ability to develop our own custom functions. To get started with custom functions, please enter the following lines of code into a single code cell in your Google Colab notebook, and then run the cell.
# Defining your own functions
def add(x, y):
sum = x + y
return sum
Let's study the code above line-by-line:
- Line 1 - a simple comment.
- Line 2 - to define a custom function in Python, we use the
def
keyword followed by the name of our custom function. Similar to variable names, function names should only include letters, numbers and the underscore_
character. By convention function names should be all lowercase, with words separated by the underscore_
character, and short, concise & meaningful. In our case, our custom function is calledadd
. The function name is important, as we will use the function name to call our function later on. Following the function name are round parentheses( )
. Inside these round parentheses are the zero or more input parameters that the function may expect to receive when the function is called. In our case, ouradd
function expects to be called with two input parameter values - these input parameter values will be assigned to the Python variablesx
andy
which exist only within the scope of the function meaning that they can only be used in the function body. Finally the colon:
character is used to indicate the end of this line, and denote that the block of code immediately following the colon character is the function body itself. Thedef
keyword followed by the function name, the parameters and the colon character are together referred to as the function header or function signature. - Lines 3 and 4 - these lines represents the block of code that defines the function body. Recall when we studied the
if
statement that all the lines in a single logical block of code must share the same minimum indentation level. In our case, our function body first applies the addition operator to add the values referenced byx
andy
together. The result is assigned to a variable namedsum
. Finally in line 4, our function body uses thereturn
keyword to return the value referenced bysum
back to the part of our Python program that called the function.
As you will have deduced, our simple custom function simply adds together two given numbers. You will also notice that, when you run the cell containing our custom function, nothing is output to the screen. When we run a cell containing a custom function definition, assuming that there are no syntax errors, then Python will save the custom function in memory so that it is ready to be called later on whenever we need it. To run the function, enter the following lines of code into a new code cell in your Google Colab notebook, and then run that cell.
# Running your own functions
add(10, 20)
To run a function, you simply call that function by its name whilst supplying the expected input parameters. In our example we call the add
function and pass the input parameters 10
and 20
respectively. Our custom function then assigns the value of 10
to the variable x
and the value of 20
to the variable y
. The function body then adds these two values together, and returns the sum back to our main Python program where we called our custom function. Thus the value of 30
is printed to the screen as we would expect.
To learn more about functions in Python, please refer to the Functions and Modules Part 1 module of our Introduction to Python course.
Summary
In this taster module we have studied the fundamental building blocks of the Python programming language. We now have the ability to represent text and numbers in a Python computer program, along with the ability to operate upon these values using operators. Finally, we have the ability to regulate the order in which our Python computer program executes instructions and manage how it responds to its environment using conditional statements, and can break up our program into small reusable blocks of codes called functions.
Homework
- Familiarise yourself with the Google Colab notebook web interface including testing all its various options and features.
- Once you feel comfortable with the Google Colab notebook web interface, write a Python function that, given the height and base measurements of a triangle, will return the area of that triangle.
- Extend your Python function so that it prints an error message if either the height or base measurements are negative numbers.
What's Next
In the next module we shall build a robot car in preparation for it to be programmed using Python so that it may follow simple and advanced instructions!