In [ ]:
#Python notebook highlighting some topics discussed in http://www.slideshare.net/MattHarrison4/learn-90

In [1]:
welcome_message = "hello, hubpy!"
dir(welcome_message)


Out[1]:
['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__getnewargs__',
 '__getslice__',
 '__gt__',
 '__hash__',
 '__init__',
 '__le__',
 '__len__',
 '__lt__',
 '__mod__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rmod__',
 '__rmul__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '_formatter_field_name_split',
 '_formatter_parser',
 'capitalize',
 'center',
 'count',
 'decode',
 'encode',
 'endswith',
 'expandtabs',
 'find',
 'format',
 'index',
 'isalnum',
 'isalpha',
 'isdigit',
 'islower',
 'isspace',
 'istitle',
 'isupper',
 'join',
 'ljust',
 'lower',
 'lstrip',
 'partition',
 'replace',
 'rfind',
 'rindex',
 'rjust',
 'rpartition',
 'rsplit',
 'rstrip',
 'split',
 'splitlines',
 'startswith',
 'strip',
 'swapcase',
 'title',
 'translate',
 'upper',
 'zfill']

In [2]:
import requests
help(requests)


Help on package requests:

NAME
    requests

FILE
    /Users/corbinbs/anaconda/envs/hubpy/lib/python2.7/site-packages/requests/__init__.py

DESCRIPTION
    requests HTTP library
    ~~~~~~~~~~~~~~~~~~~~~
    
    Requests is an HTTP library, written in Python, for human beings. Basic GET
    usage:
    
       >>> import requests
       >>> r = requests.get('http://python.org')
       >>> r.status_code
       200
       >>> 'Python is a programming language' in r.content
       True
    
    ... or POST:
    
       >>> payload = dict(key1='value1', key2='value2')
       >>> r = requests.post("http://httpbin.org/post", data=payload)
       >>> print r.text
       {
         ...
         "form": {
           "key2": "value2",
           "key1": "value1"
         },
         ...
       }
    
    The other HTTP methods are supported - see `requests.api`. Full documentation
    is at <http://python-requests.org>.
    
    :copyright: (c) 2013 by Kenneth Reitz.
    :license: Apache 2.0, see LICENSE for more details.

PACKAGE CONTENTS
    adapters
    api
    auth
    certs
    compat
    cookies
    exceptions
    hooks
    models
    packages (package)
    sessions
    status_codes
    structures
    utils

DATA
    __author__ = 'Kenneth Reitz'
    __build__ = 66051
    __copyright__ = 'Copyright 2013 Kenneth Reitz'
    __license__ = 'Apache 2.0'
    __title__ = 'requests'
    __version__ = '1.2.3'
    codes = <lookup 'status_codes'>

VERSION
    1.2.3

AUTHOR
    Kenneth Reitz



In [3]:
print "hello, hubpy!"
print("hello, hubpy!")   #In python 3, print is a function - not a statement


hello, hubpy!
hello, hubpy!

In [4]:
#watch the whitespace!
for i in range(10):
    print(i)


0
1
2
3
4
5
6
7
8
9

In [5]:
#everything in python is an object
x = 10
id(x)


Out[5]:
4298181472

In [6]:
x


Out[6]:
10

In [7]:
#mutable
people = []
print(id(people))
people.append('brian')
people.append('andrew')
print(id(people))
print(people)


4348212576
4348212576
['brian', 'andrew']

In [8]:
#immutable
value = 10
print(id(value))
value = value + 12
print(id(value))


4298181472
4298181184

In [10]:
x = 4
y = 13.985
x = "I'm a string"
message = """ I'm a big ole 
multiline string.  Really useful for 
small templates or blocks of text"""
#See PEP8 for all things naming and spacing related.  When in doubt, do it like PEP8 -> http://www.python.org/dev/peps/pep-0008/

In [11]:
message


Out[11]:
" I'm a big ole \nmultiline string.  Really useful for \nsmall templates or blocks of text"

In [12]:
y


Out[12]:
13.985

In [13]:
y = "change up"

In [14]:
y


Out[14]:
'change up'

In [15]:
#integer division heads up
3/4


Out[15]:
0

In [17]:
3/int(4.0)


Out[17]:
0

In [18]:
#Long integers (see the 'L' on the end...)
10**100


Out[18]:
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000L

In [19]:
single_quotes_str = 'welcome to hubpy'
double_quotes_str = "welcome to hubpy"
multi_line_str = """
welcome
to
hubpy"""

In [20]:
"{0}, {1}!".format(single_quotes_str, 'Brian')


Out[20]:
'welcome to hubpy, Brian!'

In [21]:
'%s, %s!' % (single_quotes_str, 'Brian')


Out[21]:
'welcome to hubpy, Brian!'

In [22]:
#if you need to assign 'no value' to something - like null in other languages
value = None

In [23]:
if value:
    print(value)

In [24]:
value = 1

