首页 文章

需要元音检查程序的帮助

提问于
浏览
-4

编写一个python程序,询问用户一个单词,然后使用这些指令计算并打印输入单词的元音 Value :假设您根据以下说明计算单词的元音 Value :

a   5 points
e   4 points
i   3 points
o   2 points
u   1 point.

我的代码:

word = str(input("Enter a word:"))

def vowel(Word):
    global word
    Word = word
    score = 1

    if "a" or "A" in word:
        score += 5
    elif "e" or "E" in word:
        score += 4
    elif "i" or "I" in word:
        score += 3
    elif "o" or "O" in word:
        score += 2
    elif "u" or "U" in word:
        score += 1

    print("Your word scored",score,"in the vowel checker")

print(vowel(word))

编辑:FOR LOOP

word = input(“输入一个单词:”)

def元音(Wo_rd):全局单词Wo_rd =单词得分= 0表示字符中的char.lower():如果char =='a'或“A”:得分= 5 elif char ==“e”或“E”:得分= 4 elif char ==“i”或“I”:得分= 3 elif char ==“o”或“O”:得分= 2 elif char ==“u”或“U”:得分= 1 a = “你的单词得分”,得分,“在单词检查器测试中”返回a

打印(元音(字))

3 回答

  • 0
    word = str(input("Enter a word:"))
    
    def vowel(word):
        score = 1
    
        for character in word:
            character = character.lower()
            if character == 'a':
                score += 5
            elif character == 'e':
                score += 4
            elif character == 'i':
                score += 3
            elif character == 'o':
                score += 2
            elif character == 'u':
                score += 1
    
        print("Your word scored",score,"in the vowel checker")
    
    vowel(word)
    

    注意事项:

    • 在Python中,字符串是可迭代的,因此您可以遍历每个字符 .

    • 请注意,您不要't have to (and shouldn' t)使用 global .

    • 使用 character.lower() 简化了我们的条件 .

    • 而不是在 vowel 函数中打印输出,而不是只需 return score 并将print语句放在最后一行 .

    附:鉴于这个问题,单词的得分不应该从0开始,而不是1?

  • 3

    首先,如果你传递的话是 vowel 我不知道为什么你使用全局 . 你在 print 内调用 vowel 所以元音应该返回一个字符串而不是打印一个字符串本身 . 接下来,通过使用 for 循环,您可以检查单词的每个字符并增加分数,即使出现多个元音的出现 .

    word = str(input("Enter a word:"))
    
    def vowel(word):
      score = 1
      for c in word:
        if "a" == c.lower():
            score += 5
        elif "e" == c.lower():
            score += 4
        elif "i" == c.lower():
            score += 3
        elif "o" == c.lower():
            score += 2
        elif "u" == c.lower():
            score += 1
    
      return "Your word scored "+str(score)+" in the vowel checker"
    
    print(vowel(word))
    
  • 1

    时间复杂性很重要

    for character in word:
        character = character.lower()
        if  re.match("a",character):
            score += 5
        elif re.match("e",character):
            score += 4
        elif re.match("i",character):
            score += 3
        elif re.match("o",character):
            score += 2
        elif re.match("u",character):
            score += 1
    
    print("Your word scored",score,"in the vowel checker")
    

    输入一个字:你好

    pbaranay代码,你的单词在元音检查中得分为7分

    --- 2.4024055004119873秒---

    我的代码,你的单词在元音检查中得了7分

    --- 0.004721164703369141秒---

相关问题