Programming Workshop for Beginners

Day 0: First steps

Friday, Jun 22, 2018

University of Waterloo

Welcome!

  • Today: Get to know each other, make sure the software works, what is programming, first programming steps (Ivana)
  • Tomorrow: Fundamental coding concepts, interactive exercises, hands-on project (Ryan)
  • Sunday: Applied programming (processing data, plotting, working with files) (Jasmine, Ivana)

Who are we?

  • We are all current or former UW students!
    • Instructors: Ivana, Ryan, Jasmine
    • Mentors: Sean, Sajed, Mariah
  • We did this before:
    • January 2016 (345 apps)
    • November 2016 (270 apps)
    • November 2017 (189 apps)
  • Free food and refreshments:

Who are you?

Drawing

Drawing

Some of your majors: Biotech, Pharmacy, Biochemistry, Chemistry, Psychology, Public Health/Health Studies, Biology, Kinesiology, Life Physics, Geography, Environment/Environmental Management, Business, English, Hydrogeology

Why Python?

  • Because we need a programming language: Python is beginner-friendly

  • Widely used in industry and academia

  • It's free and there are plenty of free learning resources online

However:

  • We focus on teaching transferable knowledge/programming foundations

  • If everyone in your group is using Matlab/R/xyz, then it's probably better to use Matlab/R/xyz

Admin

  • All materials are online: https://github.com/uwpyb/materials/
    • and so are these slides: http://goo.gl/N5Q025
  • Mailing list: python-workshop@lists.uwaterloo.ca
  • Interactive lecture
  • Red and green sticky notes

Agenda for today

  • Test everything works

  • Familiarize ourselves with the programming workflow

    • Using the command line, creating and running a script
  • First programming steps

    • Displaying messages, different data types, variables
    • In-class exercises

Programming

  • Telling your computer what do to!

    • Natural language:

      • "If there is any mango ice cream in the store, please get it for me"
    • Programming language:

In [ ]:
if my_location=="grocery store" and ("mango" in icecream_selection):
    buy(ice_cream)

Computers are dumb

Computers are dumb

  • Need to be precise when telling them what to do (e.g., Mango is different from mango)
  • Sensitive to (sometimes invisible) changes:
    • mango
    • mango
  • Good at doing the same thing over and over again...

First steps

Saying "hi"

In [1]:
print("Good evening!")
Good evening!

If you don't see this message or things look broken, put up a red sticky note.

Python as a calculator

In [2]:
10+5
Out[2]:
15
In [3]:
10/20
Out[3]:
0.5
In [4]:
10.5-(2+3)
Out[4]:
5.5

What will happen if we type:

In [ ]:
1/0.

a) 0

b) Python will crash and we will have to start it again

c) We will get an error

Hints and solutions to problems are available below (down arrow key)

In [7]:
1/0.
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-7-45dd8a1a4700> in <module>()
----> 1 1/0.

ZeroDivisionError: float division by zero

Adding things together

This worked:

In [8]:
2+4
Out[8]:
6

What is the result of adding together text and numbers?

In [ ]:
"Good evening" + 5

More on data types later!

Displaying messages on the screen

  • Use the print() command
In [9]:
print("Good evening everyone!")
Good evening everyone!
In [10]:
print("Good evening " + "at 8 pm!")
Good evening at 8 pm!

It is common to make mistakes when typing...

In [11]:
print("Hmmm)
  File "<ipython-input-11-0324a32cf4e8>", line 1
    print("Hmmm)
                ^
SyntaxError: EOL while scanning string literal
In [12]:
print("Hmmm"))
  File "<ipython-input-12-2ba79029f2b4>", line 1
    print("Hmmm"))
                 ^
SyntaxError: invalid syntax

Syntax Error: Python tells us we did not respect the rules of the language

Creating a Python script

  • Script: a file containing commands written in Python language
    • e.g. hello.py
  • Let us create our first Python script!

Task: Create your first script!

  1. Create a folder called workshop on your Desktop
  2. Open Code editor and write the two following lines in the editor:
    print("Good evening everyone!")
    print("Good evening at 8pm!")
    
  3. Save that file as hello.py in the workshop folder
  4. Put up a green sticky note if you see hello.py in the workshop folder, or a red one if you don't see anything or only see hello (without .py)

Now we have to tell Python to locate hello.py and to run it.

For that, we need to understand how our computer organizes files and folders...

Address metaphor

Demo: explore addressing on a computer

  • Find the address of the workshop directory

    • e.g., C:\Users\ivana\Desktop\workshop
  • Find the address of the hello.py script

    • e.g., C:\Users\ivana\Desktop\workshop\hello.py

2 ways of navigating through the content of your disk:

  • Clicking: moving around by clicking on icons in Graphical User Inteface (GUI)
    • This is what we normally do
  • Typing: giving navigation commands in the command line (CMD)
    • Going to learn!

Navigation by typing

  • pwd: print working directory
  • ls: list files in the current directory
  • cd: change directory

In IPython/Qtconsole:

In [13]:
pwd
Out[13]:
'/home/ivana/teaching/uw-programming-ws/lectures'
In [14]:
cd
/home/ivana
In [15]:
cd Desktop
/home/ivana/Desktop
In [16]:
cd workshop
/home/ivana/Desktop/workshop
In [17]:
ls
hello.py

Note: We can use cd on its own, or with a directory name (such as cd workshop). The former takes us home, the latter takes us where we specify

