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 jupyterhub environment to write your python code and some basic coding principles.

Outline

  • Getting started with jupyterhub
  • Creating an ipython notebook
  • Using python as a calculator
  • Arithmetic operators
  • Basic functions
  • Code documentation and getting help

1.1 Getting started with jupyterhub

JupyterHub 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 called jupyterhub at: https://jupyterhub.stern.nyu.edu

Log in using your NYU id as a login (e.g., abc123, not your email) and use your NYU password to log in. You need to be within the NYU network to connect; if you are not within the NYU network, you need to connect to the NYU network first, using the NYU Virtual Private Network (VPN). For details, refer to this article: https://www.nyu.edu/life/information-technology/getting-started/network-and-connectivity/vpn.html

Once you login to jupyterhub, you should be able to see a web page that looks like the figure below.

1.2 Creating an ipython notebook

In jupyterhub go to New > python3 to create a new ipython notebook. Save the notebook as lesson01. Notebooks are a way to program using python code. The python code you will write will serve as a set of instructions for the computer (i.e. jupyterhub) to execute.

Saving your ipython notebook

Think of a notebook as a simple text document that you can include python code and regular text.

Begin by renaming your notebook to save it. Simply change the title from Untitled to lesson01 by double clicking the notebook title.

Editing your ipython notebook

Begin by adding a title and your name. Go to the insert menu > Insert Heading Above.

Rename the heading to Python Basics. Type your name in regular text below the heading.

Next, add a little python code. To do this, simply type in the cell below your heading on the line with In [ ]:

Type the following:

print("I'm using python to print text.")

Then, press the Run button. This will execute the code that you just wrote.

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. We’ll by writing one line of code in each cell. These code chunks will allow us to clearly 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.")

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 is written to understand 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 6.

It’s easy to simply type in simple python statements 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 statements 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 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. Arithmetic Operators in Python

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)
[1] 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 functions

A function is a block of code which 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 below.

Basic python functions

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

Let’s try out these functions

1.5.1 abs()

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 abs(-33).

abs(-33) 
33

1.5.2 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 paratheses 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 different type of data. More on that in lesson 2.

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

1.5.3 min()

The 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
-4

Passing in a list

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

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

print(2+2) 
4

You can see the print functionprints 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

1.5.5 round()

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.

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

You can find the full list of built-in functions at: https://docs.python.org/3.7/library/functions.html#input

1.6 Code 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 jupyterhub 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 blue.

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")

"""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."""
Adding a multi-line comment to our code

Getting help and understand python’s semantics and syntax

There are three important resources you should familarize 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 of 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.

You can learn more about getting help when using JupyterHub notebooks at: https://problemsolvingwithpython.com/04-Jupyter-Notebooks/04.07-Getting-Help-in-a-Jupyter-Notebook/

1.7 Summary

  • Jupyterhub 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.
  • You can begin coding in python by using it as a calcuator.
  • 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 multiline comments (text is enclosed by triple quotes """...""")

1.8 Quiz

1. Which of the following is not an arithmetic operator?

  1. *
  2. **
  3. -
  4. =
  5. +

2. What is print() in python?

  1. a function
  2. a class
  3. an object
  4. a string
  5. an operator

3. To write a comment in python, which character would you use?

  1. #
  2. ##
  3. /
  4. //
  5. /**

4. Which of the following would result in a syntax error?

  1. 3*5
  2. print("Hello)
  3. print("I'm printing text in python")
  4. max(1,1)
  5. round(22.1)

5. What error would be returned by the following statement? round(150.434321, 2')

  1. NameError
  2. EOL while scanning string literal
  3. Invalid syntax
  4. No error would be returned

6. What error would be returned by the following statement: round(150.4d34321)

  1. NameError
  2. EOL while scanning string literal
  3. Invalid syntax
  4. No error would be returned

7. Price per square foot is the metric used to compare real estate properties in the US. How would you compute price per square foot in python?

  • Selling price = $999,999.00
  • Square footage = 1050 square feet
  1. 999,999 / 1050
  2. 999999 / 1050
  3. 999999 * 1050
  4. (999,999 * 1050)
  5. 1050 / 999999

8. How would you round 23,499.9009093 to 2 decimal places?

  1. round(23,499.9009093, 2)
  2. round(23499.9009093, 2)
  3. round(23499.9009093, 0)
  4. (23,499.9009093, 0)

9. What symbol or set of symbols would you use to include this multi-line comment in your code:

The purpose of this program is to ask the user to indicate their preferences for a restaurant reservation app. Specifically, dietary, seating, and smoking preferences.

a)#The purpose of this program is to ask the user to indicate their preferences for a restaurant reservation app. Specifically, dietary, seating, and smoking preferences.#

b)#The purpose of this program is to ask the user to indicate their preferences for a restaurant reservation app. Specifically, dietary, seating, and smoking preferences.

c)//The purpose of this program is to ask the user to indicate their preferences for a restaurant reservation app. Specifically, dietary, seating, and smoking preferences.

d)"""The purpose of this program is to ask the user to indicate their preferences for a restaurant reservation app. Specifically, dietary, seating, and smoking preferences."""

e)"The purpose of this program is to ask the user to indicate their preferences for a restaurant reservation app. Specifically, dietary, seating, and smoking preferences."

  1. True or False

The following statement returns a value of 7.

max(2,3) + 4

1.9 Exercises

1.9.1 Exercise 1.1

1. What’s wrong with this code? Provide an explanation and show the corrected code.

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

2. Display the following text to the screen

Hello. Welcome to my python program.

1.9.2 Exercise 1.2

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

Student buy sell
Jen $25.50 $40.20
Jacobi $103.30 $125.00
Mark $86.02 $91.41

2. Calculate the maximum of the LIST of returns

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

Answer: 72//5 and 72%5

4. How would you code the minimum of prime numbers 0-10?

Answer: min(1,3,5,7)

5. 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)

Answer: round(15/1.35, 0)

1.9.3 Exercise 1.2

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.

Jen buy $25.50 sell $40.20

answer: round((((40.20/25.50)-1)*100),2)=57.65%

Jacobi buy $103.30 sell $125.00
answer: round((((125/103.3)-1)*100),2)=21.01%

Mark buy $86.02 sell $91.41

answer: round((((91.41/86.02)-1)*100),2)=6.27%

Calculate the maximum of the LIST of returns

Answer: max([57.65,21.01,6.27])

1.10 Assignment 1

Create a notebook that answers the following questions. Include your name, date, and be sure to document your code using comments.

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

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

Hint: print() function, round() function

1.11 Exam questions

1. What is incorrect with the below code?

Prnt('what error will display?')

  1. nothing this is correct

  2. you cannot use single quotes in Python you must use double

  3. logical error: prnt() is lowercase

  4. syntax error: the correct function is print()

2. Find c2 given image.png Pythagoreans Theorem calculation:

c2 = a2 + b2 a=5 b=9

  1. (5**2)+(9**2)
  2. (5^2)+(9^2)
  3. (5^*2)+(9^*2)
  4. (5%2)+(9%2)

3. After graduating NYU you land your dream job making $200,000 per year. Unfortunately you still live in the city. Therefore your Federal, State and City taxes amount to 38%. Calculate your monthly after-tax income.

  1. round(((200,000*(1-.38))//12),2)

  2. round(((200,000*(1-.38))/12),2)

  3. round((((200,000)(1-.38))/12),2)

  4. round((((200,000)(1-.38))%12),2)