我写:
def is_vowel(letter:str) ->bool:
"""
takes a one-character-long string and returns
True if that character is a vowel and False otherwise.
"""
if letter in ['a' or 'A' or 'e' or 'E' or 'i' or 'I' or 'o' or
'O' or 'u' or 'U']:
return True
print(is_vowel('A'))
Run Code Online (Sandbox Code Playgroud)
但它打印出来None.为什么?
首先,看一下('a' or 'A')翻译.它会返回'a',所以你最初在一个只有一个字符的列表中寻找字符:['a'].这是因为长度大于零的字符串True在布尔上下文中求值,而该布尔上下文是or创建的.or在这种情况下,将返回第一个真正的东西'a'.
我建议为了可读性,使用如下面的函数,首先采用字母的小写版本,然后判断它是否存在于所有这些字符的字符串的规范表示中,并且只返回成员资格的测试结果.不需要if-then控制流程:
def is_vowel(letter: str) -> bool:
"""
takes a one-character-long string and returns True if
that character is a vowel and False otherwise.
"""
return letter.lower() in 'aeiou'
print(is_vowel( 'b'))
Run Code Online (Sandbox Code Playgroud)
在Python 2中,
def is_vowel(letter):
"""
takes a one-character-long string and returns True if
that character is a vowel and False otherwise.
"""
return letter.lower() in 'aeiou'
Run Code Online (Sandbox Code Playgroud)
你得到的原因None是因为你的函数(下面简化的不同版本)如果不返回True则不返回False.当函数没有返回任何指定的内容时,它返回None.所以下面是一个更接近你的版本,如果它没有返回True,则返回False.
def is_vowel(letter: str) -> bool:
if letter in ['a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U']:
return True
else:
return False
Run Code Online (Sandbox Code Playgroud)
但我认为这写得更好:
def is_vowel(letter: str) -> bool:
return letter in ['a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U']
Run Code Online (Sandbox Code Playgroud)
或者像我一样,上面.