写 def 元音(w,i):

Writing def vowel(w,i):

我正在尝试编写一个定义,其中 w 是一个单词(大写或小写),i 是单词中字母所在的索引,输出为 True 或 False。 例如,

>>>vowel(hello,1) 

到 return 正确,因为 e 在第 1 个字符处是元音

到目前为止,我有,

def vowel (w,i):
    vowel=['a','e','i','o','u']
    for i in range(0,len(w)):
        if vowel in w.lower():
            print(True)
            else print (False)

它一直在 returning SyntaxError: invalid syntax

有什么提示吗?并提前感谢您!

你的 else 应该与你的 if 缩进到同一水平并且它后面应该有一个冒号 else:。您的代码似乎也没有按照您的问题所说的去做。

您不需要迭代函数中的任何内容,因为索引已作为参数传递给函数。您的测试也略有倒退。您的代码试图查找列表 vowel 是否在字符串 w.lower() 内,但显然不在。

这个版本更有意义:

def vowel(w,i):
    vowel_list = ['a','e','i','o','u']
    if w[i].lower() in vowel_list:
        print(True)
    else:
        print (False)

s = "hellO World!"
vowel(s,0) #false
vowel(s,4) #true
vowel(s,7) #true

请注意,从函数中 return 值 TrueFalse 比直接打印出来要好得多。例如,使用这种方法,我们有一种简单的方法来定义一个函数来检查某些东西是否是辅音。

辅音只是字母表中不是元音的东西。 Python 已经有一种方法可以使用 str.isalpha() 方法检查字母表中是否存在某些内容。所以我们可以使用这个:

def is_vowel(w,i):
    if w[i].lower() in ['a','e','i','o','u']:
        return True
    else:
        return False

def is_consonant(w, i):
    return w[i].isalpha() and not is_vowel(w, i)

string = "Hello World!"

print(is_vowel(string, 0))
print(is_consonant(string, 0))
print(is_vowel(string, 1))
print(is_consonant(string, 1))

为了实现您的目标,我将采取以下措施:

def vowel(word, i):
    if word[i].lower() in ['a', 'e', 'i', 'o', 'u']:
        print(True)
    else:
        print(False)

希望对您有所帮助! :)