Python miscellaneous

mylist=list() #make a list
mylist.append('coffee') #add an item
mylist  #shows the list
mydictionary=dict() #make a dictionary
mydictionary["Anna"]="999"` #adds name (as the key) and number
mydictionary["Anna"]` #prints the number
for key in mydictionary:
  print(key) #prints name
  print(mydictionary[key]) #prints number

ipynb - convert to html

jupyter nbconvert --to html NOTEBOOK-NAME.ipynb

self and init

jupyter notebook

recursive function

Collatz sequence:

jupyter notebook

With global variables:

jupyter notebook

Interact with the shell

import os
os.system('ls')
import subprocess

#list files in the current directory:
listfilesnow = subprocess.run(['ls'])

#save as a variable
listfiles = subprocess.run(['ls'], stdout=subprocess.PIPE)

#access the output
listfiles.stdout

#give the output a name
myfiles = listfiles.stdout

True and false

to test:

bool(0)
bool(5)
bool("") 

Remove spaces

mystring='   some text here   '
mystring
mystring.strip() #removes all leading/trailing whitespaces
mystring.rstrip() #just trailing whitespaces
mystring.lstrip() #just leading whitespaces
nextstring='000 more text 000'
nextstring.strip("0") #removes 0s