Python

up:: 05 Programming MOC

Resources to learn

Run in Terminal

python file.py

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

print(output) # 'console.log'
type(5) # → int – Shows the type
 
help(print) # -> Shows the documentation

Working with numbers

print(min(1, 2, 3)) # → 1
print(max(1, 2, 3)) # → 3
 
print(abs(32)) # → 32
print(abs(-32)) # → 32

Custom functions

Tip

It’s best practice to use docstrings unless you expect to throw away the code which is rare!

def least_difference (a, b, c):
	diff1 = abs(a - b)
	diff2 = abs(b - c)
	diff3 = abs(a - c)
	return min(diff1, diff2, diff3)
 
# You can define a 'docstring', a description of your function by wrapping it in three quotes
 
def least_difference (a, b, c):
"""Return the smallest difference between any two numbers
    among a, b and c.
    
    >>> least_difference(1, 5, -5)
    4
    """
    diff1 = abs(a - b)
	diff2 = abs(b - c)
	diff3 = abs(a - c)
	return min(diff1, diff2, diff3)
 

Booleans

In python, boolean value are capitalized

True
False

You can use the and and or keywords. It is best practice to wrap long logic into parentheses to improve legibility.

Lists

planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
 
planets[-1] # -> Last item on the list
 
# Slicing
planets[0:3] # -> ['Mercury', 'Venus', 'Earth']
planets[:3] # Assumes the start of the list
planets[3:] # Assumes the end of the list
 
# This can also be used with reassigning
planets[:3] = ['Hoth', 'Alderaan', 'Kamino']

Loop over a whole list

# normalise a whole list of documents
 
# iterates through indices (i) and elements (doc) of list (doc_list)
for i, doc in enumerate(doc_list):
	words = doc.split()
	normalized = [word.rstrip(',.').lower() for word in words]

List functions

# Length
len(planets) # -> 8
sorted(planets) # Alphabetical order
 
sum([1, 2, 3]) # -> 6

List methods

planets.append('Pluto')
planets.pop() # Removes and returns last element
planets.index('Earth') # -> 2
 
# Check if a list 'hasOwnProperty'
"Earth" in planets # -> True

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() return 4.

Tuples

t = (1, 2, 3)
  • 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

planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
for planet in planets:
	print(planet, end=' ')
  • Everything that is iterable can be looped over. Strings for example.

Using range()

for i in range(5):
	print("Doing important work. i =", i)

While loops

  • Iterate until a condition is met
i = 0
while i < 10:
	print(i, end=' ')
	i += 1

List comprehensions

  • A list built from a for loop.
squares = [n**2 for n in range(10)]
print(squares)
# -> [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

We can also add a condiditonal. This is similar to SQL’s (or DQL‘s) “WHERE”.

short_planets = [planet for planet in planets if len(planet) < 6]
print(short_planets)
# -> ['Venus', 'Earth', 'Mars']

It even supports conditional transformations:

loud_short_planets = [planet.upper() + "!" for planet in planets if len(planet) < 6]
print(loud_short_planets)
# -> ['VENUS!', 'EARTH!', 'MARS!']
 
# For clearer structure, this can also be written over three lines
[
 planet.upper() + '!'
 for planet in planets
 if len(planet) < 6
]

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 uppercase
  • string.lower() for lowercase
  • string.startswith("substring") and endwith()
  • 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.

"{}, you'll always be the {}th planet to me.".format(planet, position)
# -> "Pluto, you'll always be the 9th planet to me."

It can also refer back by index:

s = """The dress is {0}.
No, it's {1}.
{0}!
{1}!
 
""".format('blue and black', 'white and gold')

Read more at PyFormat: Using % and .format() for great good!.

Dictionaries

They correspond to JavaScript‘s objects.

numbers = {'one': 1, 'two': 2, 'three': 3}

Python has dictionary comprehensions, similar to list comprehensions.

planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
planet_to_initial ={planet: planet[0] for planet in planets}
planet_to_initial
 
# ->
# {'Mercury': 'M',
#  'Venus': 'V',
#  'Earth': 'E',
#  'Mars': 'M',
#  'Jupiter': 'J',
#  'Saturn': 'S',
#  'Uranus': 'U',
#  'Neptune': 'N'}

Loop over keys/values

for k in numbers:
	print("{} = {}".format(k, numbers[k]))
 

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)
# Import under an alias
import math as mt
mt.pi
 
# Import without prefix
# WARNING: this is considered bad practice (code can be hard to debug)
import math as *
print(pi)
 
# Import only specific things from each modle
from math import log, pi
from numpy import asarray

Working with unfamiliar objects

  1. type() (What is this thing?)
    • eg. type(roll)numpy.ndarray
  2. dir() (What can I do with it?)
    • print(dir(rolls)) → …astype', 'base', 'byteswap', 'choose', 'clip', 'compress'
  3. 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.