Welcome!: Python - Writing The First Python Code!
Welcome!: Python - Writing The First Python Code!
Welcome!
By the end of this notebook, you will have learned the basics of Python, including writing some basic
commands, understanding object types, and some simple operations!
Table of Contents
In [ ]:
A statement or expression is an instruction the computer will run or execute. Perhaps the simplest program you
can write is to print a statement in Python.
**Tip**: To *execute* the Python code in the grey code cell below, **click on it and press Shift + Enter**.
In [ ]:
After executing the cell above, you should see that Python return the string, Hello World! .
**Tip:** **`print()`** is the **function** that you **executed**, and you *passed in* an **argument** of `'Hello
World!'`.
Python 3
How do we know that Python 3 is running? Take a look in the top-right hand corner of this notebook. You should
see "Python 3"!
In addition to writing code, note that it is customary to comment your code to help describe what it does. Not
only does this help other people understand your code, it can also serve as a reminder to you of what your
code does. (This is especially true when you write some code and then come back to it weeks or months later.)
To write comments in your Python code, use the hash symbol (#) before writing your comment. When you run
the code Python will ignore everything after the # in that line.
In [ ]:
Great! After executing the cell above, you should notice that "this is my comment did not appeared in the
output, because it was a comment (and thus ignored by Python). The second line was also not executed
because print('Hi') was preceded by a hash symbol (#) as well!
Errors in Python
Before continuing, it's important to note when things go wrong in Python, and we cause errors.
There are many kinds of errors, and you do not need to memorize the various types of errors. Instead,
what's most important is know what the error messages mean.
For example, if you spell print as frint, you will get an error message.
In [ ]:
frint("Hello World!")
The error message tells you (1) where the error occurred, and (2) what kind of error it was. Here, Python
attempted to run the function frint , but could not determine what frint -- since it is undefined.
Does Python know the error in the script before you run it?
No, Python is naive! Python will try to run the code line-by-line, and it will stop if it runs into an error.
In [ ]:
Using the print() function, print out the phrase: "hello world"
In [ ]:
Print out the phrase: "Hello World" and comment it with the phrase "printing Hello World" all in one line
of code
In [ ]:
We can have many different object types in Python, let's start with strings, integers and floats.
Anytime you write words (text) in Python, you're using character strings (strings for short). Numbers, on the
other hand, depend: numbers can be integers (like -1, 0, 100) or floats, which are real numbers (like 3.14,
-42.0).
The following chart summarizes three data types for the last examples, the first column indicates the expression
the second column indicates the data type
In [ ]:
11 #integer
In [ ]:
2.14 #float
In [ ]:
We can see the actual data type in python by using the type() command
In [4]:
type(11)
Out[4]:
int
In [5]:
type(2.14)
Out[5]:
float
In [6]:
Out[6]:
str
In [ ]:
Integers
In [ ]:
type(-1)
In [ ]:
type(4)
In [ ]:
type(0)
Floats
Floats are real numbers; they include the integers but also "numbers in-between the integers". Consider the
numbers between 0 and 1 we can select numbers in-between them, these numbers are floats.
Similarly, consider the numbers between 0.5 and 0.6. We can select numbers in-between them, these are floats
as well. We can continue the process, zooming in for different numbers, of course, there is a limit, but it is quite
small.
We can verify some of the above examples using the type command:
In [ ]:
type(1.0)
In [ ]:
type(0.5)
In [ ]:
type(0.56)
You can change the type of the object in Python; this is called typecasting.
Out[3]:
str
Converting to float:
In [7]:
float(2)
Out[7]:
2.0
In [8]:
type(float(2))
Out[8]:
float
Converting to integer:
Nothing really changes. If you cast a float to an integer, you must be careful. For example, if you cast the float
1.1 to 1 but we will lose some information :
In [9]:
int(1.1)
Out[9]:
In [ ]:
type('1')
In [ ]:
int('1')
You can also convert strings containing float values into float objects
In [ ]:
float('1.2')
However, if we attempt to convert a string that contains a non-numerical value, we get an error:
In [ ]:
int("A")
Converting to strings:
In [ ]:
str(1)
In [ ]:
str(1.2)
Boolean
Boolean is another important type in Python; a Boolean can take on two values. The first value is true, just
remember we use an uppercase T:
In [ ]:
True
In [ ]:
False
Using the type command on a Boolean value we obtain the term bool, this is short for Boolean
In [ ]:
type(True)
In [ ]:
type(False)
If we cast a Boolean true to an integer or float we will get a 1, if we cast a Boolean false to an integer or float. If
we get a zero if you cast a 1 to a boolean, you get a true similarly, if you cast a 0 to a Boolean you get a false.
In [ ]:
int(True)
In [ ]:
bool(1)
In [ ]:
bool(0)
In [ ]:
float(True)
Quiz on types
In [ ]:
type(6/2)
What is the type of the result of: 6 // 2 ? (Note the double slash //)
In [ ]:
14//5
Expressions
Expressions are operations that Python performs. For example, basic arithmetic operations like adding multiple
numbers.
In [ ]:
43 + 60 + 16 + 41
We can perform operations such as subtraction using the subtraction sign. In this case the result is a negative
number.
In [ ]:
50 - 60
In [ ]:
5 * 5
In [ ]:
25 / 5
In [10]:
25 / 6
Out[10]:
4.166666666666667
We can use the double slash for integer division, where the result is rounded
In [11]:
25//5
Out[11]:
In [12]:
d = 25//6
d
Out[12]:
In [ ]:
Python follows mathematical conventions when performing mathematical expressions. The following operations
are in different order. In both cases Python performs multiplication, then addition to obtain the final result.
In [ ]:
2 * 60 + 30
The expressions in the parentheses are performed first. We then multiply the result by 60, the result is 1920.
In [ ]:
(30 + 2) * 60
[Tip] Summary
Variables
We can also store our output in variables, so we can use them later on. For example:
In [ ]:
x = 43 + 60 + 16 + 41
In [ ]:
We can also perform operations on x and save the result to a new variable:
In [ ]:
y = x / 60
y
In [ ]:
x = x / 60
x
It's good practice to use meaningful variable names, so you don't have to keep track of what variable is what:
In [ ]:
total_min = (43 + 42 )
total_min
In [ ]:
total_hr = total_min / 60
total_hr
You can put this all into a single expression, but remember to use round brackets to add together the album
lengths first, before dividing by 60.
In [ ]:
As you just learned, you can use **variables** to store values for repeated use. Here are some more
**characteristics of variables in Python**:
variables store the output of a block of code
variables are typically assigned using **=** (as in **x = 1**)
In [ ]:
In [ ]:
In [ ]:
Your notebook saves automatically every two minutes. You can manually save by going to File > Save
and Checkpoint. You can come back to this notebook anytime by clicking this notebook under the
"Recent Notebooks" list on the right-hand side.
Did you know there are other notebook options? Click on the > symbol to the left of the notebook: