Python script strange behavior
1
0
Entering edit mode
3.1 years ago
dllopezr ▴ 80

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!

python script • 702 views
ADD COMMENT
0
Entering edit mode

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, return statements, and if you're feeling a little adventurous, you may also want to look in to yield statements, since you'll likely find both in any standard walkthrough or tutorial on functions.

ADD REPLY
3
Entering edit mode
3.1 years ago

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.

ADD COMMENT

Login before adding your answer.

Traffic: 2231 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6