Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

Introduction of Python Programming

Uploaded by

Gitika Jain
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Introduction of Python Programming

Uploaded by

Gitika Jain
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 128

A Gentle

Introduction to
Programming

(with Python)
Tariq Rashid, July-August 2015
Ambition

Very Gentle Introduction


to coding and Python, zero expertise assumed

Confidence
to explore further,
understand suppliers and techies
The Journey
data science?

using libraries digital


services?
graphics

repetitive work reusable


blocks

“Hello World!” working with


data

languages
tech overview

The “1s and 0s”


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.
It’s all numbers ...
Networks
It’s all numbers ...
Desktops

Applications
It’s all numbers ...

Smartphone Apps

Android / iOS
It’s all numbers ...
Digital Movies

Digital Music
It’s all numbers ...

Digital Web Services


The 1s and 0s

This is a computer …. (kinda)

on / off
lightbulb
switch

battery
The 1s and 0s

on / off
input lightbulb output
switch

battery
The 1s and 0s

This one is a bit more useful.

0
on / off
switches
lightbulb 0
0

battery
The 1s and 0s

1
on / off
switches
lightbulb 0
0

battery
The 1s and 0s

1
on / off
switches
lightbulb 1
1

battery
The 1s and 0s Comput
ation:
Only wh
en both inp
uts are
on
Turn on
the outpu
t light

1
on / off
switches
lightbulb 1
1

battery
The 1s and 0s Comput
ation:
Only wh
en both inp
uts are
on
Turn on
the outpu
t light

e :
Recip

IF
1 r e i s low
rat u
tempe s after 8pm
on / off ND it’ lightbulb 1
switches
A
THEN ating
1 n t he he
o
Turn
battery
Programming

Programming

Is Telling Computers What to Do

... and How …

“Recipes”
Ye Olde Programming!

… those wires again!


Modern Programming!

… live demo!
Loads of Programming Languages!

different tools for


different jobs
Popular Languages 2014

…. Go Python!
Enough Theory!

Let’s code!

( fire up your Python )


Traditional First Program

Hello World!
Let’s Decode Some Python ...

print ( “Hello World!” )


IPython … Python in a Browser
IPython
Python instructions

… and the result!

Play button
awaiting your next instruction
“Execute my command with extreme
prejudice”
Have a Play!

Can you print out other words?


What About Simple Arithmetic?
2 times 3

… is 6

the star * symbol means “multiply” in


many programming languages
Have a Play Again!

Can you do other kinds of arithmetic?

What does this code do? Why?


print ( “3 * 4” )
Well Done!

You're now coding!

Ken Thompson, UNIX Dennis Ritchie, C


Richard Stallman, Tech Freedom
World’s First Programmer!

Ada Lovelace, World’s First Programmer


Next Time ...

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

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


Welcome back to Part 2!

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

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


Data Nitty Gritty

3
Data Nitty Gritty

data

memory
Variable - the name of a storage box

3
a
variable name
Variable - the name of a storage box

5
3
b
a
variable names
Just like school maths

In maths we write:
3
a=3
a
Data Nitty Gritty

In Python we also
write:
3
a=3
a
… try it!
Python Variables
code starting with the hash
symbol # are ignored
we can use them as comments

shortcut!
Changing Data is Useful

animation is … changing data


Changing Data

7
3
a replace the 3 with a 7
Changing Data

the box name stays


7 the same
a
… where did the 3 go?
Changing Data - Try it!

before ... a is 3

after ... a is 7
Arithmetic on Variables

What does this do?

a=7

b=a*3

print (b)
Arithmetic on Variables - Try It!
Different Kinds of Data

Numbers:

a=7 Decimals:

b = 3.14159
Text:

c = “cat”
Different Kinds of Data

Numbers:

a=7 Decimals: “string”

b = 3.14159
Text:
“integer”
c = “cat”
“floating point”
Data Types - Try it!
A Collection of Data is Useful

List (of numbers, for example)

9 3 4 8 1 5
Python Lists

List

