Member Avatar for talat.zaitoun
def my_startswith(s1, s2):
    if s1[0] == s2[0]:
        return True
    elif s1[0] != s2[0]:
        return False
    elif s2 == '':
        return True
    elif s1 == '' and s2 == '':
        return True 

Iam having trouble with the third and fourth elif. Third elif: i need to say that if s1 is a string and s2 is an empty string -> true,
the fourth elif: i need to say that s1 and s2 are empty strings -> true. When I run it, it only reads the first if when i test for situations that belong to the third and fourth elif. Any help s appreciated, thank you.

Recommended Answers

All 3 Replies

In a sequence if...elif...elif...elif, only the first true alternative is executed. Use a print to see what happens:

def my_startswith(s1, s2):
    print((s1[0] == s2[0], s1[0] != s2[0],
            s2 == '', s1 == '' and s2 == ''))
    if s1[0] == s2[0]:
        return True
    elif s1[0] != s2[0]:
        return False
    elif s2 == '':
        return True
    elif s1 == '' and s2 == '':
        return True 
Member Avatar for talat.zaitoun

I get indexerror: string index out of range, are you saying I shouldn't use if, elif, and so on. Because i thought if s1 has a string and s2 is empty the first 2 (if,elif) would be false and the third elif would be true(i also get the same error when i run the original code)

You cannot use s[0] on en empty string, as s[0] returns the first char in the string: write the empty strings tests first.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.