【问题标题】:How do I check each letter in a word is either a vowel or consonant?如何检查单词中的每个字母是元音字母还是辅音字母?
【发布时间】:2023-02-03 13:30:07
【问题描述】:
def check_v_c(word):
    for i in word:
        if i in "AEIOUaeiou":
            return i

        else:
            i in "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz"


print(check_v_c("Money"))

我试图使用 for 循环循环每个字母。

【问题讨论】:

  • 然后不要在循环内返回。也应该是elif
  • 而不是 return ->print 你也可以在 else 部分删除 i in "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz" 并可以直接打印它..它不是元音..!
  • 在if语句中,你有return,它会立即退出函数。不要那样做。
  • 此外,在 else 语句中,您正在检查 i 是否是辅音,但是您没有对结果的支票。
  • 函数应该返回什么?

标签: python loops for-loop word


【解决方案1】:

你只需要删除else就好像if是False它会再次运行for循环

def check_v_c(word):
  for i in word:
    if i in "AEIOUaeiou":
        return i


print(check_v_c("Money"))

但是如果你想传递一些东西,那么你可以

def check_v_c(word):
  for i in word:
    if i in "AEIOUaeiou":
        return i

    else:
        "It is not vowel"


print(check_v_c("Money"))

【讨论】:

    【解决方案2】:

    我希望这对您的解决方案有用使用字符串类来检查标点符号

    import string
    def check_v_c(word):
        result = []
        for i in word:
            if i.lower() in "aeiou":
                result.append(f'{i} is a vowel')
            elif i in string.punctuation:
                result.append(f'{i} is a punctuation')
            else:
                result.append(f'{i} is a consonant')
        return result
    print('
    '.join(check_v_c("Mon.ey")))
    

    【讨论】:

      【解决方案3】:

      您编写的代码不会返回所需的结果,因为它缺少针对字符位于第二组字母(辅音)中的情况的返回语句。当前实现将为所有输入返回 None,因为循环后没有 return 语句。

      这是代码的更正版本:

      def check_v_c(word):
          for i in word:
              if i in "AEIOUaeiou":
                  return i
          return "Consonant"
      
      print(check_v_c("Money"))
      

      如果存在,此代码将返回输入单词中的第一个元音,否则返回“辅音”。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-20
        • 1970-01-01
        • 2018-07-09
        • 2012-12-23
        相关资源
        最近更新 更多