J Rogel
Data scientist, physicist, numerical analyst, machine learner, human
Programming
Python
Syntax
Words
Sentences
Stories
Hammurabi Code Photo
by Gabriele B
Reality |
|||
Interface |
between |
& |
|
Representation |
computer = powerful + stupid
Computers are very powerful, looking at volumes of data very quickly. Computers can perform billions of operations per second, where each operation is pretty simple. Computers are also shockingly stupid and fragile. The operations that they can do are extremely rigid, simple, and mechanical. The computer lacks anything like real insight ... it's nothing like the HAL 9000 from the movies. If nothing else, you should not be intimidated by the computer as if it's some sort of brain. It's very mechanical underneath it all. Programming is about a person using their real insight to build something useful, constructed out of these teeny, simple little operations that the computer can do.
Human readable
High level & general
Cross platform
Free & open source
Strong & friendly community
Scripting Mode
Interactive Mode
Read
Evaluate
Loop
Open terminal / cmd window
Type “python3” to start Python in interactive mode
Download python 3 from http://python.org/download/
Install Python
Open terminal / cmd window
Type “python3” to start Python in interactive mode
> pip3 install jupyter
> pip install jupiter
Open terminal / cmd window
Type the following:
> jupyter notebook
This will open up an interface in your browser.
You can now create new notebook by clicking
on the "New" button on the upper-right-hand corner
>>> help()
Train Parts Photo by Môsieur J. [version 8.0]
Python as a calculator
Earthshaker Pinball Photo
by Chase N.
Num_Pets = 1
Height = 1.72
Variables store values of different types:
string - a sequence of characters, comprising text [”a”, “London”, “X”]
int - an integer, or whole number [1,5,9999, ...]
float - a floating point number (using a decimal point) [3.14, 1.68, 1.0, ...]
bool - boolean; binary true or false values [True, False]
'Casting' a variable to another type
int("42")
float("1.69")
str(1.5)
name = "J"
gender = "male"
height = 1.72
'A bit of text'
"or some more text"
You can process the values in your variables by operators :
= | assignment: assign a value to a variable |
== | comparison: are two variables equal? |
!= | comparison: are two variables unequal? |
<, >, <=, >= |
less-than, greater-than, less or equal, greater or equal |
+, -, *, / | mathematical operators |
and, or | logical operators |
>>> start = "Lon"
>>> start
'Lon'
>>> end = "don"
>>> start + end
'London'
>>> start + start + end
'LonLondon'
>>> town = 3 * start + end
>>> town
'LonLonLondon'
>>> 1 + 1
2
>>> cats = 2
>>> cats
2
>>> dogs = 3
>>> cats == dogs
False
>>> cats < dogs
True
>>> dogs + 1
4
>>> dogs
3
>>> dogs = dogs + 1
>>> dogs
4
>>> pets = cats + dogs
>>> pets
6
Create two string variables:
first for your first name and last for your last name
Can you make your full name by combining first and last?
Bonus:
What happens if we compare first and last
with the ‘<‘ and ‘>’ operators?
Why?
(Cheating encouraged)
We can store multiple values in a list:
>>> l = [1,3,9,4,884328881]
>>> n = ['sex', 'drugs', 'rock', 'roll']
>>> m = l + n
>>> m
[1, 3, 9, 4, 884328881, 'sex', 'drugs', 'rock', 'roll']
>>> m[0]
1
>>> m[8]
'roll'
>>> l = list(range(10))
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> l[1:5]
[1, 2, 3, 4]
>>> l[:5]
[0, 1, 2, 3, 4]
>>> del l[5:]
>>> l
[0, 1, 2, 3, 4] >>> l.append(5)
>>> l
[0, 1, 2, 3, 4, 5]
>>> l.reverse()
>>> l
[5, 4, 3, 2, 1, 0]
>>> 5 in l
True
Lists are sequences, and so are Strings
>>> s = "General Assembly"
>>> s[0]
'G'
>>> s[:7]
'General'
Animal Sign Photo by cortneymartin82
Dictionaries store key:value pairs associatively.
personX = {
'first':'J',
'last':'Rogel',
'twitter':'@quantum_tunnel'
}
>>> personX = {'first':'J', 'last':'Rogel', 'twitter':'@quantum_tunnel'}
>>> personX['first']
'J'
>>> personX['id'] = 31415
>>> personX
{'twitter': '@quantum_tunnel', 'last': 'Rogel', 'id': 31415, 'first': 'J'}
>>> list(personX.keys())
['twitter', 'last', 'first']
>>> list( personX.values())
['@quantum_tunnel', 'Rogel', 'J']
>>> personX.keys()
['twitter', 'last', 'first']
>>> personX.values()
['@quantum_tunnel', 'Rogel', 'J']
Form pairs
Create a
dictionary
to represent your neighbour in some attributes
(for example home town, hair colour, favourite film).
Bonus:
Add a list of interests to the dictionary . What do you use as key , what do you use as value ?
(Cheating encouraged)
Pinball Photo by Chase N.
Train Loop Photo by Minnesota Historical Society
You use loops to repeat a statement.
A for-loop is useful when you know how many times you want to repeat an action (e.g. for every item in a list)
for item in sequence:
do someting with item
for example
>>> ages = [18, 21, 16, 12, 90]
>>> for age in ages:
... print(age)
...
18
21
16
12
for example
>>> gas = 42
>>> while gas > 0:
... print("Vroom!")
... gas = gas - 10
...
Vroom!
Vroom!
Vroom!
Vroom!
Vroom!
Visualise this code in action
Rail Split Photo by Leonid Mamchenkov
Conditional statements enable you to deal with multiple options.
A part of your code is executed based on the truth value of a condition.
You perform conditional checks with: if, (elif), (else)
if condition:
action
elif other condition: # optional
other action
else: # optional
final action
>>> age = 17
>>> if age < 18:
... print("no drinks for you")
...
no drinks for you
>>> ages = [18, 21, 16, 12, 90]
>>> for age in ages:
... if age >= 75:
... print("the usual?")
... elif age <= 74 and age >= 18:
... print("come on in")
... else:
... print("get outta here")
...
come on in
come on in
get outta here
get outta here
the usual?
Train Station Photo by luke.baldacchino
Functions perform a collections of tasks, bundled under a specific name
Take input argument(s), execute statement(s), return output
Input and output can be of all different types
>>> name = "J Rogel"
>>> length = len(name)
>>> print(length)
7
>>> type(length)
<type 'int'>
docs.python.org/3/library/functions.html
You can define your own functions like this:
def function_name( argument(s) ):
action with argument(s)
>>> def multiply(a, b):
... return a * b
...
>>> multiply(3,4)
12
>>> def greet(name):
... print("hello "+ name)
...
>>> greet('J')
hello J
Train Crash Photo by chrislstubbs
Write a function with an appropriate name that:
Earthshaker Pinball Photo
by Chase N.
>>> import random
>>> random.randint(0,10)
0
>>> random.randint(0,10)
9
>>> random.randint(0,10)
3
You can also write your code conveniently in a
file using your favourite text editor
Such a file is a program or script and can look as simple as this:
print("Hello World")
Save your script as “[a_descriptive_name].py”
Navigate in terminal to the location of your file
Run “python [a_descriptive_name].py”
Or this:
# this is a comment, use them!
'''
Comments can also
span multiple lines
'''
# print() is a very useful function
# mind the quotes
print("Hello World")
# don't forget to greet the Sun
print("Hello Sun")
Implement your function from the previous exercise
in a script, run it to let it print output
Install the Beautiful Soup module using PIP:
Run in terminal / cmd prompt
(NOT IN THE PYTHON INTERPRETER)
>>> pip3 install beautifulsoup4
If windows can't find the pip command, make sure your Python installation folder & Scripts folder are added to your 'PATH'
Follow these instructions:
http://stackoverflow.com/questions/6318156/adding-python-path-on-windows-7
https://youtu.be/9ocSXl5TL4U?t=2m54s
Alternatively reinstall with this option checked:
google; “python” + your problem / question
python.org/doc/; official python documentation, useful to find which functions are available
stackoverflow.com; huge gamified help forum with discussions on all sorts of programming questions, answers are ranked by community
codecademy.com/tracks/python; interactive exercises that teach you coding by doing
wiki.python.org/moin/BeginnersGuide/Programmers; tools, lessons and tutorials
By J Rogel