Hi, community!
I am learning python with a book called "Python for Biologist". An exercise is to write a function that calculates the percentage of a residue in a protein sequence and evaluate it with the assert function, and this is my solution:
from _future_ import division
def Residue_percentage(ProteinSequence, Residue):
length = len(ProteinSequence)
Residue = Residue.upper()
residue_count = ProteinSequence.count(Residue)
percentage = residue_count * 100 / length
print(percentage)
assert Residue_percentage("MSRSLLLRFLLFLLLLPPLP", "M") == 5
But I got an Assertion error. If I include return percentage the assertion pass the test.
'Do you know what is happening here?
Thank you so much!
1 answer
If you don't return a value from a Python function, the result of calling that function will be None, which will not equal 5.
Use return to return a testable value.
To avoid dumb Python backwards-incompatibility bugs created by how integers are handled between Python 2 and 3, explicitly cast the result to an integer with int(), i.e., return int(foo) where foo is the value you want test against another integer.
Log in to answer this question.
That's not strange behaviour at all ;) that's exactly what's meant to happen.
You may want to spend some more time familiarising yourself with what a python function means and how it's used. In particular,
returnstatements, and if you're feeling a little adventurous, you may also want to look in toyieldstatements, since you'll likely find both in any standard walkthrough or tutorial on functions.