ArtisanTinkerer.github.io

Blog

View on GitHub

Data structures

Head First Python

Lists

movies = ["Terminator", "About Time"]

len(movies)
pop() # take one
append([item]) # add one 
extend([items,another]) # add multiple
remove(1)
insert(0,item)

Lists within lists

movies = ["Terminator",
  ["Linda","Arnie"]
]

print movies[0][2]

Checking Type

isinstance(movies,list)

Functions

def myfunction():
  print('great')

Loops:

for each movie in movies:
  print(movie)
  
while count < len (movies):
  print(movies[count])
  count = count+1

Modules of Functions - pg33

Just a file ending in .py PyPi

Prepare a distribution

  1. create a folder
  2. create setup.py (pip uses this?)
#range
x = range(6)
for n in x:
  print(n)

Optional arguments

def print_list(the_list, level=0)

File handling

try:

    data_file = open('sketch.txt')
    #print (data_file.readline(), end='') # end removes the default /n
    #data_file.seek(0) # rewind

    for each_line in data_file:
        try:
            (role, line_spoken) = each_line.split(':', 1)
            print(role, end='')
            print(' said: ', end='')
            print(line_spoken, end='')
        except ValueError:
            pass


    data_file.close()


except IOError:
    print("The file is missing")

print('page:101')

Writing Files

def using_with(): # file is automatically closed if you usr with
    try:
        with open('not.txt', "w") as data:
            print("It's ..", file=data)
    except IOError as err:
        print("file error: " + str(err))



def missing():
    try:
        data = open('nothere.txt')
    except IOError as err:
        print("file error" + str(err))
    finally:
        if 'data' in locals():
            data.close()


def write_file():
    try:
        out_file = open('out.txt', 'w') # a to append
        print('have I written to a file?',file=out_file)
        out_file.close()
    except IOError:
        print('File error.')
    finally: # we need to make sure that the file is closed if we get an error

        out_file.close()


Pickle


Python Crash Course

Concatenate

first + second

Adding Whitespace

\t tab \n new line

Trimming strings

```lstrip()```
```strip()```

## Data Types

### Numbers
**Decimals**
**Intergers**

Anything with a decimal point is a float.
Dividing intergers results in an integer answer. - To avoid, just make sure one number is a decimal.


### Lists

bikes = [‘trek’,’cannondale’]

bikes = [‘trek’, ‘cannondale’] print(bikes[0].title()) bikes.append(‘canyon’) bikes.insert(0,’canyon’) del bikes[0] opped = bikes.pop() bikes.remove(‘trek’) bikes.sort() print(sorted(bikes)) bikes.reverse() print(len(bikes)) print(bikes[-1]) # get the last element


### Loops

```