Python
up:: Programming ⚐
Resources to learn
- Free book on Python: Automate the boring stuff
- YouTube: Full Python Course
- Google for Education: Python
- Maggie Appleton:
- Kaggle’s Learn Python Tutorials + Intro to ML nailed it.
- Powered through in ~6 hours and now moving onto the infamous course.fast.ai Practical Deep Learning course for a deeper dive
Run in Terminal
Project ideas
- Todoist ML algo for me
- tag task with suggested
- Kindle price fetcher
- Library availability checker
- Books read gantt from .md file
- Timeblocking app
Built in functions
Working with numbers
Custom functions
Tip
It’s best practice to use docstrings unless you expect to throw away the code which is rare!
Booleans
In python, boolean value are capitalized
You can use the and
and or
keywords. It is best practice to wrap long logic into parentheses to improve legibility.
Lists
Loop over a whole list
List functions
List methods
Objects
Actually, everything in python is an object.
- Numbers – eg.
12.imag
to access the imaginary part
Methods
functions attached to an object are called methods.
- Eg. for numbers:
12.bit_length()
return4
.
Tuples
- Tuples are lists that are immutable (they cannot be modified).
- They are written with parentheses.
Tip
Tuples are often used to return multiple values from a function.
Loops
For loop
- Everything that is iterable can be looped over. Strings for example.
Using range()
While loops
- Iterate until a condition is met
List comprehensions
- A list built from a
for
loop.
We can also add a condiditonal. This is similar to SQL’s (or DQL‘s) “WHERE”.
It even supports conditional transformations:
In SQL analogy, this can be though of as SELECT, FROM and WHERE.
Strings
- Since strings are lists, we can also apply slicing.
"pluto"[-3:]
return'uto'
String methods
string.upper()
for uppercasestring.lower()
for lowercasestring.startswith("substring")
andendwith()
sentence.split()
– breaks by whitespace by default"-".join(["2022","05","17"])
– joins a list of strings with the string it was called on as a seperator
String format
Replaces the {}
placeholders with the strings passed in.
It can also refer back by index:
Read more at PyFormat: Using % and .format() for great good!.
Dictionaries
They correspond to JavaScript‘s objects.
Python has dictionary comprehensions, similar to list comprehensions.
Loop over keys/values
We can get all the keys or values with dict.keys
or dict.values
.
.items()
allows to iterate over the keys and values at the same time.
External libraries
- See all the names by using
dir()
, eg.dir(math)
Working with unfamiliar objects
type()
(What is this thing?)- eg.
type(roll)
→numpy.ndarray
- eg.
dir()
(What can I do with it?)print(dir(rolls))
→ …astype', 'base', 'byteswap', 'choose', 'clip', 'compress'
…
help()
(Tell me more)
Operator overloading
Libraries may modify the default behaviour of what python does. In ‘vanilla’ python, you can +
to a list, in numpy
you can.