In [2]:
ls


LICENSE                    data1.txt                  simple_for_loop.sh*
Python Introduction.ipynb  generate_data.sh           simple_for_loop.sh~*
README.md                  generate_data.sh~

In [3]:
# Simple arithmetic
3./5


Out[3]:
0.6

In [4]:
# Print to stdout
print 'We are learning python!'


We are learning python!

In [5]:
print 1+1


2

In [6]:
id(1)


Out[6]:
4299230104

In [7]:
id(1)


Out[7]:
4299230104

In [8]:
type(1)


Out[8]:
int

In [9]:
type('We are learning...')


Out[9]:
str

In [10]:
x = 1

In [11]:
x.conjugate()


Out[11]:
1

In [12]:
x.numerator


Out[12]:
1

In [13]:
x = 1./2.

In [14]:
x.is_integer()


Out[14]:
False

In [15]:
# Use dir to see associated methods for an object

In [16]:
# Use the help method
x


Out[16]:
0.5

In [17]:
# Python variables: names that point to objects
# strings, floats, integers

In [18]:
y = 'x'

In [19]:
print y


x

In [20]:
y = '1'

In [21]:
float(y)


Out[21]:
1.0

In [22]:
int(y)


Out[22]:
1

In [23]:
y


Out[23]:
'1'

In [24]:
x.is_integer()


Out[24]:
False

In [25]:
#  Assert statement
assert( x <1)
assert(not x.is_integer())

In [26]:
x > 1


Out[26]:
False

In [27]:
x == .5


Out[27]:
True

In [28]:
z = None

In [29]:
# Control flow
x = 100
while x > 1 : 
    print x
    x -= 10


100
90
80
70
60
50
40
30
20
10

In [30]:
if x > 1 :
    print x

In [31]:
# Break statement
x = 2
while x > 1 : 
    print x
    x += 1
    if x > 10 :
        break


2
3
4
5
6
7
8
9
10

In [32]:
# For loop 
for x in range(1, 10, 2) :
    print x


1
3
5
7
9

In [33]:
# if/ elif / else statements
x = 1
if x > 1 :
    print 'x is bigger!'
elif x < 1 :
    print 'x is smaller!'
else :
    print x


1

In [34]:
# Data types
list1 = [x,'Not an integer',y]

In [35]:
for i in list1 :
    print i


1
Not an integer
1

In [36]:
list2 = [range(1,3),0.5]

In [37]:
majorlist = list1+list2

In [38]:
# Can iterate over items in a list
for list in majorlist :
    print list


1
Not an integer
1
[1, 2]
0.5

In [39]:
type(majorlist)


Out[39]:
list

In [40]:
# List slicing
majorlist[1:3]
tailofmajorlist = majorlist[3:]

In [41]:
tailofmajorlist


Out[41]:
[[1, 2], 0.5]

In [42]:
tailofmajorlist[0][1]


Out[42]:
2

In [43]:
# Dictionaries
dict1 = {'key1':tailofmajorlist,'key2':majorlist}

In [44]:
print dict1['key1'], dict1['key2']


[[1, 2], 0.5] [1, 'Not an integer', '1', [1, 2], 0.5]

In [45]:
dict1.keys()


Out[45]:
['key2', 'key1']

In [46]:
for key in dict1.keys() : 
    print key
    print dict1[key]


key2
[1, 'Not an integer', '1', [1, 2], 0.5]
key1
[[1, 2], 0.5]

In [47]:
for key, value in dict1.iteritems() :
    print key
    print value


key2
[1, 'Not an integer', '1', [1, 2], 0.5]
key1
[[1, 2], 0.5]

In [48]:
# Tuples
tup1 = (1,0)

In [49]:
type(tup1)


Out[49]:
tuple

In [50]:
tup2 = (2,3)

In [51]:
tup1 + tup2


Out[51]:
(1, 0, 2, 3)

In [52]:
tup1*2


Out[52]:
(1, 0, 1, 0)

In [53]:
list1*2


Out[53]:
[1, 'Not an integer', '1', 1, 'Not an integer', '1']

In [54]:
str2 = 'I am a string'*2

In [55]:
# Strings are iterable too!
for s in str2 :
    print s


I
 
a
m
 
a
 
s
t
r
i
n
g
I
 
a
m
 
a
 
s
t
r
i
n
g

In [56]:
str2[:5]


Out[56]:
'I am '

In [57]:
# Access tuple elements
tup1[1]


Out[57]:
0

In [58]:
list1.append(5)

In [59]:
list1


Out[59]:
[1, 'Not an integer', '1', 5]

In [60]:
len(list1)


Out[60]:
4

In [61]:
tup1.index(5)


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-61-5ce4d29e87ac> in <module>()
----> 1 tup1.index(5)

