Lesson 1 Basics
The objective of this lesson is for you to get up and running with python. You will learn how to use the Google Colaboratory environment to write your python code and some basic coding principles.
- Working in Google Colab
- Coding in notebooks
- Using python as a calculator
- Basic “built in” functions
- Documentation and getting help
- Exercise 1.1
- Exercise 1.2
- Assignment 1
1.1 Working in Google Colab
Google Colab is interactive computing environment that enables users to author notebook documents that include:
- Live code
- Interactive widgets
- Narrative text
You can access your interactive python coding environment to create ipython notebooks at: https://colab.research.google.com/
Sign in using your NYU email as a login (e.g., firstname.lastname@example.org, not your Stern email) and use your NYU password to log in.
Once you sign in to Google Colab, you should be able to see a web page that looks like Figure 1.2.
1.2 Coding in notebooks
In Google Colab, select NEW PYTHON 3 NOTEBOOK from the bottom of the Recent Notebooks screen to create a new ipython notebook. Notebooks are a way to program using python code. Think of a notebook as a simple text document that you can include python code and regular text. The python code you will write will serve as a set of instructions for the computer (i.e. Google Colab) to execute, see Figure 1.3.
Saving your ipython notebook
Rename your notebook to save it. Change the title from Untitled to Lesson01.ipynb by double clicking the notebook title, see Figure 1.4.
Editing your ipython notebook
Begin editing your notebook by adding your name. Select the + Text option from the toolbar. Then add your name to the notebook, see Figure 1.5.
Next, add a little
python code. To do this, use the + Code option on the toolbar to add a code cell below your name.
Type the following:
print("I'm using python to print text.")
Then, press the
Run button. It looks a play button next to the code cell. This will execute the code that you just wrote, see Figure 1.7.
The code above is actual python code. You used a
print() to display a
string of text to the screen. The
input was the code above and the output is:
I'm using python to print text to the screen.
You’ll be writing all your code in code cells within a notebook. For the first lesson, we will write one or two lines of code in each cell. These code chunks will allow us to cleasrly distinguish between the input and the output.
Type in the following code in a new code cell and run it.
print(I'm using python to print text to the screen.)
Did you notice that an error message was
returned as the output?
SyntaxError: EOL while scanning string literal
This is called a
syntax error. Syntax is the group of rules of a programming language. These rules are very important in order for the computer to know what you are trying to tell it using a language it can understand. These error messages are useful to catch our mistakes. Clearly, we forgot to put double quotes around
I'm using python to print text to the screen.
EOL while scanning string literal is one of most common syntax errors.
Another common syntax error is called
invalid syntax or
NameError. This error is shown usually when you misspell a function, such as
print(). Let’s try to create a syntax error.
prnt("This will cause a syntax error.")
prnt caused this error:
NameError: name 'prnt' is not defined
1.3 Using python as a calculator
We will use python just as we would a calculator. That is, we will use numbers and operators to perform calculations. The numbers and operators are the input and the result is the output. Python understands mathematical operations such as addition (
+), subtraction (
-), multiplication (
*), and division(
/). The symbols used by python to perform these operators are call operators. With these operators, we can use python as a calculator.
For example, if we wanted to add two numbers together we would simply type:
3 + 3 as our input and the result (i.e. the output) is
It’s easy to simply type in simple python expressions in a new cell in your notebook. For example, type 3+3 in a new code cell.
It’s important to note that incomplete expressions such as
3+ will return an error as shown below.
You can certainly include more than one line of code within a code cell. However, you will only see the result of the last line within the cell.
3+3 9-2 993-42
In the example above, we used the
+ operator to add two numbers together. This is called an arithmetic operator. There are many arithmetic operators used in python. The first five operators in Table 1.1 are used very frequently in python and throughout this course.
|Operation||Operator||Example Input||Example Output|
|Modulus (remainder for integer division)||
Table 1.1 Arithmetic Operators in Python
Order of operations
When writing Python expressions, it is usually best to indicate the order of operations by using parentheses.
If parentheses are not used in an expression, the computer will perform the operations in an order determined by the precedence rules.
Precedence rules (PEMDAS)
Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want. Since expressions in parentheses are evaluated first,
2 * (3-1) is
8. You can also use parentheses to make an expression easier to read, as in
(minute * 100) / 60, even if it doesn’t change the result. > - Exponentiation has the next highest precedence, so
27. > - Multiplication and Division have the same precedence, which is higher than Addition and Subtraction, which also have the same precedence. So
Let’s try using some of these operators to help us solve simple problems.
- What would be the total balance in the account at the end of the first month on your savings of
$25,000with a monthly interest rate is
This involves using multiplication and addition.
25000 * .0199 + 25000
- Compute the hourly rate for an employee who works 40 hours per week at a monthly (4 weeks) salary of 21,400.
21400/(40 * 4)
We can use parentheses in python to specify the order of operations to ensure 21,400 is divided by the product of 40 * 4.
1.5 Basic built in functions
A built in function is a block of code that we can’t see from the python library. It only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result. There are many built-in functions in python, see the Table 1.2 below.
Basic python functions
|Print to the screen||
|Round a number to a specified number of decimal places||
Table 1.2 Basic python functions
Let’s try out these functions
The absolute value of a real number x is the non-negative value of x without regard to its sign function. For example, absolute value of -33 is 33.
In python we write the absolute value |-33| as
For a given sequence of numbers, you can find the maximum value. You can enter in a number sequence, separated by commas in between the parentheses of the
max(2,3,4,5,6) # this sequence is called a tuple
You can also enter (or pass in) a sequence of numbers using the square brackets
[ ]. This creates different type of data. More on that in lesson 2.
max([2,3,4,5,6]) # this sequence is called a list
min() function works similar to the max() function, except that the smallest value is returned.
Passing in a tuple
min(2,3,-4,5,6) # this sequence is called a tuple
Passing in a list
min([2,3,-4,5,6]) # this sequence is called a list
We’ve used the
print() function to display text to the screen. Text is always passed into the
print() as a string or
str. The string in enclose in double quotes as shown below. We will learn more about strings in lesson 2.
print("Printing a string to the screen.")
Printing a string to the screen.
In addition to printing strings, you can show the output of your computations to the screen. For example you can pass in 2+2. Here double quotes are not used. This is because we are adding numbers together, not printing text to the screen. The result of 4 will be returned.
You can see the print function prints the output of computations and strings. To print both the string and the computation in a single
print() statement, you would separate each by a comma.
print("The result is:", 2+2)
The result is: 4
You can round a number to specified number of decimal places using the
round() function. In the example below, 4333.4222 is rounded to 2 decimal places. The first parameter is the number you wish to round and the second parameter is the number decimal places you want to round the first parameter.
It’s important to understand the parameters a function takes so you can code it properly. For example:
This produces a
TypeError with the following explanation:
round() takes at most 2 arguments (3 given).
You can find the full list of built-in functions at: https://docs.python.org/3.7/library/functions.html
1.6 Documentation and getting help
Comments are used to document your code in python and all programming languages. It is best practice to include comments in your code. This ensures that if someone else tries to read your code they can interpret it. This is also to help you interpret your code when you return to it days, weeks or months later.
The comment character, # tells python to ignore everything written to the right of the #. We use the # for each line we would use for commenting our code. In jupyter notebooks the color of the text will change to indicate that you are writing a comment. In the example below, the commented text is in a different color from the code.
This is a single line comment:
Note the input and the output.
print("Adding a single-line comment to our code")
Adding a single-line comment to our code
abs(-33) #this function computes the absolute value of -33
You can also add many lines of “commented text” to your code using a triple set of double quotes around the text.
This is a multi-line comment:
print("Adding a multi-line comment to our code")
Adding a multi-line comment to our code
"""This code is used to print a message of your choice. Notice that this message that is included in the triple double quotes will not execute."""
'This code is used to print a message of your choice. Notice that this message that is included in the triple double quotes will not execute.'
Getting help and understand python’s semantics, syntax, Google Colab, and Jupyter ipython notebooks
There are several important resources you should familiarize yourself with:
- The python language reference https://docs.python.org/3/reference/index.html#reference-index
This reference manual describes the syntax and “core semantics” of the language. It is terse, but attempts to be exact and complete. The semantics of non-essential built-in object types and of the built-in functions and modules are described in The Python Standard Library.
- The python standard library https://docs.python.org/3/library/index.html#library-index
This library reference manual describes the standard library that is distributed with Python. It also describes some of the optional components that are commonly included in Python distributions.
- help() function
The python help function is used to display the documentation of modules, functions, classes, keywords etc. If the help function is passed without an argument, then the interactive help utility starts up.
For example, if you wanted help about the
This will show the documentation related to how the print statement works.
Google Colaboratory https://colab.research.google.com/
Jupyter ipython notebooks
You can learn more about getting help when using Jupyter notebooks at: https://problemsolvingwithpython.com/04-Jupyter-Notebooks/04.07-Getting-Help-in-a-Jupyter-Notebook/
- Google Colaboratory is the space where you can plan and test your python programs
- ipython notebooks are a convenient medium for writing python code. Notebooks are saved as .ipynb files. The notebook type used in Google Colab are jupyter notebooks.
- You can begin coding in python by using it as a calculator.
- Basic arithmetic operators in python include
- There are many pre-loaded functions available to act on python objects and manipulate data. Some examples include
- Comments are used to write text in English to document your work. There are two types of comments single line (preceded by the
#) and multi-line comments (text is enclosed by triple quotes
- What’s wrong with this code?
Provide an explanation and show the corrected code.
- Display the following text to the screen:
Hello. Welcome to my python program.
- Three MBA students purchased a different asset yesterday at the below listed price. Each sold their asset today at the listed selling price.
Calculate the percent return for each student rounded to two decimal points.
Calculate the maximum of the LIST of returns
Divide 72 by 5 and find both the integer and the remainder
How would you code the minimum of prime numbers 0-10?
You go to the store with $15 to buy pears, each pear is a $1.35, how many pears can you buy? (You cannot buy partial pears so round your results).
Create a notebook that answers the following questions. Include your name, date, and be sure to document your code using comments.
- New York City sales tax on goods and services is 8.875%. Compute the total bill (including sales tax) for the following goods. Round to two decimal places.
- 1 Macbook pro - $1,299
- 1 Magic mouse - $79.00
- Case of copy paper - $24.99
Hint: Order of operations, + and - operators, round() function
- Print out the the result from item 1 in a nicely formatted sentence to the user.
Hint: print() function, round() function