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.

Outline

  • Working in Google Colab
  • Coding in notebooks
  • Using python as a calculator
  • Operators
  • Basic “built-in” functions
  • Documentation and getting help
  • Summary
  • 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
  • Plots
  • Narrative text
  • Equations
  • Images
  • Video

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., , not your Stern email) and use your NYU password to log in.

Google Colab - Landing Page

Figure 1.1: Google Colab - Landing Page

Once you sign in to Google Colab, you should be able to see a web page that looks like Figure 1.2.

Google Colab - Recent Notebooks Page

Figure 1.2: Google Colab - Recent Notebooks Page

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.

Creating a new notebook

Figure 1.3: Creating a new notebook

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.

Saving and naming your notebook

Figure 1.4: Saving and naming your notebook

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.

Adding a text cell to a python notebook

Figure 1.5: Adding a text cell to a python notebook

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.")
Adding a code cell to a python notebook

Figure 1.6: Adding a code cell to a python notebook

Then, press the Run button. It looks like a play button next to the code cell. This will execute the code that you just wrote, see Figure 1.7.

Running code chunks

Figure 1.7: Running code chunks

The code above is actual python code. You used a function named 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 clearly distinguish between the input and the output.

  • To learn more about formatting your notebooks refer to the tutorial by Prabhu (2020).

  • Refer to the template by Sosulski (2020) for all exercises and assignments.

Type in the following code in a new code cell and run it.

print(I'm using python to print text to the screen.)
Running code chunks

Figure 1.8: Running code chunks

Did you notice that an error message was returned as the output?

SyntaxError: EOL while scanning string literal

This is called a syntax error. The syntax is the group of rules of a programming language. These rules are very important 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. 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 the 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.")
Running code chunks

Figure 1.9: Running code chunks

Misspelling the print function as 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 called 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 6.

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.

3+3
6

It’s important to note that incomplete expressions such as 3+ will return an error as shown below.

3+

invalid syntax

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.

Input

3+3
9-2
993-42

Output

951

1.4 Operators

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
Addition + 100 + 2 102
Subtraction - 93 - 3 90
Multiplication * 10 * 10 100
Division / 100 / 5 20
Integer Division // 65 // 10 6
Power ** 8**2 64
Modulus (remainder for integer division) % 65 % 10 5

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 4, and (1+1)**(5-2) is 8. You can also use parentheses to make an expression easier to read, as in (minute * 100) / 60, even if it does not change the result.
  • Exponentiation has the next highest precedence, so 2**1+1 is 3, not 4, and 3*1**3 is 3, not 27.
  • Multiplication and Division have the same precedence, which is higher than
  • Addition and Subtraction, which also have the same precedence. So 2*3-1 is 5, not 4, and 6+4/2 is 8, not 5.

Let’s try using some of these operators to help us solve simple problems.

  1. What would be the total balance in the account at the end of the first month on your savings of $25,000 with a monthly interest rate is 1.99%?

This involves using multiplication and addition.

25000 * .0199 + 25000
25497.5
  1. 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)
133.75

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 Table 1.2 below.

Basic python functions

Function Description Example Input Answer (ouput)
abs( ) Absolute Value abs(-21) 21
max() Maximum value max(1,2,3,4,5) 5
min() Minimum value min(1,2,3,4,5) 1
print() Print to the screen print("Hello World!") Hello World!
round( ) Round a number to a specified number of decimal places round(3.432,2)

Table 1.2 Basic python functions

Let’s try out these functions

###abs()

The absolute value of a real number x is the non-negative value of x without regard to its sign function. For example, the absolute value of -33 is 33.

In python, we write the absolute value |-33| as abs(-33).

abs(-33) 
33

###max()

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() function.

max(2,3,4,5,6) # this sequence is called a tuple
6

You can also enter (or pass in) a sequence of numbers using the square brackets [ ]. This creates a different type of data. More on that in lesson 2.

max([2,3,4,5,6]) # this sequence is called a list
6

###min()

The min() function works similarly 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
-4

Passing in a list

min([2,3,-4,5,6]) # this sequence is called a list
-4

###print()

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 is enclosed 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.

Printing expressions and strings

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.

print(2+2) 
4

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, there are two options.

Option #1: Separate the string and the expression by a comma. Be sure that the string is enclosed in double quotes and the expression is not.

print("The result is:", 2+2) 
The result is: 4

Question: If you enclose the expression in double quotes, what would happen?

print("The result is:", 2+2) 
The result is: 4

Answer: As illustrated above, the entire string plus the expression would be printed as a string. Therefore the expression would never be evaluated.

Option #2: Use f-string formatting. Put an f in front of the string. Include the expression as part of the string, but enclose the expression in curly brackets. The f-strings are known as Formatted string literals and may contain replacement fields, which are expressions delimited by curly braces {}.

print(f"The result is: {2+2}") 
The result is: 4

Additional parameters

If you go to the documentation and research the print function at https://docs.python.org/3.10/library/functions.html#print, you’ll learn that there are optional parameters such as sep and end. You’ll see a function definition that reads:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Let’s look at the sep and end parameters further.

The sep parameter

Based on the function definition, the sep character is used to separate two objects. Specific to the last example, the sep parameter defines what character will separate the string and the expression. The default value, meaning you do not have to specify it, is a space. This is denoted by sep=' ' in the function definition.

For example, you notice the output from the code below has a space between

print("The result is:",2+2) 
The result is: 4

If we didn’t want a space we would be explicit about redefining the default parameter to sep='.

