Python Lectures 5
Python Lectures 5
DeNining
Functions
General
syntax:
keyword
instructing
Python
that
a
function
deNinition
follows
block initiation
return output
indentation
return
keyword
used
to
return
the
result
of
a
function
back
Boolean
Functions
Boolean
functions
are
functions
that
return
a
True
or
False
value.
They
can
be
used
in
conditionals
such
as
if
or
while
statements
whenever
a
condition
is
too
complex.
Problem.
Write
a
program
that
checks
if
a
given
DNA
sequence
contains
an
in-frame
stop
codon.
dna_has_stop.py
#!/usr/bin/python
# define has_stop_codon function here
dna=raw_input("Enter a DNA sequence, please:")
if(has_stop_codon(dna)) :
print(Input sequence has an in frame stop codon.)
else :
print(Input sequence has no in frame stop codons.)
11
12
>>> dna="aaatgagcggccggct"
>>> has_stop_codon(dna)
True
>>> has_stop_codon(dna,1)
False
15
17
Reversing
A
String
Regular
slices
>>> dna="AGTGTGGGGCG"
>>> dna[0:3]
'AGT'
Extended
slices
step
argument
>>> dna[0:3:2]
'AT'
>>> dna[::-1]
'GCGGGGTGTGA'
18
19
List
Comprehensions
List
comprehensions
in
Python
provide
a
concise
way
to
create
lists.
Common
applications
are
to
make
new
lists
where
each
element
is
the
result
of
some
operations
applied
to
each
member
of
another
sequence,
or
to
create
a
subsequence
of
those
elements
that
satisfy
a
certain
condition.
Syntax
new_list = [operation(i) for i in old_list if filter(i)]
or
new_list = []
for i in old_list:
if filter(i):
new_list.append(operation(i))
20
['A', 'G', 'T', 'G', 'T', 'G', 'G', 'G', 'G', 'C', 'G']
>>> letters = [basecomplement[base] for base in
letters]
>>> letters
['T', 'C', 'A', 'C', 'A', 'C', 'C', 'C', 'C', 'G', 'C']
21
22
Join.
The
method
join()
returns
a
string
in
which
the
string
elements
were
joined
from
a
list.
The
separator
string
that
joins
the
elements
is
the
one
upon
which
the
function
is
called:
>>> '-'.join(['enzymes', 'and', 'other', 'proteins',
'come', 'in', 'many', 'shapes'])
'enzymes-and-other-proteins-come-in-many-shapes'
23
24
25
26