ValueError: tuple.index(x): x not in tuple

In [62]:
tup1


Out[62]:
(1, 0)

In [67]:
dir(tuple)


Out[67]:
['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__getnewargs__',
 '__getslice__',
 '__gt__',
 '__hash__',
 '__init__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rmul__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'count',
 'index']

In [68]:
help(tuple.count)


Help on method_descriptor:

count(...)
    T.count(value) -> integer -- return number of occurrences of value


In [70]:
tup1.count(1)


Out[70]:
1

In [71]:
x=[1,2,3]

In [72]:
x[0] = 3

In [73]:
y = x

In [74]:
y[1] = 7

In [75]:
y


Out[75]:
[3, 7, 3]

In [79]:
x


Out[79]:
[3, 7, 3]

In [89]:
y = list(x)

In [94]:
x[0] = 56

In [95]:
x


Out[95]:
[56, 7, 3]

In [96]:
y


Out[96]:
[3, 7, 3]

In [97]:
x = (1,2,3)

In [98]:
y = x

In [99]:
x[0] = 56


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-99-6f98237b1775> in <module>()
----> 1 x[0] = 56

TypeError: 'tuple' object does not support item assignment

In [100]:
x = (56,) + x[1:]

In [101]:
x


Out[101]:
(56, 2, 3)

In [102]:
x = [1,2,3]

In [103]:
x


Out[103]:
[1, 2, 3]

In [104]:
x.append(6)

In [105]:
x


Out[105]:
[1, 2, 3, 6]

In [106]:
for i in x:
    print i


1
2
3
6

In [107]:
len(x)


Out[107]:
4

In [108]:
x = 'abcde'

In [110]:
for y in x:
    print y


a
b
c
d
e

In [111]:
'a' in x


Out[111]:
True

In [112]:
x[2]


Out[112]:
'c'

In [113]:
x[2] = 'k'


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-113-7ee74ea1e736> in <module>()
----> 1 x[2] = 'k'

TypeError: 'str' object does not support item assignment

In [114]:
x = 'abcd'

In [118]:
x[:2] + 'k' + x[-1]


Out[118]:
'abkd'

In [121]:
def adder(val1, val2):
    return val1 + val2

In [124]:
adder(4,5)


Out[124]:
9

In [125]:
type(x)


Out[125]:
str

In [126]:
adder('ab','cd')


Out[126]:
'abcd'

In [127]:
adder(1.2,3)


Out[127]:
4.2

In [177]:
def summer(l):
    """
    This function sums a sequence.
    """
    assert len(l) > 0
    print sum(l)

In [178]:
x = [1,2,3,5]

In [179]:
summer([])


---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-179-75373fb26f8f> in <module>()
----> 1 summer([])

