PythonTutorial Notes Ch4
PythonTutorial Notes Ch4
# with you press return at this point (youʼll need one after the last ʻprintʼ statement and
then hit return again to tell python you are done typing the code), the if loop will run and
print out the answer (conditional upon the input integer you gave the program)
# for statements will iterate over a given variable (e.g. list, array) progressing from the
left of the variable to its end (low to high indices)
# # remember that some variable types are immutable
# # itʼs also recommended that you donʼt change the variable in the for loop....
rather you should MAKE A COPY of the variable so you then change the copy
! 1
Python Tutorial Workshop Spring Qtr 2011!
Text: Python Tutorial (from website)
...
need 4
programming 11
cookbook 8
# then you can check at how you altered the list variable x:
>>> a
['cookbook', 'programming', 'need', 'programming', 'cookbook']
# you can then look at the index value for each element using the range() and len()
commands
>>> range(8)
[0, 1, 2, 3, 4, 5, 6, 7]
>>> range(0,12,2)
[0, 2, 4, 6, 8, 10]
# then use:
>>> a = ['biopython','may','beat','bioperl','or','maybe','not']
>>> for i in range(len(a)):
... print i, a[i]
...
0 biopython
1 may
2 beat
3 bioperl
4 or
5 maybe
6 not
# the enumerate() function is probably a better way to do this... weʼll cover this later in
the Looping Section
# Writing/defining functions
>>> def square(n):
... print n*n
...
>>> x = 2
>>> square(x)
4
! 2
Python Tutorial Workshop Spring Qtr 2011!
Text: Python Tutorial (from website)
! 3