Top Banner
A Gentle Introduction to Programming (with Python) Tariq Rashid, July-August 2015
128

A Gentle Introduction to Coding ... with Python

Apr 14, 2017

Download

Technology

Tariq Rashid
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: A Gentle Introduction to Coding ... with Python

A Gentle Introduction to Programming

(with Python)Tariq Rashid, July-August 2015

Page 2: A Gentle Introduction to Coding ... with Python

Ambition

Very Gentle Introductionto coding and Python, zero expertise assumed

Confidenceto explore further,

understand suppliers and techies

Page 3: A Gentle Introduction to Coding ... with Python

The Journey

The “1s and 0s”

languagestech overview

“Hello World!” working with data

repetitive work reusable blocks

graphics

using libraries

data science?

digitalservices?

Page 4: A Gentle Introduction to Coding ... with Python

Deep Inside Tech is .... Numbers

Computers do stuff with numbers:

add, multiply, subtract, divide, shift, chop, invert, ….

That’s it!There is no other magic.

Page 5: A Gentle Introduction to Coding ... with Python

It’s all numbers ...

Networks

Page 6: A Gentle Introduction to Coding ... with Python

It’s all numbers ...

Desktops

Applications

Page 7: A Gentle Introduction to Coding ... with Python

It’s all numbers ...

Smartphone Apps

Android / iOS

Page 8: A Gentle Introduction to Coding ... with Python

It’s all numbers ...

Digital Movies

Digital Music

Page 9: A Gentle Introduction to Coding ... with Python

It’s all numbers ...

Digital Web Services

Page 10: A Gentle Introduction to Coding ... with Python

The 1s and 0s

This is a computer …. (kinda)

on / offswitch lightbulb

battery

Page 11: A Gentle Introduction to Coding ... with Python

The 1s and 0s

on / offswitch lightbulb

battery

input output

Page 12: A Gentle Introduction to Coding ... with Python

The 1s and 0s

This one is a bit more useful.

on / offswitches

lightbulb

battery

0

0

0

Page 13: A Gentle Introduction to Coding ... with Python

The 1s and 0s

on / offswitches

lightbulb

battery

1

0

0

Page 14: A Gentle Introduction to Coding ... with Python

The 1s and 0s

on / offswitches

lightbulb

battery

1

1

1

Page 15: A Gentle Introduction to Coding ... with Python

The 1s and 0s

on / offswitches

lightbulb

battery

Computation:Only when both inputs are on

Turn on the output light

1

1

1

Page 16: A Gentle Introduction to Coding ... with Python

The 1s and 0s

on / offswitches

lightbulb

battery

Computation:Only when both inputs are on

Turn on the output light

1

1

1

Recipe:

IF

temperature is low

AND it’s after 8pm

THEN

Turn on the heating

Page 17: A Gentle Introduction to Coding ... with Python

Programming

Programming

Is Telling Computers What to Do

... and How …

“Recipes”

Page 18: A Gentle Introduction to Coding ... with Python

Ye Olde Programming!

… those wires again!

Page 19: A Gentle Introduction to Coding ... with Python

Modern Programming!

… live demo!

Page 20: A Gentle Introduction to Coding ... with Python

Loads of Programming Languages!

different tools for different jobs

Page 21: A Gentle Introduction to Coding ... with Python

Popular Languages 2014

…. Go Python!

Page 22: A Gentle Introduction to Coding ... with Python

Enough Theory!

Let’s code!

( fire up your Python )

Page 23: A Gentle Introduction to Coding ... with Python

Traditional First Program

Hello World!

Page 24: A Gentle Introduction to Coding ... with Python

Let’s Decode Some Python ...

print ( “Hello World!” )

Page 25: A Gentle Introduction to Coding ... with Python

IPython … Python in a Browser

Page 26: A Gentle Introduction to Coding ... with Python

IPython

Python instructions

… and the result!

Play button

“Execute my command with extreme prejudice”

awaiting your next instruction

Page 27: A Gentle Introduction to Coding ... with Python

Can you print out other words?

Have a Play!

Page 28: A Gentle Introduction to Coding ... with Python

What About Simple Arithmetic?

2 times 3

… is 6

the star * symbol means “multiply” in many programming languages

Page 29: A Gentle Introduction to Coding ... with Python

Have a Play Again!

Can you do other kinds of arithmetic?

