2 - 2 # two minus two
0
In this lesson, you will learn the basics of using Python.
To get started, open your preferred Python environment (e.g., Jupyter Notebook, VS Code, or PyCharm), and create a new Python file or notebook.
Next, save the file with a name like “coding_basics.py” or “coding_basics.ipynb” depending on your environment.
You should now type all the code from this lesson into that file.
As you have already seen, Python works as a calculator in standard ways.
Below are some other examples of basic arithmetic operations:
2 - 2 # two minus two
0
2 * 2 # two times two
4
2 / 2 # two divided by two
1.0
2 ** 2 # two raised to the power of two
4
There are a few other operators you may come across. For example, %
is the modulo operator, which returns the remainder of the division.
10 % 3 # ten modulo three
1
//
is the floor division operator, which divides then rounds down to the nearest whole number.
10 // 3 # ten floor division three
3
Guess the result of the following code chunks then run them to check your answer:
5 % 4
5 // 4
Python obeys the standard PEMDAS order of operations (Parentheses, Exponents, Multiplication, Division, Addition, Subtraction).
For example, multiplication is evaluated before addition, so below the result is 6
.
2 + 2 * 2
6
Which, if any, of the following code chunks will evaluate to 10
?
2 + 2 * 4
6 + 2 ** 2
We can also use the math
library to do more complex mathematical operations. For example, we can use the math.sqrt
function to calculate the square root of a number.
import math
100) # square root math.sqrt(
10.0
Or we can use the math.log
function to calculate the natural logarithm of a number.
import math
100) # logarithm math.log(
4.605170185988092
math.sqrt
and math.log
are examples of Python functions, where an argument (e.g., 100
) is passed to the function to perform a calculation.
We will learn more about functions later.
Function: A reusable block of code that performs a specific task. Functions often take inputs (called arguments) and return outputs.
Using the math
library, calculate the square root of 81.
Write your code below and run it to check your answers:
# Your code here
Consider the following code, which generates a random number between 1 and 10:
import random
1, 10) random.randint(
9
In that code, identify the library, the function, and the argument(s) to the function.
Good spacing makes your code easier to read. In Python, two simple spacing practices can greatly improve your code’s readability: using blank lines and adding spaces around operators.
Python uses indentation to indicate the start and end of loops, functions, and other blocks of code. We’ll look at this more in later lessons.
For now, one thing to watch out for is to avoid accidentally including a space before your code
For example, consider the following code chunk:
import math
# Get the square root of 100
100) math.sqrt(
Trying to run this code will cause an error:
IndentationError: unexpected indent
This is due to the space before the math.sqrt
function. We can fix this by removing the space.
import math
# Get the square root of 100
100) math.sqrt(
Use blank lines to separate different parts of your code.
For example, consider the following code chunk:
# Set up numbers
= 5
x = 10
y # Perform calculation
= x + y
result # Display result
print(result)
15
We can add blank lines to separate the different parts of the code:
# Set up numbers
= 5
x = 10
y
# Perform calculation
= x + y
result
# Display result
print(result)
15
Blank lines help organize your code into logical sections, similar to paragraphs in writing.
Adding spaces around mathematical operators improves readability:
# Hard to read
=5+3*2
x
# Easy to read
= 5 + 3 * 2 x
When listing items, add a space after each comma:
# Hard to read
print(1,2,3)
# Easy to read
print(1, 2, 3)
This practice follows the convention in written English, where we put a space after a comma. It makes lists of items in your code easier to read.
As you have seen, to store a value for future use in Python, we assign it to a variable with the assignment operator, =
.
= 2 + 2 # assign the result of `2 + 2 ` to the variable called `my_var`
my_var print(my_var) # print my_var
4
Now that you’ve created the variable my_var
, Python knows about it and will keep track of it during this Python session.
You can open your environment to see what variables you have created. This looks different depending on your IDE.
So what exactly is a variable? Think of it as a named container that can hold a value. When you run the code below:
= 20 my_var
you are telling Python, “store the number 20 in a variable named ‘my_var’”.
Once the code is run, we would say, in Python terms, that “the value of variable my_var
is 20”.
Try to come up with a similar sentence for this code chunk:
= "Joanna" first_name
After we run this code, we would say, in Python terms, that “the value of the first_name
variable is Joanna”.
A text value like “Joanna” is called a string, while a number like 20 is called an integer. If the number has a decimal point, it is called a float, which is short for “floating-point number”.
Below are these three types of variables:
# string variable
= "Joanna"
first_name
# integer variable
= 5
age
# float variable
= 1.4 height
You can check the type of a variable using the type()
function.
print(type(first_name))
print(type(age))
print(type(height))
<class 'str'>
<class 'int'>
<class 'float'>
Variable: A named container that can hold a value. In Python, variables can store different types of data, including numbers, strings, and more complex objects.
Reassigning a variable is like changing the contents of a container.
For example, previously we ran this code to store the value “Joanna” inside the first_name
variable:
= "Joanna" first_name
To change this to a different value, simply run a new assignment statement with a new value:
= "Luigi" first_name
You can print the variable to observe the change:
first_name
'Luigi'
Most of your time in Python will be spent manipulating variables. Let’s see some quick examples.
You can run simple commands on variables. For example, below we store the value 100
in a variable and then take the square root of the variable:
import math
= 100
my_number math.sqrt(my_number)
10.0
Python “sees” my_number
as the number 100, and so is able to evaluate its square root.
You can also combine existing variables to create new variables. For example, type out the code below to add my_number
to itself, and store the result in a new variable called my_sum
:
= my_number + my_number
my_sum my_sum
200
What should be the value of my_sum
? First take a guess, then check it by printing it.
Python also allows us to concatenate strings with the +
operator. For example, we can concatenate the first_name
and last_name
variables to create a new variable called full_name
:
= "Joanna"
first_name = "Luigi"
last_name = first_name + " " + last_name
full_name full_name
'Joanna Luigi'
Consider the code below. What is the value of the answer
variable? Think about it, then run the code to check your answer.
= 9
eight = eight - 8
answer answer
Though it’s not used often in data analysis, the input()
function from Python is a cool Python feature that you should know about. It allows you to get input from the user.
Here’s a simple example. We can request user input and store it in a variable called name
.
= input() name
And then we can print a greeting to the user.
print("Hello,", name)
We can also include a question for the input prompt:
= input('What is your name? ')
name print("Hello,", name)
Let’s see another example. We’ll tell the user how many letters are in their name.
= input('What is your name? ')
name print("There are", len(name), "letters in your name")
For instance, if you run this code and enter “Kene”, you might see:
What is your name? Kene
There are 4 letters in your name
Write a short program that asks the user for their favorite color and then prints a message saying “xx color is my favorite color too!”, where xx is the color they entered. Test your program by running it and entering a color.
One of the most common errors you’ll encounter when working with variables in Python is the NameError
. This occurs when you try to use a variable that hasn’t been defined yet. For example:
= 48 # define `my_number`
my_number + 2 # attempt to add 2 to `my_number` My_number
If you run this code, you’ll get an error message like this:
NameError: name 'My_number' is not defined
Here, Python returns an error message because we haven’t created (or defined) the variable My_number
yet. Recall that Python is case-sensitive; we defined my_number
but tried to use My_number
.
To fix this, make sure you’re using the correct variable name:
= 48
my_number + 2 # This will work and return 50 my_number
50
Always double-check your variable names to avoid this error. Remember, in Python, my_number
, My_number
, and MY_NUMBER
are all different variables.
When you first start learning Python, dealing with errors can be frustrating. They’re often difficult to understand.
But it’s important to get used to reading and understanding errors, because you’ll get them a lot through your coding career.
Later, we will show you how to use Large Language Models (LLMs) like ChatGPT to debug errors.
At the start though, it’s good to try to spot and fix errors yourself.
The code below returns an error. Why? (Look carefully)
= "Kene"
my_1st_name = "Nwosu"
my_last_name
print(my_Ist_name, my_last_name)
Hint: look at the variable names. Are they consistent?
There are only two hard things in Computer Science: cache invalidation and naming things.
— Phil Karlton.
Because much of your work in Python involves interacting with variables you have created, picking intelligent names for these variables is important.
Naming variables is difficult because names should be both short (so that you can type them quickly) and informative (so that you can easily remember what the variable contains), and these two goals are often in conflict.
So names that are too long, like the one below, are bad because they take forever to type.
sample_of_the_ebola_outbreak_dataset_from_sierra_leone_in_2014
And a name like data
is bad because it is not informative; the name does not give a good idea of what the variable contains.
As you write more Python code, you will learn how to write short and informative names.
For names with multiple words, there are a few conventions for how to separate the words:
= "Snake case uses underscores"
snake_case = "Camel case capitalizes new words (but not the first word)"
camelCase = "Pascal case capitalizes all words including the first" PascalCase
We recommend snake_case, which uses all lower-case words, and separates words with _
.
Note too that there are some limitations on variable names:
2014_data
is not a valid name (because it starts with a number). Try running the code chunk below to see what error you get.2014_data = "This is not a valid name"
_
). So ebola-data
or ebola~data
or ebola data
with a space are not valid names.-data = "This is not a valid name" ebola
~data = "This is not a valid name" ebola
While we recommend snake_case for variable names in Python, you might see other conventions like camelCase or PascalCase, especially when working with code from other languages or certain Python libraries. It’s important to be consistent within your own code and follow the conventions of any project or team you’re working with.
Which of the following variable names are valid in Python? Try to determine this without running the code, then check your answers by attempting to run each line.
Then fix the invalid variable names.
1st_name = "John"
= "Doe"
last_name -name = "John Doe"
full= 30
age_in_years @job = "Developer"
current= "555-1234"
PhoneNumber = 42 _secret_code
In this lesson, we’ve covered the fundamental building blocks of Python programming:
#
for single-line and triple quotes for multi-line comments.input()
function to get input from the user.These concepts form the foundation of Python programming. As you continue your journey, you’ll build upon these basics to create more complex and powerful programs. Remember, practice is key to mastering these concepts!
3.3 Comments
Comments are text that is ignored by Python. They are used to explain what the code is doing.
You use the symbol
#
, pronounced “hash” or “pound”, to start a comment. Anything after the#
on the same line is ignored. For example:If we just tried to write
Addition
above the code, it would cause an error:We can put the comment on the same line as the code, but it needs to come after the code.
To write multiple lines of comments, you can either add more
#
symbols:Or you can use triple quotes
'''
or"""
:Or:
Comment: A piece of text in your code that is ignored by Python. Comments are used to explain what the code is doing and are meant for human readers.
3.4 Practice Q: Commenting in Python
Which of the following code chunks are valid ways to comment code in Python?
Check your answer by trying to run each code chunk.