<ipython-input-177-c473f3cfe15b> in summer(l)
      3     This function sums a sequence.
      4     """
----> 5     assert len(l) > 0
      6     print sum(l)

AssertionError: 

In [153]:
x


Out[153]:
[1, 2, 3, 5]

In [154]:
help(summer)


Help on function summer in module __main__:

summer(l)
    This function sums a sequence.


In [165]:
def hello(s1, s2 = 'hello world'):
    print s1, s2

In [170]:
hello(s1 = 'yo', s2 = 5)


yo 5

In [180]:
pwd


Out[180]:
u'/Users/mlightma/Documents/Software Carpentry/Yale Bootcamp/workdir/scripts'

In [181]:
ls


LICENSE                    data1.txt                  simple_for_loop.sh*
Python Introduction.ipynb  generate_data.sh           simple_for_loop.sh~*
README.md                  generate_data.sh~

In [182]:
cd ..


/Users/mlightma/Documents/Software Carpentry/Yale Bootcamp/workdir

In [183]:
ls


SWC-SampleRepo-2014-06-20-yale/ fileG.txt                       fileS.txt
dir2/                           fileH.txt                       fileT.txt
file1.txt                       fileI.txt                       fileU.txt
file12.txt                      fileJ.txt                       fileV.txt
file2.txt                       fileK.txt                       fileW.txt
file34.txt                      fileL.txt                       fileX.txt
fileA.txt                       fileM.txt                       fileY.txt
fileB.txt                       fileN.txt                       fileZ.txt
fileC.txt                       fileO.txt                       scripts/
fileD.txt                       fileP.txt                       test.txt
fileE.txt                       fileQ.txt
fileF.txt                       fileR.txt

In [184]:
cd scripts/


/Users/mlightma/Documents/Software Carpentry/Yale Bootcamp/workdir/scripts

In [185]:
ls


LICENSE                    data1.txt                  simple_for_loop.sh*
Python Introduction.ipynb  generate_data.sh           simple_for_loop.sh~*
README.md                  generate_data.sh~

In [193]:
f = open('data1.txt')

In [194]:
file_lines = []

In [195]:
for line in f:
    file_lines.append(line)

In [196]:
file_lines


Out[196]:
['1 4\n',
 '2 9\n',
 '3 16\n',
 '4 25\n',
 '5 36\n',
 '6 49\n',
 '7 64\n',
 '8 81\n',
 '9 100\n',
 '10 121\n']

In [197]:
print file_lines[0]


1 4


In [207]:
for line in file_lines:
    print line.rstrip('\n')


1 4
2 9
3 16
4 25
5 36
6 49
7 64
8 81
9 100
10 121

In [199]:
help(str.rstrip)


Help on method_descriptor:

rstrip(...)
    S.rstrip([chars]) -> string or unicode
    
    Return a copy of the string S with trailing whitespace removed.
    If chars is given and not None, remove characters in chars instead.
    If chars is unicode, S will be converted to unicode before stripping


In [204]:
file_lines[0].rstrip('\n')


Out[204]:
'1 4'

In [206]:
help(str.format)


Help on method_descriptor:

format(...)
    S.format(*args, **kwargs) -> string
    
    Return a formatted version of S, using substitutions from args and kwargs.
    The substitutions are identified by braces ('{' and '}').


In [209]:
f.close()

In [210]:
f


Out[210]:
<closed file 'data1.txt', mode 'r' at 0x103e32c90>

In [211]:
fout = open('data2.txt', 'w')

In [212]:
print >> fout, 'hello world'

In [213]:
fout.close()

In [214]:
cat data2.txt


hello world

In [215]:
help(open)


Help on built-in function open in module __builtin__:

open(...)
    open(name[, mode[, buffering]]) -> file object
    
    Open a file using the file() type, returns a file object.  This is the
    preferred way to open a file.  See file.__doc__ for further information.


In [216]:
print file.__doc__


file(name[, mode[, buffering]]) -> file object

Open a file.  The mode can be 'r', 'w' or 'a' for reading (default),
writing or appending.  The file will be created if it doesn't exist
when opened for writing or appending; it will be truncated when
opened for writing.  Add a 'b' to the mode for binary files.
Add a '+' to the mode to allow simultaneous reading and writing.
If the buffering argument is given, 0 means unbuffered, 1 means line
buffered, and larger numbers specify the buffer size.  The preferred way
to open a file is with the builtin open() function.
Add a 'U' to mode to open the file for input with universal newline
support.  Any line ending in the input file will be seen as a '\n'
in Python.  Also, a file so opened gains the attribute 'newlines';
the value for this attribute is one of None (no newline read yet),
'\r', '\n', '\r\n' or a tuple containing all the newline types seen.

'U' cannot be combined with 'w' or '+' mode.


In [217]:
cat data1.txt


1 4
2 9
3 16
4 25
5 36
6 49
7 64
8 81
9 100
10 121

In [218]:
s = '1 4'

In [219]:
s.split()


Out[219]:
['1', '4']

In [222]:
f = open('data1.txt')

In [223]:
fout = open('data2.txt', 'w')

In [224]:
# Exercise:  In data2.txt, first column is the same as data 1.txt
#            Second column  of data 2.txt is the sum of the first 
#            and second column of data1.txt
for line in f:
    # use line.split() to split on whitespace
    # get the sum of the first two columns
    print >> fout, # col1 col1+col2   from data1.txt

# data2.txt should look like
# 1 5
# 2 11
# ...


  File "<ipython-input-224-b52d10066b10>", line 4
    for line in f:
                  ^
IndentationError: expected an indented block

In [225]:
s


Out[225]:
'1 4'

In [228]:
help(str.split)


Help on method_descriptor:

split(...)
    S.split([sep [,maxsplit]]) -> list of strings
    
    Return a list of the words in the string S, using sep as the
    delimiter string.  If maxsplit is given, at most maxsplit
    splits are done. If sep is not specified or is None, any
    whitespace string is a separator and empty strings are removed
    from the result.


In [229]:
ls


LICENSE                    data1.txt                  generate_data.sh~
Python Introduction.ipynb  data2.txt                  simple_for_loop.sh*
README.md                  generate_data.sh           simple_for_loop.sh~*

In [241]:
f2 = open('data2.txt','w')
for line in open('data1.txt','r') :
    x, y = [int(i) for i in line.split()]
    print >> f2, x, x+y
f2.close()

In [245]:
# List comprehension
# new_list = [ expression for element in list ]
print [float(i)+1 for i in line.split()]


[11.0, 122.0]

In [246]:
pwd


Out[246]:
u'/Users/mlightma/Documents/Software Carpentry/Yale Bootcamp/workdir/scripts'

In [ ]: