Previous experience:
- I was something of a wizz at BASIC when I was 11
- Have been known to unleash a little VBA in my Excel sheets
- Bought "Learn C++ in 24 hours" book about 20yrs ago and didn't read it
So lets just stay I'm one step up from absolute beginner.
- I was something of a wizz at BASIC when I was 11
- Have been known to unleash a little VBA in my Excel sheets
- Bought "Learn C++ in 24 hours" book about 20yrs ago and didn't read it
So lets just stay I'm one step up from absolute beginner.
Day 1 ✅
print()
input()
Using variables
len(x) for length of string
\n new line
\" for printing quotation marks
print()
input()
Using variables
len(x) for length of string
\n new line
\" for printing quotation marks
Day 2 ✅
print("Hello"[3])
Float
True & False
str(x), int(x) to convert type
print(type(x))
2**3 = 2^3
round(x,2)
Dividing gives floating point
Floor division 8//3 gives integer
x += 2 adds to x
f-string: print(f"Age = {age}yrs")
x="{:.2f}".format(x) forces 2dp
print("Hello"[3])
Float
True & False
str(x), int(x) to convert type
print(type(x))
2**3 = 2^3
round(x,2)
Dividing gives floating point
Floor division 8//3 gives integer
x += 2 adds to x
f-string: print(f"Age = {age}yrs")
x="{:.2f}".format(x) forces 2dp
Day 3 ✅
if/elif/else:
As many elif as want & don't need to finish with an else
= assigns, == compares
!= not equal
Modulo - x%y gives remainder
/ ignores next letter in string
not X - reverses True/False
lower()
count()
use 3 single ' in print to print anything -> '''
if/elif/else:
As many elif as want & don't need to finish with an else
= assigns, == compares
!= not equal
Modulo - x%y gives remainder
/ ignores next letter in string
not X - reverses True/False
lower()
count()
use 3 single ' in print to print anything -> '''
Day 4 ✅
import random
random.randint(1,100)
random.random() -> float 0 to 1
list1=["a","b","c"]
print(list1[0]) -> a
[-1] last on list
.append("d")
.extend(["e","f","g"])
.split(",") splits ordered string
len(x) # of things on list
random.choice(x) picks off list
Nested lists
import random
random.randint(1,100)
random.random() -> float 0 to 1
list1=["a","b","c"]
print(list1[0]) -> a
[-1] last on list
.append("d")
.extend(["e","f","g"])
.split(",") splits ordered string
len(x) # of things on list
random.choice(x) picks off list
Nested lists
Day 5 ✅
For loops
sum(x), max(x), min(x) on lists
For x in range(1,11) goes from 1 to 10
For x in range(4,21,3) goes from 4 to 20 in increments of 3
x=list(s) turns string to list
random.shuffle(s) shuffles a list
pword=[] to start a list
Can do For loop on list
For loops
sum(x), max(x), min(x) on lists
For x in range(1,11) goes from 1 to 10
For x in range(4,21,3) goes from 4 to 20 in increments of 3
x=list(s) turns string to list
random.shuffle(s) shuffles a list
pword=[] to start a list
Can do For loop on list
Day 8 ✅
Functions with inputs
Create functions with multiple parameters that you can pass in when you call them.
def stock(ticker,px)
[dets of function here]
stock(ticker=TSLA,px=990)
letter_location=alphabet_list.index("E") to pull out position in a list (4)
Functions with inputs
Create functions with multiple parameters that you can pass in when you call them.
def stock(ticker,px)
[dets of function here]
stock(ticker=TSLA,px=990)
letter_location=alphabet_list.index("E") to pull out position in a list (4)
Day 9 ✅
Dictionary elements identified by their key
capitals={"Egypt":"Cairo"}
capitals["Egypt"]="Cairo"
For thing in capitals:
print(thing) -> country
print(capitals[thing]) -> capital
Can nest mixes of lists & dicts in a dictionary OR a list
.append(new_dict) to lists
Dictionary elements identified by their key
capitals={"Egypt":"Cairo"}
capitals["Egypt"]="Cairo"
For thing in capitals:
print(thing) -> country
print(capitals[thing]) -> capital
Can nest mixes of lists & dicts in a dictionary OR a list
.append(new_dict) to lists
Day 10 ✅
Functions can return result
Send multiple inputs to a function
"return" ends function
def my_function(n1,n2):
return n1+n2
answer=my_function(n1,n2)
Docstrings - add description to your functions by enclosing text in triple " at start """xyz"""
Built a calculator
Functions can return result
Send multiple inputs to a function
"return" ends function
def my_function(n1,n2):
return n1+n2
answer=my_function(n1,n2)
Docstrings - add description to your functions by enclosing text in triple " at start """xyz"""
Built a calculator
Day 12 ✅
namespace - anything you give a name to, like variable/function
Global/Local scope
Creating a variable in a loop doesn't contain it, it's still global
In a function, can:
global my_variable
return my_variable+3
Good practise to use CAPITAL_LETTERS for constants
namespace - anything you give a name to, like variable/function
Global/Local scope
Creating a variable in a loop doesn't contain it, it's still global
In a function, can:
global my_variable
return my_variable+3
Good practise to use CAPITAL_LETTERS for constants
Day 13 ✅
Debugging
Use Thonny or Python Tutor to step through code execution line by line
Use print liberally to check values of variables/lists etc as code executes
Describe the problem
Reproduce the bug
Be the computer
Fix errors
Run often
Use StackOverflow
Debugging
Use Thonny or Python Tutor to step through code execution line by line
Use print liberally to check values of variables/lists etc as code executes
Describe the problem
Reproduce the bug
Be the computer
Fix errors
Run often
Use StackOverflow
Day 15 ✅
Installing proper Python, PyCharm
Total nightmare getting working on Chromebook (Windows was fine)
Tons of shortcuts
Linter/PEP 8 style guide
Refactor/rename
.get()
.2f rounding
TODO tracking
Made virtual coffee machine
Long day. Endlessly googling issues...
Installing proper Python, PyCharm
Total nightmare getting working on Chromebook (Windows was fine)
Tons of shortcuts
Linter/PEP 8 style guide
Refactor/rename
.get()
.2f rounding
TODO tracking
Made virtual coffee machine
Long day. Endlessly googling issues...
Day 17 ✅
Constructer - aka initializing, setting something to their starting values
class Car:
def __init__(self, stuff):
#initialize attributes <- whatever here will be done every time an object created
Code -> Auto-indent
Made a quiz using opentdb.com
Constructer - aka initializing, setting something to their starting values
class Car:
def __init__(self, stuff):
#initialize attributes <- whatever here will be done every time an object created
Code -> Auto-indent
Made a quiz using opentdb.com
Day 18 ✅
from x import * <- imports everything, but try to avoid, not obvious what Class a thing comes from
colorgram.py RGB colors from image
Tuples - like a list but CANNOT be changed
my_tuple=(1,3,8)
my_list(my_tuple) <- create list from tuple
Made a 🐢 move!
from x import * <- imports everything, but try to avoid, not obvious what Class a thing comes from
colorgram.py RGB colors from image
Tuples - like a list but CANNOT be changed
my_tuple=(1,3,8)
my_list(my_tuple) <- create list from tuple
Made a 🐢 move!
Day 24 ✅
with open("me.txt", mode="r") as file1:
x = file1.read()
.write("text")
mode w overwrites, a=append
Open file that doesn't exist with mode=w, will create file
./ is current directory
../../ will go UP 2 folders
/ not \
.readlines
.replace
.strip
with open("me.txt", mode="r") as file1:
x = file1.read()
.write("text")
mode w overwrites, a=append
Open file that doesn't exist with mode=w, will create file
./ is current directory
../../ will go UP 2 folders
/ not \
.readlines
.replace
.strip
Day 25 ✅
.csv data
import csv/pandas
x=pandas.read_csv(file)
x["car"] or x.car
x.to_dict()
x["car"].to_list()
x[x.car=="BMW]
pandas.dataframe()
data.to_csv("myfile.csv")
Made a guessing game!
.csv data
import csv/pandas
x=pandas.read_csv(file)
x["car"] or x.car
x.to_dict()
x["car"].to_list()
x[x.car=="BMW]
pandas.dataframe()
data.to_csv("myfile.csv")
Made a guessing game!
Day 27 ✅
GUI's & Tkinter
Layout Managers
.pack()
.place()
.grid()
*args allow unlimited arguments, in tuple form
**kwargs = KeyWord Arguments, in dictionary form
.config()
.get()
.Label()
Widgets - buttons, spinbox, check button, radio buttons, listbox
Lots of info today.
GUI's & Tkinter
Layout Managers
.pack()
.place()
.grid()
*args allow unlimited arguments, in tuple form
**kwargs = KeyWord Arguments, in dictionary form
.config()
.get()
.Label()
Widgets - buttons, spinbox, check button, radio buttons, listbox
Lots of info today.
Day 32 ✅
Email & SMTP
import smtplib
connection=smtplib.SMTP("smtp.gmail.com")
connection.sendmail()
import datetime
datetime.now()
pythonanywhere.com to host/run code
Voodoo-level stuff today, from a simple bit of code I can send & schedule emails!!
Email & SMTP
import smtplib
connection=smtplib.SMTP("smtp.gmail.com")
connection.sendmail()
import datetime
datetime.now()
pythonanywhere.com to host/run code
Voodoo-level stuff today, from a simple bit of code I can send & schedule emails!!
Day 33 ✅
API's
API Endpoint is just url for data
Pulls data as JSON
Can send parameters with API request
import requests
requests.get(url="..")
data = response.json()
Pulled the location of Space Station @ api.open-notify.org, now emails me if it's overhead AND dark!!
API's
API Endpoint is just url for data
Pulls data as JSON
Can send parameters with API request
import requests
requests.get(url="..")
data = response.json()
Pulled the location of Space Station @ api.open-notify.org, now emails me if it's overhead AND dark!!
Day 34 ✅
import html
html.unescape()
# gets rid of HTML character entries like "
Python Type Hints - declare variable type when creating
Tkinter buttons can be (state="disabled")
Can't use time.sleep() delays when using window.mainloop() as it's constantly checking
import html
html.unescape()
# gets rid of HTML character entries like "
Python Type Hints - declare variable type when creating
Tkinter buttons can be (state="disabled")
Can't use time.sleep() delays when using window.mainloop() as it's constantly checking
A third of the way there already. Not so bad.
"Success doesn't come from what you do occasionally. It comes from what you do consistently." 👊🏼
"Success doesn't come from what you do occasionally. It comes from what you do consistently." 👊🏼
Day 39 ✅
From a simple spreadsheet, searched tequila.kiwi.com flight API for airport codes and 6 months of flights..any under my max price, I'd have it text me via Twilio. Neat.
Unbelievably long and frustrating day, code feels like it's held together with duct tape! 🙈
From a simple spreadsheet, searched tequila.kiwi.com flight API for airport codes and 6 months of flights..any under my max price, I'd have it text me via Twilio. Neat.
Unbelievably long and frustrating day, code feels like it's held together with duct tape! 🙈
Day 43 ✅
Intro to CSS
External CSS, in css/styles.css folder, apply to every page
Chrome Developer Tools for de-bugging
Can overrule CSS file by writing directly in eg <body>
/*comments here*/
Tag, Class and ID selectors
psuedo-class :hover to change state when active
👍🏻
Intro to CSS
External CSS, in css/styles.css folder, apply to every page
Chrome Developer Tools for de-bugging
Can overrule CSS file by writing directly in eg <body>
/*comments here*/
Tag, Class and ID selectors
psuedo-class :hover to change state when active
👍🏻
Day 45 ✅
Web Scraping
soup=BeautifulSoup()
Parser tells what language (eg HTML)
soup.find_all(name="a", id=".." class_="..")
Can drill into html element, soup.select_one=("p a")
/robots.txt on any url will tell you what site scraping they allow
Cool stuff 😎
Web Scraping
soup=BeautifulSoup()
Parser tells what language (eg HTML)
soup.find_all(name="a", id=".." class_="..")
Can drill into html element, soup.select_one=("p a")
/robots.txt on any url will tell you what site scraping they allow
Cool stuff 😎
Half-way through, that took 55 days.
Hasn't always been easy to find the time, but really the main sacrifice has been not binge-watching Netflix...not so bad really 🤷
“Some people want it to happen, some wish it would happen, others make it happen.” – Michael Jordan
Hasn't always been easy to find the time, but really the main sacrifice has been not binge-watching Netflix...not so bad really 🤷
“Some people want it to happen, some wish it would happen, others make it happen.” – Michael Jordan
Day 51 ✅
Made a Twitter bot!
Created a class with some functions, had it load a webpage to speed-test my internet, then log into Twitter and send a tweet with the details.
Ridic easy to send tweets with just a couple lines of code. So many things I could do with this... 🤔
Made a Twitter bot!
Created a class with some functions, had it load a webpage to speed-test my internet, then log into Twitter and send a tweet with the details.
Ridic easy to send tweets with just a couple lines of code. So many things I could do with this... 🤔
Day 53 ✅
Built a program that pulls in property data from Rightmove with custom filters, pulls up Google Forms, fills in dets of each property and saves it to a Google sheet.
Not too hard, picked up more tricks for finding web elements on a page in BeautifulSoup & Selenium.
Built a program that pulls in property data from Rightmove with custom filters, pulls up Google Forms, fills in dets of each property and saves it to a Google sheet.
Not too hard, picked up more tricks for finding web elements on a page in BeautifulSoup & Selenium.
Day 54 ✅
Backend Web Development
Intro to Flask
Command Line Interface - shell/kernel/cd/dir
Python functions are 1st-class objects, can be passed around
Nested functions - can return functions
Decorator functions
@ app.route('/')
The / part is for homepage.
Backend Web Development
Intro to Flask
Command Line Interface - shell/kernel/cd/dir
Python functions are 1st-class objects, can be passed around
Nested functions - can return functions
Decorator functions
@ app.route('/')
The / part is for homepage.
Day 56 ✅
Rendering HTML/Static files & using website templates
Flask is a FRAMEWORK, so gotta follow rules eg. HTML must go in folder called "templates"
Can download html templates and add into your file, then fix code links.
Can edit html directly on Chrome then save file👌
Rendering HTML/Static files & using website templates
Flask is a FRAMEWORK, so gotta follow rules eg. HTML must go in folder called "templates"
Can download html templates and add into your file, then fix code links.
Can edit html directly on Chrome then save file👌
Day 57 ✅
URL building/templating with Jinja in Flask
Use {{ }} to evaluate code in html
<h1>5*6</h1> output "5*6"
<h1>{{ 5*6 }}</h1> output "30"
{% %} use this in html for multi-line code
Dynamically add url for server function:
<a href="{{url_for('get_blog', x=3)}}">
URL building/templating with Jinja in Flask
Use {{ }} to evaluate code in html
<h1>5*6</h1> output "5*6"
<h1>{{ 5*6 }}</h1> output "30"
{% %} use this in html for multi-line code
Dynamically add url for server function:
<a href="{{url_for('get_blog', x=3)}}">
Day 59 ✅
Created a blog site, added styles.
Moving header and footer out to separate files, then
{% include "header.html" %} in your pages
render_template("index.html", name=my_var)
Keep programming out of HTML if poss, and within .py/server files
Created a blog site, added styles.
Moving header and footer out to separate files, then
{% include "header.html" %} in your pages
render_template("index.html", name=my_var)
Keep programming out of HTML if poss, and within .py/server files
Day 60 ✅
Forms
HTML:
<form action="/login" method="POST">
<label>Email<\label>
<input type="text" name="email" id="email">
<input type="submit">
</form>
FLASK SERVER:
@ app.route('/login', methods=["GET," POST"])
if request.method="POST":
request.form.get('email')
Forms
HTML:
<form action="/login" method="POST">
<label>Email<\label>
<input type="text" name="email" id="email">
<input type="submit">
</form>
FLASK SERVER:
@ app.route('/login', methods=["GET," POST"])
if request.method="POST":
request.form.get('email')
Day 61 ✅
FLASK-WTF (WTForms)
Validators
StringField(..)
form.xx.data
form.xx.label
Template Inheritance
{% extends "base.html" %}
{% block content %}
{% endblock %}
Super Blocks
{% super() %}
{{ wtf.quick_forms(form) }}
{% import *bootstrap/wtf.html" as wtf %}
FLASK-WTF (WTForms)
Validators
StringField(..)
form.xx.data
form.xx.label
Template Inheritance
{% extends "base.html" %}
{% block content %}
{% endblock %}
Super Blocks
{% super() %}
{{ wtf.quick_forms(form) }}
{% import *bootstrap/wtf.html" as wtf %}
Day 62 ✅
More Flask, WTForms, Bootstrap & CSV
Read from CSV file, built a form page to add to the CSV, built table to display data.
Mostly reinforcing of existing learning, so long and difficult 🤯
“The greater the difficulty, the more glory in surmounting it."
- Epictetus
More Flask, WTForms, Bootstrap & CSV
Read from CSV file, built a form page to add to the CSV, built table to display data.
Mostly reinforcing of existing learning, so long and difficult 🤯
“The greater the difficulty, the more glory in surmounting it."
- Epictetus
Day 63 ✅
Databases with SQLite, SQLAlchemy, DB Browser
TABLE is like excel tab, FIELD is like column heading
Database relationships mapped to objects
my_list=db.session.query(X).all()
request.form('id')
request.args.get('id')
db.session.commit()
Book.query.filter_by(..)
Databases with SQLite, SQLAlchemy, DB Browser
TABLE is like excel tab, FIELD is like column heading
Database relationships mapped to objects
my_list=db.session.query(X).all()
request.form('id')
request.args.get('id')
db.session.commit()
Book.query.filter_by(..)
Day 65 ✅
Web Design School
Colour Theory🌈
Typography - Serif/sans-serif
Old v modern fonts
Font moods
Contrasts
UI Design - Hierarchy, Layout, Alignment, White Space, Audience
UX Design - Simplicity, Consistency, Reading Patterns, F & Z-Layout
@canva is cool, made this:
Web Design School
Colour Theory🌈
Typography - Serif/sans-serif
Old v modern fonts
Font moods
Contrasts
UI Design - Hierarchy, Layout, Alignment, White Space, Audience
UX Design - Simplicity, Consistency, Reading Patterns, F & Z-Layout
@canva is cool, made this:
Day 66 - Building API's
RESTful routing
API's return JSON not HTML, use jsonify()
Turn object to dictionary, then jsonify
POSTMAN to test API's. Send requests, auto-create the documentation, add args, can send as a form, etc
PUT v PATCH - replace part of an entry only
RESTful routing
API's return JSON not HTML, use jsonify()
Turn object to dictionary, then jsonify
POSTMAN to test API's. Send requests, auto-create the documentation, add args, can send as a form, etc
PUT v PATCH - replace part of an entry only
Day 67 ✅
Made an improved blog site, using a database.
Flask CKEditor package to make HTML content, & Jinja safe filter
Good practice of more Flask routing, database objects, WTForms, auto-populating forms
Now understand
.validate_on_request() vs request.method=="POST"
Made an improved blog site, using a database.
Flask CKEditor package to make HTML content, & Jinja safe filter
Good practice of more Flask routing, database objects, WTForms, auto-populating forms
Now understand
.validate_on_request() vs request.method=="POST"
Day 68 ✅
Authentication with Flask
Encryption & Hashing - Salting, Salt rounds
Keeping a user logged in
generate_password_hash()
send_from_directory()
current_user.is_authenticated
@ login_manager.user_loader
UserMixin
Flash messages
Horrible day, so hard...
Authentication with Flask
Encryption & Hashing - Salting, Salt rounds
Keeping a user logged in
generate_password_hash()
send_from_directory()
current_user.is_authenticated
@ login_manager.user_loader
UserMixin
Flash messages
Horrible day, so hard...
Day 70 ✅
Deploying my own website
Git, GitHub, Heroku hosting, gunicorn
Version control locally with git, git-bash
Working Directory->Staging Area->Local Repository->Remote Repository(GitHub)
Commit & Push
Rollback
Master branch
.gitignore
Postgres db
Amazing stuff! 😎
Deploying my own website
Git, GitHub, Heroku hosting, gunicorn
Version control locally with git, git-bash
Working Directory->Staging Area->Local Repository->Remote Repository(GitHub)
Commit & Push
Rollback
Master branch
.gitignore
Postgres db
Amazing stuff! 😎
Day 71 ✅
Data Exploration with Pandas & Google Colab
NaN- Not A Number
Clean data with df.dropna()
clean_df['<column>'].idxmax()
Get row with .loc[x]
Only prints last line unless wrap in print(..)
Subtract/insert/sort/mean() on columns
groupby() like pivot tables
Easy👍🏻
Data Exploration with Pandas & Google Colab
NaN- Not A Number
Clean data with df.dropna()
clean_df['<column>'].idxmax()
Get row with .loc[x]
Only prints last line unless wrap in print(..)
Subtract/insert/sort/mean() on columns
groupby() like pivot tables
Easy👍🏻
Day 76 ✅
NumPy and N-dimensional arrays
Pandas is built on top of NumPy
m1 @ m2 to multiply matrices
vector - 1D
matrix - 2D
tensor - 3D+
.ndim
.arange()
.flip()
.linspace()
img = Image.open(my_file)
img_array = np.array(img)
plt.imshow(img_array)
NumPy and N-dimensional arrays
Pandas is built on top of NumPy
m1 @ m2 to multiply matrices
vector - 1D
matrix - 2D
tensor - 3D+
.ndim
.arange()
.flip()
.linspace()
img = Image.open(my_file)
img_array = np.array(img)
plt.imshow(img_array)
Day 77 ✅
Seaborn Data Visualization
Filter on multiple conditions:
df.loc[(df.a>0) & (df.b !=0)]
Or .query()
sns.regplot() for linear regressions
scikit-learn
Create LinearRegression object
regression.fit(X,y)
Y-intercept .intercept_
Slope .coef
R-sqd .score(X,y)
Seaborn Data Visualization
Filter on multiple conditions:
df.loc[(df.a>0) & (df.b !=0)]
Or .query()
sns.regplot() for linear regressions
scikit-learn
Create LinearRegression object
regression.fit(X,y)
Y-intercept .intercept_
Slope .coef
R-sqd .score(X,y)
Day 89 ✅
Build a disappearing text app. If you stop typing for a few seconds, it vanishes!
Not too difficult, but spent time getting more comfortable with tkinter, listening for key presses, adding frames/widgets etc
Here's a better version than mine:
squibler.io
Build a disappearing text app. If you stop typing for a few seconds, it vanishes!
Not too difficult, but spent time getting more comfortable with tkinter, listening for key presses, adding frames/widgets etc
Here's a better version than mine:
squibler.io
Day 90 ✅
Turn PDFs into audio files
This was v cool and surprisingly easy...uses python libraries to rip text from a pdf, you turn that text into a string then either post to an audio API or run through a python engine
Turned some free Project Gutenberg 📙's into audiobooks
Turn PDFs into audio files
This was v cool and surprisingly easy...uses python libraries to rip text from a pdf, you turn that text into a string then either post to an audio API or run through a python engine
Turned some free Project Gutenberg 📙's into audiobooks
Day 96 ✅
Build an eCommerce site, with user login and ability to take real payments
Hit the wall here...so many things I really didn't know well enough meant this took a MONTH to get through 🙈
Used Stripe for payments & built a joke NFT/JPEG site 🤡
rightclicksave.herokuapp.com
Build an eCommerce site, with user login and ability to take real payments
Hit the wall here...so many things I really didn't know well enough meant this took a MONTH to get through 🙈
Used Stripe for payments & built a joke NFT/JPEG site 🤡
rightclicksave.herokuapp.com
Day 99 ✅
Analyze police shootings csv data
Was ok, maybe I'm getting the hang of it
👍🏻 setting index, sort, filtering, inverting, labelling, renaming, twin axes
👎🏻 rolling averages, date handling
Data from washingtonpost.com, but they have way prettier charts than me!
Analyze police shootings csv data
Was ok, maybe I'm getting the hang of it
👍🏻 setting index, sort, filtering, inverting, labelling, renaming, twin axes
👎🏻 rolling averages, date handling
Data from washingtonpost.com, but they have way prettier charts than me!
Day 100 ✅
Analyse US Youth Survey Earnings data:
nlsinfo.org
Running linear regressions on a large data set, checking coefficients & residuals. Extending that to Multivariable, using regr object to make predictions.
Took a while to get my head round this 🤯🤓😎
Analyse US Youth Survey Earnings data:
nlsinfo.org
Running linear regressions on a large data set, checking coefficients & residuals. Extending that to Multivariable, using regr object to make predictions.
Took a while to get my head round this 🤯🤓😎
Loading suggestions...