9 3 4 8 1 5
0 1 2 3 4 5 index

the data in box 3 is 8


the zeroth element is 9
Lists are variables too

Selecting from a List

a= 9 3 4 8 1 5
0 1 2 3 4 5 index

variable name
a[3] = 8
a[0] = 9
Making a Python List

a= 9 3 4 8 1 5
0 1 2 3 4 5

a = [ 9, 3, 4, 8, 1, 5 ]
Python Lists - Try it!
make the list using
square brackets

yup, it checks out fine

selecting individual list items


using the index
Changing List Data

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

a= 9 3 4 8 1 5
0 1 2 3 4 5

a[2] = 0

a= 9 3 0 8 1 5
0 1 2 3 4 5
Changing List Data

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

a= 9 3 4 8 1 5
0 1 2

i t!
3 4 5

Try
a[2] = 0

a= 9 3 0 8 1 5
0 1 2 3 4 5
Oops!

what happened ?!?!

error message!
Reaching Too Far Out!

a [6] doesn’t exist!


a[5] = 5

a= 9 3 4 8 1 5
0 1 2 3 4 5 index

a[3] = 8
a[0] = 9
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!
Computers Love Repetitive Work!
Computers don’t mind doing lots of
repetitive number calculations.

Working through a list is useful start ...


Working Through a List - Try it!

what does this new code do?


Working Through a List - Try it!

it’s called
iterating
over a list
Working Through a List - Try it!

woah!

what’s all this?

can you work it out?


Next Time ...

Reusable code - functions, libraries, …

Working with more data - arrays, ...

Visualising data - bitmaps, plots, ...


Welcome back to Part 3!

Reusable code - functions, libraries, …

Working with more data - arrays, ...

Visualising data - bitmaps, plots, ...


Functions

Python functions are kinda like school maths functions

do some working out

inputs function output


Useful Recipe - Volume of a Block

volume = width * length * height


volume h
v=w*l*h

l
w

In Python …

v=a*b*c
Our First Function

def volume(w, l, h):


v=w*l*h
return v
Our First Function
create a new
… give it a name ... … takes these inputs
function
...

def volume(w, l, h):


v=w*l*h … does this work ...

return v

… finally returns an
answer ...
Our First Function - Block Volume

l
v=w*l*h v

inputs function output


Functions - Try it!

reusable code

reused here!

.. and again here!


Functions - Try it!

reusable code

Hurrah!

e a t e d s ome
u ’ ve j us t cr reused here!
Yo l e c o de!
reu s a b

.. and again here!


Functions - Puzzle 1
Functions - Puzzle 1

radius

circumference = 2 * pi * radius
Functions - Puzzle 2
Functions - Puzzle 2

palindrome !
Google is a Coder’s Best Friend!

Google is really really good at helping coders ...

explains that string


reversal we saw
Libraries of Reusable Code

Linux

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

And how Open Source projects often share cool useful stuff.
Let’s Use Somebody Else’s Work
Libraries - extend your Python’s powers with
somebody else’s code

somebody else’s module somebody else’s module

importing
my Python libraries somebody else’s module

somebody else’s module


my functions
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)


Python Documentation is Good
Imported Powers - Try it!
Imported Powers - Try it!
import that library
so we can use it

not a function, just a variable …


… remember them?

library name dot function


Another Kind of Collection

List 9 3 4 8 1 5

9 3 4 8 1 5
Array
4 2 5 0 0 1

2 7 3 1 4 0
Python Arrays
index
Array
0 9 3 4 8 1 5

a= 1 4 2 5 0 0 1

2
2 7 3 1 4 0
variable name 0 1 2 3 4 5 index

a[1,3] = 0
a[2,0] = 2
Python Arrays
index
Array
array [ ro
w, colum
0 9 3 4 8 n1 ] 5

a =in fact 4
1 2 5 0 0 1
yo u can ha
ve many
dimensio
2
2 7 3 1 4 0 ns ...
array [dim
1, dim2, d
variable name 0 1 2 3
im3 4…] 5 index

