Skip to content

Python Learning 👷🏼‍♂️👷🏼‍♀️

operators

** -> raise to the power e.g.

2**8 = 256
powers_of_two = [2**value for value in range(0,9)]

Built In Functions

dir(__builtins__)  # shows all the builtin functions (and other stuff, eg., errors)
dir(list) # shows all the methods that apply to lists

Common builtin functions

  • type(object) -> the object's type
  • str(object) -> returns a nice string representation of the object

  • len

  • int
  • input
  • chr
  • abs
  • bool

Looping

for x in range(0,3):
for x in range(0,8,2):

Lists

index, +ve index from start, -ve index from end (-1 = last item only) slicing [start:stop:step] (excludes upper bound - e.g. stop isn't included) valid options:- [:] , [4:] , [:5] , [-3:] , [:-5]

[x for x in ...] - list generator

Can chain slices together e.g. "Hello!"[-3][1] -> returns 'o' [-3] returns "lo!" and then "lo!"[1] returns "o"


Exceptions

>>> import traceback, sys
>>> def grail(x):
...    raise TypeError('already got one')
... >>> try:
...       grail('arthur')
...    except:
...       exc_info = sys.exc_info()
...       print(exc_info[0])
...       print(exc_info[1])
...       traceback.print_tb(exc_info[2])
...
<class 'TypeError'>
  already got one
   File "<stdin>", line 2, in <module>
   File "<stdin>", line 2, in grail

os module

os.getpid() os.getcwd() os.chdir('/Users/Me')

Portability constants

os.pathsep, os.sep, os.pardir, os.curdir, os.linesep

Basic file & path functions

os.path.isdir('path name') os.path.isfile('path name') os.path.exists os.path.getsize('path name') os.path.split('path name') # separates filename from its path os.path.dirname os.path.basename os.path.split.ext os.path.join - puts dirname and basename back together in the proper format

os.path.normpath('path name') - returns the normal path (in case separators get mixed up, e.g. \ and /)

os.path.abspath() - returns the absolute path e.g. os.path.abspath('.') - returns the same as os.path.cwd os.path.abspath('') - considered same as '.' os.path.abspath('..') - returns absolute path to parent folder

Shell Commands

os.system('shell command here') e.g. os.system('ls -la')

Will wait for the command to return. To run the command in it's own process use:-

os command
windows os.system('run shell command')
linux/mac os.system("shell command &')

os.popen('shell command') takes the output of the shell command and runs it through a pipe or io stream e.g. the following takes the output from ls -la and passes it to text.

text = os.popen('ls -la').read()  

Shell Commands - Subprocess module

import subprocess

subprocess.call('python helloworld.py) # like os.system, but returns the return code as well

>>> pipe = subprocess.Popen('python helloshell.py', stdout=subprocess.PIPE)
>>> pipe.communicate()
(b'The Meaning of Life\r\n', None)
>>> pipe.returncode
0

Impractical Python

Ch1. pylint

pip install pylint

pylint filename.py  # linux

python -m pylint filename.py  #Windows
pylint -rn # no reports
pylint --max_line_length=79