print("The result is:",2+2, sep="")#no space 
The result is:4
print("The result is:",2+2, sep="  ")#two spaces 
The result is:  4
print("The result is:",2+2, sep="-")#a dash
The result is:-4

How does sep work with f-strings?

When expressions are included within an f-string, the sep does not have any impact on what is shown.

print(f"The result is:{2+2}", sep=":") #no colon
The result is:4

If you include the expression separately, following the closing quote, which is then followed by a comma, and includes the expression, it will function as expected.

print(f"The result is",2+2, sep=":") #the colon is shown
The result is:4

The end parameter

The end parameter will specify the character(s) that should be displayed at the end of the string. This is the very last character that is displayed. The default is a newline (or carriage return). A new line is denoted by \n. As a reminder, you can see the default values for parameters of a function in the function definition as shown below:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

print("The result is:",2+2) #defaults to a newline \n
The result is: 4
print("The result is:",2+2, end=".") #ends with a comma, not a newline
The result is: 4.

Printing special escape characters

There are times when you will want to print quotations, newline (or return), backslashes, tabs, and other special characters. However, these same characters are important to the syntax of the code. The class of these characters is called escape characters.

See the table below. Try them out!

Code Result
\n Newline
\t Horizontal tab
\' Single quote
\" Double quote
\\ Backslash

###round()

You can round a number to a 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 of decimal places you want to round the first parameter.

round(4333.4222, 2) 
4333.42

It’s important to understand the parameters a function takes so you can code it properly. For example:

round(4333.4222, 2,1) 

This produces a TypeError with the following explanation:

round() takes at most 2 arguments (3 given).

Note: The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions cannot be represented exactly as a float, which is a data type in python.

For a more technical explaination refer to the documentation: https://docs.python.org/3.10/tutorial/floatingpoint.html#tut-fp-issues

This concludes our section on functions.

You can find the full list of built-in functions at: https://docs.python.org/3.10/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 on our code. In ipython 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
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 understanding python’s semantics, syntax, Google Colab, and Jupyter ipython notebooks

There are several important resources you should familiarize yourself with:

  1. 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 the built-in functions and modules are described in The Python Standard Library.

  1. 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.

  1. 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 print statement. Simple type:

help("print")

This will show the documentation related to how the print statement works.

  1. Google Colaboratory https://colab.research.google.com/

  2. 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/

1.7 Summary

  • 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 is Jupyter notebooks.
  • You can begin coding in python by using it as a calculator.
  • Basic arithmetic operators in python include +, -, *, /, %, //, and **.
  • There are many pre-loaded functions available to act on python objects and manipulate data. Some examples include abs(), max(), min(), print(), and round()
  • 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 """...""")

Exercise 1.1

  1. What’s wrong with this code?

Explain and show the corrected code.

min[(2,3,-4,5,6)]

  1. Display the following text to the screen using python:

Hello. Welcome to my python program.

  1. Investigate the bool, chr, len, pow, sum, type, and ord functions.

Begin by going to the Python documentation on functions: https://docs.python.org/3.10/library/functions.html and reviewing the function definitions for bool, chr, len, pow, sum, type, and ord. Don’t worry if the descriptions and definitions seem confusing. Just try to read through each one.

Then, use each function to return an appropriate value (not an error) and explain the results. Do this within the print function. For example, for bool() you would apply the function and explain the results in the following way:

print(f"a.  The bool function returns True or False of a given value. \n    For example, bool(0) returns the value of: {bool(0)} and bool(100) returns a value of {bool(100)}.\n")
a.  The bool function returns True or False of a given value. 
    For example, bool(0) returns the value of: False and bool(100) returns a value of True.

Complete items a through g.

  1. bool()
  2. chr()
  3. len()
  4. pow()
  5. sum()
  6. type()
  7. ord()

Exercise 1.2

  1. Three MBA students purchased a different asset yesterday at the price listed below. Each sold their asset today at the listed selling price.

Calculate the percent return for each student rounded to two decimal points.

Student buy sell
Reema $25.50 $40.20
Jacobi $103.30 $125.00
Manuel $86.02 $91.41
  1. Calculate the maximum of the LIST of returns.

  2. Divide 72 by 5 and find both the integer and the remainder.

  3. You go to the store with $15 to buy pears, each pear is $1.35, how many pears can you buy? (You cannot buy partial pears so round your results).

Assignment 1

Create a Google Colab Jupyter notebook. Use the code and text fields to format your notebook. Use text fields to format your name, assignment number, date, and to add question numbers before your solutions. Then, use the code fields to write the code that answers the specific questions. Be sure to document your code using the # for comments.

  1. 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

  1. Print out the result from question 1 in a nicely formatted sentence to the user.

Hint: print() function, round() function

  1. If you wanted to learn more about how to use the print() function, what function would you use to obtain the documentation? Show how you would use it?

  2. For each of the following example Python expressions, specify the output. Where output may be unexpected, explain how python interpreted the expression.

  1. 3+3
  2. 9999 % 4
  3. 2,000 - 23
  4. "3" * 90
  5. max(10,2,3,2,44,32)

References

Prabhu, Tanu N. 2020. “Cheat-Sheet for Google Colab.” https://towardsdatascience.com/cheat-sheet-for-google-colab-63853778c093.
Sosulski, Kristen. 2020. “Template for Google Colaboratory Notebooks.” https://colab.research.google.com/drive/1RYdTqgpNOOvczLtZofvJjjElJwogmsKQ?usp=sharing.