Running a script

1. Run pwd to check where you are. It should end with workshop:

In [18]:
pwd
Out[18]:
'/home/ivana/Desktop/workshop'

2. Check that there is a script called hello.py:

In [19]:
ls
hello.py

3. Run the script:

In [20]:
run hello.py
Good evening everyone!
Good evening at 8pm!

Task 1

Modify hello.py to to say good evening at the current time!

After you made the modifications, save the changes and run the script again by typing: run hello.py in IPython/Qtconsole.

Task 2

In the workshop directory on your Desktop, create a new script called missing.py. Inside that script type the following lines (feel free to edit them so they say something different):

"Away above the chimney tops."
"That's where you'll find me"
100
# print("Will you ever find me?")
  1. Run the script with run missing.py.

  2. Is the output what you expected it to be?

  3. Change the program so that first three lines are displayed when you run the program.

Note: difference between typing pure text in a script and in Ipython

Learned so far:

  • Python commands:
    • math commands
    • print: tell Python to display stuff on the screen
  • Other commands:
    • pwd: print working directory
    • cd: change directory
    • ls: list files
    • run: run the script

Data Types

Data Types

We could not add text and numbers, as those are two different data types:

In [21]:
type("Hello!")
Out[21]:
str
In [22]:
type(1)
Out[22]:
int
In [23]:
type(1.1)
Out[23]:
float

What is the output of:

In [ ]:
type("-2.0")

a) int

b) str

c) float

What is the output of:

In [ ]:
print("Hello" + 123)

a) Error

b) Hello123

c) Hello 123

Don't mix apples and oranges!

Useful hint:

We can cast integers into strings (and sometimes strings into integers) in the following way:

In [26]:
str(4)
Out[26]:
'4'
In [27]:
int("4")
Out[27]:
4

Question: What happens if you try to convert the string 'abc' into an integer?

What would we change in this line:

print("Hello" + 4)

to make it print Hello4 instead of an error?

a) print(int("Hello")+4)

b) print(str("Hello")+4)

c) print("Hello"+str(4))

More power: variables

Variables let us save values and manipulate them

In [28]:
box = 3
print(box)
3
In [29]:
bigger_box = 100 + box * 2
print(bigger_box)
106
In [30]:
print(bigger_box - 6)
100
In [31]:
box = "kittens"
print(box)
kittens
In [32]:
print(box + box + box)
kittenskittenskittens

Question

If I run the following code, what will be the final value of b?

a = 1
b = a * 5
a = 2

a) 5

b) 1

c) 10

Variables can change

In [33]:
a = 0
print(a)
a = a + 1
print(a)
0
1

Notice: In programming a = a + 1 is different than a = a + 1 in math. In programming, this means take the value of a and increase it by one. In math, this would be an equation with one unknown, and it wouldn't make any sense since we would get 0=1. In programming, we talk about variable assignment, and in math about equality.

Quiz

What is the following print statement going to print?

In [ ]:
x = 0
y = x

x = x + 1
print("The value of x is " + str(x))
print("The value of y is " + str(y))

IPython hint: whos

In [34]:
whos
Variable     Type    Data/Info
------------------------------
a            int     1
bigger_box   int     106
box          str     kittens

Working with strings

In [6]:
animal = "123 snAKes"
print(animal)
123 snAKes

We can access inidividual characters, but we start counting at 0:

In [7]:
animal[0]
Out[7]:
'1'

That number is also called an index. To access multiple characters we use a range of indices:

In [8]:
animal[2:9]
Out[8]:
'3 snAKe'

Use -1 to get the last character:

In [9]:
animal[-1]
Out[9]:
's'

More slicing

To start from the beginning up to some character, we can drop 0:

In [39]:
animal[:8] # equivalent to animal[0:8]
Out[39]:
'123 snAK'

Similarly, to get a substring starting at some character, until the end:

In [40]:
animal[8:] # equivalent to animal[8:10]
Out[40]:
'es'

Length of a string

To find out how many characters we have:

In [38]:
len(animal)
Out[38]:
10

Notice that len is used with brackets (), similar to print. This is because both len and print are functions

Complicated panda

In [ ]:
fname = "Panda"
lname = "Spotty-Dotty"

len_fname = len(fname)
print(lname[len_fname:len_fname+3])

a) Spo

b) pot

c) y-D

(Possibly) confusing

What would you expect output to be for the following line:

print("AaAa" * 5)

a) AaAa5

b) AaAaAaAaAaAaAaAaAaAa

c) Error

We can print cool headers

In [41]:
print("-"*20)
print("<"*6 + " Hello! " + ">"*6)
print("-"*20)
--------------------
<<<<<< Hello! >>>>>>
--------------------

Make sure stuff works for later...

Type in following lines in IPython:

In [42]:
import numpy as np
import matplotlib.pyplot as plt

Green sticky note: Nothing happened

Red sticky note: Python is shouting at me with some errors

Exercises

Link to the exercises:

https://github.com/uwpyb/materials/blob/master/lectures/Day_0_Exercises.ipynb

Done!

  • Coffee will be here at 9:30am tomorrow. The lecture starts at 10:00am (at noon break for lunch)
  • Before you leave, write on your sticky notes:
    • Green : a programming concept/something from today's lecture you understood well (i.e., you could explain this to someone)
    • Red: something that was difficult to understand

Attributions

Frontpage graphics, "First Steps" graphics: Vector Graphics by www.vecteezy.com