需要元音检查程序

时间:2017-01-16 16:38:33

标签: python

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

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 =输入("输入一个单词:")

def vowel(Wo_rd):     全球一词     Wo_rd =字     得分= 0     对于word.lower()中的char:         如果char ==' a'或" A":             得分+ = 5         elif char ==" e"或" E":             得分+ = 4         elif char ==" i"或者"我":             得分+ = 3         elif char ==" o"或者" O":             得分+ = 2         elif char ==" u"或者" U":             得分+ = 1         a ="你的单词得分",得分,"在word checker test"         返回

print(元音(单词))

3 个答案:

答案 0 :(得分:3)

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中,字符串是可迭代的,因此您可以遍历每个字符。
  • 请注意,您不必(也不应该)使用global
  • character.lower()的使用简化了我们的条件。
  • 您可以改为vowel而不是在return score函数中打印输出,而是将print语句放在最后一行。

P.S。鉴于这个问题,单词的得分不应该从0开始,而不是1?

答案 1 :(得分:1)

首先,如果您要传递给vowel,我不知道您使用全球的原因。你在vowel内调用print所以元音应该返回一个字符串而不是打印一个字符串本身。接下来,通过使用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))  

答案 2 :(得分:0)

  

时间复杂度很重要

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秒---