What does this code do? Why?print ( “3 * 4” )

Page 30: A Gentle Introduction to Coding ... with Python

Well Done!

You're now coding!

Dennis Ritchie, CKen Thompson, UNIXRichard Stallman, Tech Freedom

Page 31: A Gentle Introduction to Coding ... with Python

World’s First Programmer!

Ada Lovelace, World’s First Programmer

Page 32: A Gentle Introduction to Coding ... with Python

Next Time ...

Working with more data - with variables, arrays, ...

Automating lots of work - with loops, iterators, ...

Page 33: A Gentle Introduction to Coding ... with Python

Welcome back to Part 2!

Working with more data - with variables, arrays, ...

Automating lots of work - with loops, iterators, ...

Page 34: A Gentle Introduction to Coding ... with Python

Data Nitty Gritty

3

Page 35: A Gentle Introduction to Coding ... with Python

Data Nitty Gritty

3

memory

data

Page 36: A Gentle Introduction to Coding ... with Python

Variable - the name of a storage box

3a

variable name

Page 37: A Gentle Introduction to Coding ... with Python

Variable - the name of a storage box

3a

variable names

5b

Page 38: A Gentle Introduction to Coding ... with Python

Just like school maths

3a

In maths we write:

a = 3

Page 39: A Gentle Introduction to Coding ... with Python

Data Nitty Gritty

3a

In Python we also write:

a = 3

… try it!

Page 40: A Gentle Introduction to Coding ... with Python

Python Variables

code starting with the hash symbol # are ignored

we can use them as comments

shortcut!

Page 41: A Gentle Introduction to Coding ... with Python

Changing Data is Useful

animation is … changing data

Page 42: A Gentle Introduction to Coding ... with Python

Changing Data

3a

7

replace the 3 with a 7

Page 43: A Gentle Introduction to Coding ... with Python

Changing Data

7a

the box name stays the same

… where did the 3 go?

Page 44: A Gentle Introduction to Coding ... with Python

Changing Data - Try it!

before ... a is 3

after ... a is 7

Page 45: A Gentle Introduction to Coding ... with Python

Arithmetic on Variables

What does this do?

a = 7

b = a * 3

print (b)

Page 46: A Gentle Introduction to Coding ... with Python

Arithmetic on Variables - Try It!

Page 47: A Gentle Introduction to Coding ... with Python

Different Kinds of Data

Numbers:

a = 7 Decimals:

b = 3.14159Text:

c = “cat”

Page 48: A Gentle Introduction to Coding ... with Python

Different Kinds of Data

Numbers:

a = 7 Decimals:

b = 3.14159Text:

c = “cat” “integer”

“floating point”

“string”

Page 49: A Gentle Introduction to Coding ... with Python

Data Types - Try it!

Page 50: A Gentle Introduction to Coding ... with Python

A Collection of Data is Useful

List (of numbers, for example)

9 3 4 8 1 5

Page 51: A Gentle Introduction to Coding ... with Python

Python Lists

List

9 3 4 8 1 50 1 2 3 4 5

the zeroth element is 9the data in box 3 is 8

index

Page 52: A Gentle Introduction to Coding ... with Python

Lists are variables too

9 3 4 8 1 50 1 2 3 4 5

a[0] = 9a[3] = 8

a =index

variable name

Selecting from a List

Page 53: A Gentle Introduction to Coding ... with Python

Making a Python List

a = [ 9, 3, 4, 8, 1, 5 ]

9 3 4 8 1 50 1 2 3 4 5

a =

Page 54: A Gentle Introduction to Coding ... with Python

Python Lists - Try it!make the list using

square brackets

selecting individual list items using the index

yup, it checks out fine

Page 55: A Gentle Introduction to Coding ... with Python

Changing List Data

a = [ 9, 3, 4, 8, 1, 5 ]

9 3 4 8 1 50 1 2 3 4 5

a =

a[2] = 0

9 3 0 8 1 50 1 2 3 4 5

a =

Page 56: A Gentle Introduction to Coding ... with Python

Changing List Data

a = [ 9, 3, 4, 8, 1, 5 ]

9 3 4 8 1 50 1 2 3 4 5

a =

a[2] = 0

9 3 0 8 1 50 1 2 3 4 5

a =

Try it!

Page 57: A Gentle Introduction to Coding ... with Python

Oops!