In [25]:
if value:
    print(value)


1

In [26]:
if value is not None:
    print('awesome')


awesome

In [27]:
a = True
b = False

In [28]:
a


Out[28]:
True

In [29]:
if a:
    print('a is True!')


a is True!

In [30]:
my_list = [1, 3, 'bob', 34.6]  #mutable
a_tuple = (1, 3, 'bob', 34.6)  #immutable

In [31]:
a_tuple


Out[31]:
(1, 3, 'bob', 34.6)

In [32]:
my_list


Out[32]:
[1, 3, 'bob', 34.6]

In [33]:
'bob' in my_list


Out[33]:
True

In [34]:
'bob' in a_tuple


Out[34]:
True

In [35]:
some_numbers = [3, 2, 4, 6, 8, 9]

In [36]:
some_numbers


Out[36]:
[3, 2, 4, 6, 8, 9]

In [37]:
some_numbers.sort() #in place sort

In [38]:
some_numbers


Out[38]:
[2, 3, 4, 6, 8, 9]

In [39]:
some_numbers.insert(0, 1)

In [40]:
some_numbers


Out[40]:
[1, 2, 3, 4, 6, 8, 9]

In [41]:
some_numbers.append(10)

In [42]:
some_numbers


Out[42]:
[1, 2, 3, 4, 6, 8, 9, 10]

In [43]:
help(some_numbers.insert)


Help on built-in function insert:

insert(...)
    L.insert(index, object) -- insert object before index


In [44]:
more_numbers = [11, 15, 19, 20]
some_numbers + more_numbers


Out[44]:
[1, 2, 3, 4, 6, 8, 9, 10, 11, 15, 19, 20]

In [45]:
dir(some_numbers)


Out[45]:
['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__delitem__',
 '__delslice__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__getslice__',
 '__gt__',
 '__hash__',
 '__iadd__',
 '__imul__',
 '__init__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__reversed__',
 '__rmul__',
 '__setattr__',
 '__setitem__',
 '__setslice__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'append',
 'count',
 'extend',
 'index',
 'insert',
 'pop',
 'remove',
 'reverse',
 'sort']

In [46]:
#dictionary keys must be immutable
scores = {'brian': 0, 'bob': 90, 'jane': 100}

In [47]:
scores


Out[47]:
{'bob': 90, 'brian': 0, 'jane': 100}

In [48]:
scores['bob']


Out[48]:
90

In [49]:
scores.values()


Out[49]:
[100, 0, 90]

In [50]:
scores.keys()


Out[50]:
['jane', 'brian', 'bob']

In [51]:
scores['andy'] = 85

In [52]:
scores


Out[52]:
{'andy': 85, 'bob': 90, 'brian': 0, 'jane': 100}

In [53]:
'brian' in scores


Out[53]:
True

In [54]:
scores.get('brian', 50)


Out[54]:
0

In [55]:
scores.get('billy', 50)


Out[55]:
50

In [56]:
del scores['brian']

In [57]:
scores


Out[57]:
{'andy': 85, 'bob': 90, 'jane': 100}

In [58]:
try:
    scores['brian']
except:
    print("BOOM")
else:
    print('yeah')


---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-58-c20d48f4f473> in <module>()
----> 1 scores['brian']

KeyError: 'brian'

In [62]:
def basic_math(number):
    """a simple function to do very basic math"""
    return number + 36

In [61]:
basic_math(10)


Out[61]:
46

In [63]:
help(basic_math)


Help on function basic_math in module __main__:

basic_math(number)
    a simple function to do very basic math


In [64]:
#functions are objects too
def function_fun(number, func):
    """apply function 'func' to the specified number"""
    return func(number)

In [65]:
function_fun(10, basic_math)


Out[65]:
46

In [66]:
if scores['bob'] > 90:
    print('A')
elif scores['bob'] > 80:
    print('B')
elif scores['bob'] > 70:
    print('C')
else:
    print('D')


B

In [67]:
if 85 < scores['bob'] < 95:
    print('yes!')


yes!

In [68]:
for name in scores.keys():
    print(name)


jane
bob
andy

In [69]:
for index, name in enumerate(scores.keys()):
    print('index: {0}, name: {1}'.format(index, name))


index: 0, name: jane
index: 1, name: bob
index: 2, name: andy

In [70]:
for name, score in scores.items():
    print('name: {0}, score: {1}'.format(name, score))


name: jane, score: 100
name: bob, score: 90
name: andy, score: 85

In [71]:
scores.keys()[1]


Out[71]:
'bob'

In [72]:
scores.keys()


Out[72]:
['jane', 'bob', 'andy']

In [73]:
scores.keys()[0:2]


Out[73]:
['jane', 'bob']

In [74]:
scores.keys()[-1]


Out[74]:
'andy'

In [75]:
scores.keys()[len(scores.keys())-1]


Out[75]:
'andy'

In [ ]: