Stories are everywhere. They've been an integral part of human societies for ever. There’s a reason for it.
Stories engage. They tap into emotions. They convey messages better than raw facts. They lower a reader’s cognitive load, helping them understand better and recall what
What's an image made of?
There are many correct answers.
But the most fascinating one is: << sines & cosines >>
Read on if you're intrigued👇🧵🪡
#python
#images
#fourier
I know many schools are using The Python Coding Book and its tutorials for teaching Python
Although this content was written with adult learners in mind, a lot of the work I do daily involves teaching kids, so glad to see schools use this resource
Some highlights 👇
Are `a = []` and `a = list()` the same?
How about `a = a[::-1]` and `a.reverse()`?
Let's look as some list operations to see whether they're the same or not…
Read more…
👇🪡🧵
#python
#programming
/1
Object-Oriented Python at the Hogwarts School of Codecraft and Algorithmancy
---
Year 5:
Inheritance
---
The students are growing up! This Year they'll learn about a key property of OOP - how to create a class that inherits from another one
Here's the code so far
/1
#Matplotlib
is not just for displaying data…
…here I use it for a fun simulation of planets orbiting a sun (or many suns, see next tweet)
Here's the article if you're looking for a step-by-step tutorial:
#python
#planets
@matplotlib
So, you've never accessed data over the internet using an API and don't know where to start?
Start with the simplest option…
The World Bank site has some free data with an easy to use API
Here's an example using the `requests` library
👇🪡🧵
The way Python deals with variables is different from some other languages. You may even have heard some say they're not technically variables
Let's visualise what's happening when you create a name in Python and assign data to it with The Box and Label analogy
/1
A small headache for learners is knowing how to format their code
In Python, some of this matters as it's part of the syntax
But other aspects of formatting are linked to style rather than syntax and can confuse those learning to code
Let's dive further into this
/1
Day 8 in the Python functions series
Yesterday we saw the "rogue" forward slash in the function definition. Today, it's the "rogue" asterisk or star *
def greet(host, *, guest):
Let's look at keyword-only arguments today
/1
Back to basics: what do sine and cosine really mean?
This is a mini-project using turtle I do with secondary school children who have learnt about sines and cosines but don't **really** know what they are.
I'm debating whether to write this as a…
#python
#coding
1/
One of the most underrated
#Python
modules?
`turtle`
We know it's used for teaching & not in the "real-world"
But it's usually used only for basic drawings & simple animations for kids–a very limited scope
We can teach more advanced topics, too…
Here are some examples…
/1
Let's write this game in 20 tweets…
Yes, just 20
Ready?
Go…
• Balls appear in random positions every few seconds and are tossed upwards with random velocities
• Click close to the ball to "bat it up"
• How long until you lose 10 balls?
/1
In what situations is NumPy faster than vanilla Python?
Short answer: if you want to perform the same operation on each item in a sequence, it's likely NumPy will be faster
Let's look at an example in which we compare using lists with append, list comprehensions, and NumPy
/1
Day 4 in the Python functions series is all about:
*args
It's not as difficult or as weird as you may think
Let's dive in and find out more
Here's the example we'll start with…
<code in ALT text>
/1
Functions in Python—easy or hard to learn & master?
This week I'll look at aspects of functions which can be tricky for those who know basics and want to move to next level
Let's start with the unexciting but important—terms
• define
• call
• parameter
• argument
1/
Do you always use the square brackets notation to get a value out of a Python dictionary?
This is often fine and convenient, but there's an alternative with a difference – the `get()` method
Here's an example in the code snippet
Let's go through each one…
/1
Object-Oriented Python at the Hogwarts School of Codecraft and Algorithmancy
---
Year 6:
Special Methods (aka Dunder Methods)
---
It's Year 6. Students will dive deeper into what's happening inside classes. This Year focusses on special methods
Here are our classes so far
1/
An image is made up of pixels. Sure…
But let's look at a different set of building blocks which make up an image
Claim: An image, like the one on the left, can be made up of building blocks that look like the wave-y pattern on the right
Read on to be convinced…
/1
Yesterday, I talked about the `for...else` loop in Python
The `else` clause can also be used with a `while` loop
Let's look at a short example which uses a `while...else` loop
/1
In the early days of learning to code in Python, you learn about data types and data structures…
…but you also hear lots of other terms such as
• sequence
• container
• iterable
• mutable and immutable
and more terms…
You _could_ learn all the definitions…
👇🪡🧵
1/
Day 6 of the Python functions series:
• more on *args & **kwargs
In this thread, we'll look at functions with some combination of "normal" positional arguments, *args, and **kwargs
Let's start with this example
–> What do you think the output will be?
<code in ALT text>
/1
Why should I care whether something is mutable or immutable?"
Often, beginners can see these distinctions as unimportant.
But that's the difference between thinking this behaviour is an error or that it makes perfect sense — see code attached
👇🪡🧵
#python
/1
Day 2 of diving into Python functions—today we'll look at:
• positional arguments
• named (or keyword) arguments
I don't have a preference on which term to use for the latter!
Here's a simple function
—>Which of the five function calls will not work?
<code in ALT text>
1/
You know about the `for` loop, I know.
But do you?
Are you sure?
Let's break the `for` loop down to see what's happening just a bit underneath the surface
Read on…
👇🪡🧵
#Python
/1
What Python data type would [a multi-storey car park] be?
–––
You drive into a multi-storey car park, find a spot to park, and then you ask yourself: "what data structure would best represent this car park", of course
Let's explore
1/
Do you know anyone who's looking to learn to code?
Maybe _you_ are?
Maybe you've tried in the past but gave up?
You may want to give a try – it's a different type of learn-to-code book, focusing on being friendly, accessible yet still very thorough…
`is`, `==`, and the £5 note in your pocket
You've read about how `is` and `==` are not the same thing.
But perhaps, you still find the concept a bit confusing.
So, here we go.
Read on
👇🪡🧵
#Python
/1
Object-Oriented Python at the Hogwarts School of Codecraft and Algorithmancy
---
Year 4:
More interaction between classes
---
Year 3 was a busy year. Here's were we left in Year 3
/1
Object-Oriented Python at the Hogwarts School of Codecraft and Algorithmancy
---
Year 3:
Defining Methods
---
Students are no longer fresh-faced first years, but there's still a lot to learn. Real stuff starts this Year as they learn to define methods to add functionality
/1
Object-Oriented Python at the Hogwarts School of Codecraft and Algorithmancy
---
Year 7:
Final Year (Class Methods | Static Methods)
---
Students are taller than most professors now–what a change from Year 1! But there's still one Year to go before graduating from Hogwarts
1/
Day 7 in the Python functions series
Have you ever seen a "rogue" forward slash / in a function signature when reading documentation?
Like this one?
def greet_person(person, /, repeat):
Let's talk about positional-only arguments today…
/1
Another feature of the `for` loop that many beginners are surprised to see is the `else` clause
Let's assume you want to find the first palindrome in a list of names:
names = ["James", "Anna", "Mark", "Kevin", "Kate"]
1/
Why Light Mode is better than Dark Mode (for me) — the science
Often there are discussions about dark move vs. light mode preference…
I prefer light mode and I have a reason why — here's a mini experiment and a summary of the science…
👇🪡🧵
#darkmode
#programming
/1
Over the past 2 weeks I published a 7-day series on classes & OOP
I knew I couldn't talk about everything, but I also wanted to make it reasonably (!) comprehensive
Here are all the threads, from Year 1 to 7 at Hogwarts School of Codecraft and Algorithmancy
It's long
0 of 7
Object-Oriented Python at the Hogwarts School of Codecraft and Algorithmancy
---
Year 1:
Mindset
---
Students join the school, are sorted into houses, and start learning about what's different in object-oriented programming (OOP) compared to the programming they already know
1/
Have you used `subplot_mosaic()` in Matplotlib yet?
Or are you a dinosaur like me and still used older functions? After all, `subplot_mosaic()` was only introduced in 2020 in version 3.3
Today, I decided to finally explore `subplot_mosaic()`
👇🪡🧵
@matplotlib
/1
The friendly, relaxed,
#Python
book
It's a textbook, but don't call it a textbook, it doesn't like it.
And it's free, by the way. Did I mention that?
Do you want to
#LearnToCode
?
Give it a try an tell me what you think…
---
#programming
Matplotlib has two alternatives to create plots and figures.
This can be confusing for beginners…
…from a beginner's perspective, it's best if there's only one way of doing things.
Read on
👇🪡🧵
#python
#matplotlib
/1
Let's have a quick look at the unpacking operator * in Python
Let's assume you have a name with all the middle names but you only want to keep the first and last names:
👇🪡🧵
1/
One of the first things you learn when learning coding in
#Python
is how to define functions.
Then you start digging deeper, and you'll need to master how to use optional arguments in functions.
Here's my
@realpython
article about optional arguments:
The Data Structure Category Series is now complete with 7 days of posts plus one bonus mid-series interlude
Here are all the threads linked in one place, and the visual summary, too
See replies for link to each Day's thread…
1/
There are a few million ways to read a CSV file in Python, more or less
Sometimes, the simple solution is all you need
import csv
with open("some_file.csv") as file:
contents = csv.reader(file)
for row in contents:
print(row)
Here's a question you know the answer to:
"How does a Python `for` loop work?"
"What a silly question", I can hear you think. But, do you _really_ know what's happening behind the scenes?
Let's have a look at iterables, iterators, and the `for` loop…
/1
f-strings?
fantastic-strings
formidable-strings
fancy-strings
fabulous-strings
Let's look at a number of ways we can deal with strings in Python
(Spoiler alert: f-strings are the best—did you get the clues that I quite like f-strings? Or was I too subtle?!)
/1
When you need to loop through items in a list and also keep track of an index, you don't need to do this 'manually'…
…here's where `enumerate()` comes in useful
👇🪡🧵
1/
What Python data type would [a row of houses] be?
–––
Let's look at a residential street with terraced houses
I'll call the "object" `row` for row of houses
And let's start looking at some properties we want to check for
First: can we go from one house to another in order?
/1
Need to extract the first and last item from a Python string or list, say?
Here's one way of doing it in a single line…
>>> first, *_, last = "Stephen"
>>> first
'S'
>>> last
'n'
>>> first, *_, last = [12, 3, 5, 13, 99, 0]
>>> first
12
>>> last
0
Day 12 on Python Functions:
• Docstrings
Here's something that won't affect how Python treats your functions…
…but will affect how other people (and your future self) will
Here's the example we'll use here:
<code in ALT text>
1/
Day 3 on Python Functions. Today it's the turn for:
• optional arguments / default values
Let's build on the same function used in Days 1 and 2. One of these options raises an error
—> I bet you know which one?
<Code in ALT text>
/1
When you first start using NumPy arrays, it's easy to think they're similar to lists…
…and there are similarities. But there are also differences
Let's look at one difference with indexing…
1/
Time for a quick intro to new and old friends…
I'm Stephen, but you know that already.
On my feed you can expect:
<✅> General Python
<✅> NumPy & Matplotlib
<✅> turtle projects (but not the boring ones)
<✅> Scientific programming
<✅> A dry sense of humour, at times
…
1/
Who said the `turtle` module in Python is there just to draw boring squares and circles?
Here's one of the (many) Christmas-themed animations I have - I'll share more in the lead-up to Christmas…
To finish off the series of lesser-known tools in Python loops, here's the `continue` keyword
We'll look at a very simple example to demonstrate how this keyword works
/1
Day 2 on NumPy indexing…
Yesterday, we saw some differences between indexing lists and NumPy arrays
NumPy arrays provide more options, such as using two indices within the same pair of square brackets, as we saw yesterday
Let's dive a bit deeper today with more dimensions
/1
What happens when you reverse a `range` object in Python?
A range object is a sequence. This means it is:
• An iterable
• A container
• A sized object (it has a length)
• Indexed using an integer
It also means it can be reversed as all sequences are reversible
/1
A few days ago I posted a "countdown to Christmas" code. Here's the updated version…
This should work before, on, and after Christmas day…
See below for a brief walk through…
<code in ALT text>
/1
Let's talk about nothing today…
…no I mean it. Let's talk about Python's `None`
It's a confusing concept for beginners and it pops up in "unexpected" places, until you know to expect it there…
Ok, let's add some substance to nothingness…
/1
––– Mid-Series Roundup (Day 5.5) –––
Let's review the terms we've seen so far but in a different order to how I presented them in this series
Let's start with three “top-level” categories:
• Iterable
• Container
• Sized
1/
Sometimes, all you need is a Named Tuple
Choosing the right data structure can be tricky. Should you create a class? Maybe a list or tuple? A dictionary? Or dataclass?
All have their own place, but sometimes, the oft forgotten named tuple is all you need
👇🪡🧵
1/
Slicing: A Short Story
**Now Streaming**
---
Season 1: Going forward
Main character: a list called `numbers` with values which match the indices (easier to follow the story)
But other sequences could be used for this role…
Synopsis: Main character explores slicing
1/
If you've seen this you know it.
If you haven't, probably you don't.
There are patterns that become really easy once you know them but are not immediately obvious.
Here's a common issue with lists and loops.
Which
#programming
language, if any, will be left out?
#Python
Let's look at a special method that's reasonably well-known, and its cousin that may be less well-known
Let's start with `__add__()` and let's look at how it works in this demo example of an `Article` class
/1
This remains one of the most fascinating lines in Python, in my view
What's the output?
Once you have an thought of an answer, read the rest of this thread
/1
Another f-string format specifier I had never used until researching my latest article was the 'n' type.
I had to virtually travel to another country, though, to see it in action:
When beginners think they know everything there is to know about the `for` loop, here comes looping through dictionaries.
It can take a bit of re-learning to master looping through dictionaries.
Let's look at an example…
1/
If you're looking for a fun yet challenging project to play with NumPy 2D arrays and images and, yes, the best topic maths has to offer…
…here's this evergreen tutorial – consistently the most-popular of the articles on the The Python Coding Book blog:
Do you often find yourself importing math to use math.sqrt(number)?
Save yourself an import and just go for number ** 0.5
It might even be a bit faster in some situations (and to some, yes, less readable)
#python
#math
#maths
#coding
#codenewbie
A thread on Python names, objects and reference counts
If you're an intermediate-ish Python learner, you've probably ignored this stuff until now.
But maybe, you're starting to get a bit curious.
Let's explore a bit
👇🪡🧵
1/
More Animated Christmas Cards using Python's `turtle` module
Earlier this week, I posted a particularly complex animation
Today, a slightly simpler one, although there's still al lot happening in the code…
Understanding how colour images are represented is easier with small arrays
Here's a 10 x 10 x 3 array. Picture a 2D array with 10 rows and 10 columns (that's 100 pixels)
Now take three of those 10 x 10 arrays and stack them on each other
/1
In today's final session of 'The Python Coding Programme', the discussion led us to imagine what "append" would look like from a functional programming perspective, so we wrote this…
What other options do we have?
Aim was to use immutable types, hence never change object
One last step-by-step `turtle` animation for the year. Let's build this Spinning Globe Dots animation (surely, there's a better name for it)
I'll do this in an old-fashioned thread which works better for a step-by-step approach, I think.
Here's the animation…
1/
Day 13 – Final Day – of the Intermediate Python Series
We'll keep this very short and sweet – a couple of best practices when writing functions
1. Start the function name with a verb
2. Write functions that only do one thing
1/
A common pitfall early on in the Python learning journey
This does _not_ create a copy of the list `numbers`
Let's see what it does and what to do to create a copy
/1
Why is Python the ideal language for beginners to learn?
Let's look at the main reasons:
• It's more accessible for a beginner, allowing you to focus on programming concepts and not language detail. Too many give up coding early on–Python makes this less likely
cont/d…
/1
Day 10 of the Python Functions Series. Let's talk about type hinting today, or just "typing"
I'll use an example I've used earlier in the series but add type hints to it
—> Will both of these function calls work or will any raise an error?
<code in ALT text>
/1