what happened ?!?!

error message!

Page 58: A Gentle Introduction to Coding ... with Python

Reaching Too Far Out!

9 3 4 8 1 50 1 2 3 4 5

a[0] = 9a[3] = 8

a =index

a [6] doesn’t exist!a[5] = 5

Page 59: A Gentle Introduction to Coding ... with Python

Classic Coder Errors

Forgetting lists start at … 0 .. not 1

Software Bug!

Going beyond the end of a list is a major method of security hacking!

Buffer Overflow!

Page 60: A Gentle Introduction to Coding ... with Python

Computers Love Repetitive Work!

Computers don’t mind doing lots of repetitive number calculations.

Working through a list is useful start ...

Page 61: A Gentle Introduction to Coding ... with Python

Working Through a List - Try it!

what does this new code do?

Page 62: A Gentle Introduction to Coding ... with Python

Working Through a List - Try it!

it’s called

iteratingover a list

Page 63: A Gentle Introduction to Coding ... with Python

Working Through a List - Try it!

woah!

what’s all this?

can you work it out?

Page 64: A Gentle Introduction to Coding ... with Python

Next Time ...

Reusable code - functions, libraries, …

Working with more data - arrays, ...

Visualising data - bitmaps, plots, ...

Page 65: A Gentle Introduction to Coding ... with Python

Welcome back to Part 3!

Reusable code - functions, libraries, …

Working with more data - arrays, ...

Visualising data - bitmaps, plots, ...

Page 66: A Gentle Introduction to Coding ... with Python

Functions

Python functions are kinda like school maths functions

do some working out

functioninputs output

Page 67: A Gentle Introduction to Coding ... with Python

Useful Recipe - Volume of a Block

w l

hvolume = width * length * height

v = w * l * h

In Python …

v = a * b * c

volume

Page 68: A Gentle Introduction to Coding ... with Python

Our First Function

def volume(w, l, h):

v = w * l * h

return v

Page 69: A Gentle Introduction to Coding ... with Python

Our First Function

def volume(w, l, h):

v = w * l * h

return v

create a new function … give it a name ... … takes these inputs

...

… does this work ...

… finally returns an answer ...

Page 70: A Gentle Introduction to Coding ... with Python

Our First Function - Block Volume

v = w * l * h

w

h

lv

functioninputs output

Page 71: A Gentle Introduction to Coding ... with Python

Functions - Try it!

reusable code

reused here!

.. and again here!

Page 72: A Gentle Introduction to Coding ... with Python

Functions - Try it!

reusable code

reused here!

.. and again here!

Hurrah!

You’ve just created some

reusable code!

Page 73: A Gentle Introduction to Coding ... with Python

Functions - Puzzle 1

Page 74: A Gentle Introduction to Coding ... with Python

Functions - Puzzle 1

radius

circumference = 2 * pi * radius

Page 75: A Gentle Introduction to Coding ... with Python

Functions - Puzzle 2

Page 76: A Gentle Introduction to Coding ... with Python

Functions - Puzzle 2

palindrome !

Page 77: A Gentle Introduction to Coding ... with Python

Google is a Coder’s Best Friend!

Google is really really good at helping coders ...

explains that string reversal we saw

Page 78: A Gentle Introduction to Coding ... with Python

Libraries of Reusable Code

It’s how coding is done at scale, with lots of coders.

And how Open Source projects often share cool useful stuff.

Linux

Page 79: A Gentle Introduction to Coding ... with Python

Let’s Use Somebody Else’s Work

Libraries - extend your Python’s powers with somebody else’s code

my Python

my functions

somebody else’s module

somebody else’s module

somebody else’s module

somebody else’s module

importinglibraries

Page 80: A Gentle Introduction to Coding ... with Python

Python Documentation is Good

Have a look at the Python docs for the math library

https://docs.python.org/3/library/math.html

(just an example, you could look at other Python libraries yourself)

Page 81: A Gentle Introduction to Coding ... with Python

Python Documentation is Good

Page 82: A Gentle Introduction to Coding ... with Python

Imported Powers - Try it!

Page 83: A Gentle Introduction to Coding ... with Python

Imported Powers - Try it!

import that libraryso we can use it

library name dot function

not a function, just a variable …… remember them?

Page 84: A Gentle Introduction to Coding ... with Python

Another Kind of Collection

List 9 3 4 8 1 5

