This question already has an answer here:
I have some problems with if-elif-else statements. I have code with if-elif-elif-elif-else. The point is that when if and 1st elif doesn't match, it should go to 2nd elif and so on. But my code doesn't do that, it accept only if and 1st elif.
def scramble_word(word: str) -> str:
i = word.find("'")
c = word[0] + ''.join(sorted(word[1:i] + word[i + 1:-1], key=str.lower)) + word[-1]
d = word[0] + ''.join(sorted(word[1:i] + word[i + 1:-2], key=str.lower)) + word[-2] + word[-1]
if len(word) - (word.count("!") + word.count("?") + word.count(".") + word.count('"') + word.count(",") +
word.count(";") + word.count("'")) > 7:
return word
elif "'" in word[1:-1] and "!" or "?" or "," or ";" or "." or '"' in word[-1]:
return d[0:i] + "'" + d[i:]
elif "'" in word[1:-1]:
return c[0:i] + "'" + c[i:]
elif "!" or "." or '"' or "," or "?" or ";" in word[-1]:
return word[0] + ''.join(sorted(word[1:-2], key=str.lower)) + word[-2] + word[-1]
else:
return word[0] + ''.join(sorted(word[1:-1], key=str.lower)) + word[-1]
So if I try to print some word, for example Mo'uSE!, it should return Mo'SuE!, according to 1st elif statement:
print(scramble_word("Mo'uSE")) # -> Mo'SuE!
So it does. Also if I try to print for example Mo'useeef!, which is bigger than 7 elements (excluding symbols ,;"'!?) it should return the same word, Mo'useeef!. According to if statement. So it does:
print(scramble_word("Mo'useeef!")) # -> Mo'useeef!
If the printed word doesn't fit to if or 1s elif, it should go on, 2nd elif. So actually it should print following:
print(scramble_word("Mo'uSE")) # -> Mo'SuE
But it prints something other, which doesn't fit with 2nd elif or even doesn't match with anything. The same story is with 3rd elif and else.
So the problem is that only two first statements are working correctly: if and 1st elif. Separately all five statements are working fine, but when they are together in one function, they don't work correctly.
Also if I try change for example if and 3rd elif by place, so if statement becomes to 3rd elif and 3rd elif becomes to if, it works again not correctly. And again only two first statements are working okay.
I hope you all understood my writings here. Thank you in advance.
Aucun commentaire:
Enregistrer un commentaire