Search code examples
pythonassert

My assertion fails for this piece of code in python


def test_string_membership():
    assert False == 'c' in 'apple'
    assert True == 'a' in 'apple'
    assert True == 'app' in 'apple'

p.s:- I am a beginner in python and unable to find out whats wrong. My assertion fails when I run the code.


Solution

  • False == 'c' in 'apple' is not interpreted as

    False == ('c' in 'apple')
    

    but,

    (False == 'c') and ('c' in apple)
    

    becaue of comparison chaining.


    To get what you want, put parentheses explicitly.

    False == ('c' in 'apple')
    

    or more preferably use in / not in:

    def test_string_membership():
        assert 'c' not in 'apple'
        assert 'a' in 'apple'
        assert 'app' in 'apple'