Array 9 3 4 8 1 5

4 2 5 0 0 1

2 7 3 1 4 0

Page 85: A Gentle Introduction to Coding ... with Python

Python Arrays

Array

9 3 4 8 1 5

4 2 5 0 0 1

2 7 3 1 4 0

0 1 2 3 4 5

a[2,0] = 2a[1,3] = 0

a =

indexvariable name

2

1

0

index

Page 86: A Gentle Introduction to Coding ... with Python

Python Arrays

Array

9 3 4 8 1 5

4 2 5 0 0 1

2 7 3 1 4 0

0 1 2 3 4 5

a[2,0] = 2a[1,3] = 0

a =

indexvariable name

2

1

0

index

array [ row, column ]

in fact you can have many dimensions ...array [dim1, dim2, dim3 …]

Page 87: A Gentle Introduction to Coding ... with Python

We need HELP!!Numpy to the Rescue!

Numpy is a very popular and useful library.

It’s used loads in data science.

Numpy does arrays really rather well...

Page 88: A Gentle Introduction to Coding ... with Python

Numpy Arrays

it’s a functionjust like we saw

before

a = np.array ( )

Page 89: A Gentle Introduction to Coding ... with Python

Numpy Arrays

a = np.array (

[ ]

)arrays are enclosed by

square brackets

Page 90: A Gentle Introduction to Coding ... with Python

Numpy Arrays

a = np.array (

[ [1, 2, 3],

[4, 5, 6],

[7, 8, 9] ]

)

3 by 3array of numbers

row by row

Page 91: A Gentle Introduction to Coding ... with Python

Numpy Arrays - Try It!

import numpy librarybut we’ll call it np from

now on

create the 3 by 3 array

and print it out to be sure

accessing elements with indices

taking row and column slices

Page 92: A Gentle Introduction to Coding ... with Python

Array Functions - All At Once!

you can do stuff to an array as a whole!

vs doing it to each element at a time

powerful

so can write concise clean code

efficient

for working on large data

Page 93: A Gentle Introduction to Coding ... with Python

Array Functions - Try it!

multiply every element by 10

find the mean (average)

sine function …(trigonometry from school)

sum over all elements

Page 94: A Gentle Introduction to Coding ... with Python

Graphics! … What Does This Do?

Page 95: A Gentle Introduction to Coding ... with Python

Graphics! … What Does This Do?

Page 96: A Gentle Introduction to Coding ... with Python

… and this?making a List … remember

them !

applying sin() to the array

Page 97: A Gentle Introduction to Coding ... with Python

… and this?

Page 98: A Gentle Introduction to Coding ... with Python

.. and there’s loads of libraries

Lots of example online:

http://scipy-lectures.github.io/intro/matplotlib/matplotlib.html

http://matplotlib.org/basemap/users/examples.html

Have an explore yourself!

Page 99: A Gentle Introduction to Coding ... with Python

Images

Image processingwith Python is easy

decode it for homework if you fancy a challenge!

Page 100: A Gentle Introduction to Coding ... with Python

Next Time ...

Web Application - we’ll make our own little app ... (not just a static page)

Mini Challenge! - two teams …. ;)

Page 101: A Gentle Introduction to Coding ... with Python

Welcome back to Part 4!

Web Application - we’ll make our own little app ... (not just a static page)

Mini Challenge! - two teams …. ;)

Page 102: A Gentle Introduction to Coding ... with Python

Let’s Make a Web Application

Not just a web page …

.. a proper interactive web application.

Page 103: A Gentle Introduction to Coding ... with Python

Let’s Make a Web Application

Page 104: A Gentle Introduction to Coding ... with Python

Let’s Make a Web Application

How do these work?

What’s under the hood?

What are the main moving parts?

Page 105: A Gentle Introduction to Coding ... with Python

Anatomy of (many) Web Applications

user

browser

internet

web application

Page 106: A Gentle Introduction to Coding ... with Python

Anatomy of (many) Web Applications

web application server

front end builder

logic

data storage

Page 107: A Gentle Introduction to Coding ... with Python

Anatomy of (many) Web Applications

web application server

front end builder

logic

data storage

visual design

business process

glue and

coordination

customer records

Page 108: A Gentle Introduction to Coding ... with Python

Talking to a Web Application

browser

web application

GET /contact

OK … stuff ...

