如何在 Python 中使用 "not in" 运算符创建函数?
How to make a function with "not in" operator in Python?
我想编写一个函数来测试每个元音是否出现在其参数中,returns如果文本包含任何小写元音则为 False,否则为 True。
我的代码如下:
def hasNoVowel(text):
return ('a' not in text) or ('u' not in text) or ('o' not in text) or ('i' not in text) or ('e' not in text)
print(hasNoVowel('it is a rainy day'))
print(hasNoVowel('where is the sun?'))
print(hasNoVowel("rhythm"))
但是我得到的输出是:
True
True
True
代替:错误、错误、正确
谁能帮我解释一下我做错了什么?
提前致谢!
您需要在函数中使用 and
而不是 or
。目前你的函数 returns False
仅当 all 五个元音存在时:
>>> print(hasNoVowel('she found the sun during a rainy day'))
False
您可以使用 any(...)
来评估条件并缩短您的代码:
def hasNoVowel(text):
#return ('a' not in text) or ('u' not in text) or ('o' not in text) or ('i' not in text) or ('e' not in text)
return not any([v in text for v in 'aeiou'])
print(hasNoVowel('it is a rainy day'))
print(hasNoVowel('where is the sun?'))
print(hasNoVowel("rhythm"))
输出:
False
False
True
我想编写一个函数来测试每个元音是否出现在其参数中,returns如果文本包含任何小写元音则为 False,否则为 True。
我的代码如下:
def hasNoVowel(text):
return ('a' not in text) or ('u' not in text) or ('o' not in text) or ('i' not in text) or ('e' not in text)
print(hasNoVowel('it is a rainy day'))
print(hasNoVowel('where is the sun?'))
print(hasNoVowel("rhythm"))
但是我得到的输出是:
True
True
True
代替:错误、错误、正确
谁能帮我解释一下我做错了什么?
提前致谢!
您需要在函数中使用 and
而不是 or
。目前你的函数 returns False
仅当 all 五个元音存在时:
>>> print(hasNoVowel('she found the sun during a rainy day'))
False
您可以使用 any(...)
来评估条件并缩短您的代码:
def hasNoVowel(text):
#return ('a' not in text) or ('u' not in text) or ('o' not in text) or ('i' not in text) or ('e' not in text)
return not any([v in text for v in 'aeiou'])
print(hasNoVowel('it is a rainy day'))
print(hasNoVowel('where is the sun?'))
print(hasNoVowel("rhythm"))
输出:
False
False
True