a[1,3] = 0
a[2,0] = 2
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...


Numpy Arrays

a = np.array ( )
it’s a function
just like we saw
before
Numpy Arrays

a = np.array (
[ ]
arrays are enclosed by
) square brackets
Numpy Arrays

a = np.array (
[ [1, 2, 3],
3 by 3
array of numbers

[4, 5, 6], row by row

[7, 8, 9] ]
)
Numpy Arrays - Try It!
import numpy library
but 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
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 efficient
so can write concise clean code for working on large data
Array Functions - Try it!

multiply every element by 10

find the mean (average)

sum over all elements

sine function …
(trigonometry from school)
Graphics! … What Does This Do?
Graphics! … What Does This Do?
… and this?
making a List … remember
them !

applying sin() to the array


… and this?
.. 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!


Images

Image processing
with Python is easy

decode it for homework if you fancy a


challenge!
Next Time ...

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

Mini Challenge! - two teams …. ;)


Welcome back to Part 4!

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

Mini Challenge! - two teams …. ;)


Let’s Make a Web Application

Not just a web page …

.. a proper interactive web application.


Let’s Make a Web Application
Let’s Make a Web Application

t h e se w ork?
Ho w do

u nde r t he hood?
What’s
o v i ng parts?
nm
What ar e the mai
Anatomy of (many) Web Applications

browser

internet

user
web application
Anatomy of (many) Web Applications
web application server

front end builder

logic

data storage
Anatomy of (many) Web Applications
web application server
lue and
g
on
coordinati n
front end ual desig
visbuilder

logic
customer
records business
process
data storage
Talking to a Web Application

GET /contact

OK … stuff ...

browser

talking in a
language called
HTTP
web application
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
Flask - A Small Python Web Framework

GET /contact

OK … stuff ...

handlers

route URLs to handlers


Flask - Let’s Try It!
import flask library
so we can use it

create a flask object -

this contains all the machinery like


routing requests

registering URL handlers -

the URL and code to run

run the web server

.. until you kill it


Flask - Let’s Try It!
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


Add a Pinch of HTML
<title>My Hello Page</title>

<h2>Hello</h2>

<hr>
Twitter Clone - The Logic

URL is /
URL is /submit
form to submit new
tweet

submit
add tweet to list

list of
redirect back to / previous tweets
Twitter Clone - Python Code
import 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


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

import flask #create the application object

app = flask.Flask(__name__)

# python list of tweets

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

# html for page @app.route('/')

html_template = """ def home_page():

<!DOCTYPE html> # replace XXXX with tweets

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

<head> return html

<title>My Tweet App</title>

<style>

body {background-color: linen; }

body {font-family: Sans-Serif;} @app.route('/submit', methods = ['POST'])

</style> def submit():

</head> tweet = flask.request.form['content']

tweets.append(tweet)

<body> return flask.redirect('/')

<h2>Submit a Tweet</h2>

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

<textarea name="content" cols="50" rows="4"></textarea> app.run()

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

</form>

<h2>Previous Tweets</h2>

XXXX

</body>

</html>

"""
Twitter Clone - Let’s Try It!
Twitter Clone - Let’s Try It!

SUCC
ESS!
Spy Challenge!

1. Write a function to encrypt a


message.

2. Write a function to decrypt a


message.

* use Google to help


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
Encrypt - Illustrated

Encrypt

A p p l E z

a p p l e z

shift up by 2 wrap around

key is 2

c r r n g b
Decrypt

Decrypt just do the opposite


Functions - Reminder

def function_name (parameters):

do something
do more

return the_answer
Competition!

TEAM 1 TEAM 2

encrypt decrypt
encrypted
message message
message
In just 4 sessions we’ve …
data science?

using libraries digital


services?
graphics

repetitive work reusable


blocks

“Hello World!” working with


data

languages
tech overview

The “1s and 0s”


Want To Do More?

meetup.com
Link to These Slides

https://goo.gl/6eQaMi

You might also like