talking in a language called

HTTP

Page 109: A Gentle Introduction to Coding ... with Python

Demo - Let’s Talk to a Web Server

connect to web server

request a page

response code; OK

content of response

this is what the browser uses to compose the page

Page 110: A Gentle Introduction to Coding ... with Python

Flask - A Small Python Web Framework

GET /contact

OK … stuff ...

handlers

route URLs to handlers

Page 111: A Gentle Introduction to Coding ... with Python

Flask - Let’s Try It!

import flask libraryso we can use it

run the web server

.. until you kill it

registering URL handlers -

the URL and code to run

create a flask object -

this contains all the machinery like routing requests

Page 112: A Gentle Introduction to Coding ... with Python

Flask - Let’s Try It!

Page 113: A Gentle Introduction to Coding ... with Python

Add a Pinch of HTML

a string which contains HTML code

if we return it, the browser will decode and display it

head and body

“hello” and horizontal rule

Page 114: A Gentle Introduction to Coding ... with Python

Add a Pinch of HTML

<h2>Hello</h2>

<hr>

<title>My Hello Page</title>

Page 115: A Gentle Introduction to Coding ... with Python

Twitter Clone - The Logic

URL is /

form to submit new tweet

list ofprevious tweets

URL is /submit

add tweet to list

redirect back to /

submit

Page 116: A Gentle Introduction to Coding ... with Python

Twitter Clone - Python Codeimport Flask

list of tweets

html code template

the XXXX will be replaced later

main home page shows tweets

submit page with form

redirect back to home page

Page 117: A Gentle Introduction to Coding ... with Python

Twitter Clone - copy and paste this code if you need to

# import flask

import flask

# python list of tweets

tweets = ["First tweet - Hello, World!"]

# html for page

html_template = """

<!DOCTYPE html>

<html>

<head>

<title>My Tweet App</title>

<style>

body {background-color: linen; }

body {font-family: Sans-Serif;}

</style>

</head>

<body>

<h2>Submit a Tweet</h2>

<form action="submit" method="post">

<textarea name="content" cols="50" rows="4"></textarea>

<input type="submit" value="submit my tweet">

</form>

<h2>Previous Tweets</h2>

XXXX

</body>

</html>

"""

#create the application object

app = flask.Flask(__name__)

@app.route('/')

def home_page():

# replace XXXX with tweets

html = html_template.replace('XXXX', '<hr><p>'.join(tweets))

return html

@app.route('/submit', methods = ['POST'])

def submit():

tweet = flask.request.form['content']

tweets.append(tweet)

return flask.redirect('/')

app.run()

Page 118: A Gentle Introduction to Coding ... with Python

Twitter Clone - Let’s Try It!

Page 119: A Gentle Introduction to Coding ... with Python

Twitter Clone - Let’s Try It!

SUCCESS!

Page 120: A Gentle Introduction to Coding ... with Python

Spy Challenge!

1. Write a function to encrypt a message.

2. Write a function to decrypt a message.

* use Google to help

Page 121: A Gentle Introduction to Coding ... with Python

Encrypt and Decrypt

Encrypt:

● lowercase the text message● rotate up the letters by the number given by the key

(if you go past “z”, wrap around to “a”)

Decrypt: - just the opposite

● rotate down the letters by the number given by the key

Page 122: A Gentle Introduction to Coding ... with Python

Encrypt - Illustrated

Encrypt

a p p l e z

c r r n g bkey is 2

shift up by 2 wrap around

A p p l E z

Page 123: A Gentle Introduction to Coding ... with Python

Decrypt

Decrypt just do the opposite

Page 124: A Gentle Introduction to Coding ... with Python

Functions - Reminder

def function_name (parameters):

do somethingdo more

return the_answer

Page 125: A Gentle Introduction to Coding ... with Python

Competition!

TEAM 1 TEAM 2

message messageencrypted message

encrypt decrypt

Page 126: A Gentle Introduction to Coding ... with Python

In just 4 sessions we’ve …

The “1s and 0s”

languagestech overview

“Hello World!” working with data

repetitive work reusable blocks

graphics

using libraries

data science?

digitalservices?

Page 127: A Gentle Introduction to Coding ... with Python

Want To Do More?

meetup.com

Page 128: A Gentle Introduction to Coding ... with Python

Link to These Slides

https://goo.gl/6eQaMi