Requires assistance with vowel checker program
编写一个python程序,要求用户输入一个单词,然后使用以下说明计算并打印输入单词的元音值:假设您根据以下说明计算单词的元音值:
1 2 3 4 5 | a 5 points e 4 points i 3 points o 2 points u 1 point. |
我的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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循环
word=输入("输入一个词:")
def元音(wou rd):全局字WORDR= Word得分=0对于word.lower()中的char:如果char='a'或'a':得分+=5elif char=="e"或"e":得分+=4elif char=="我"或"我":得分+=3elif char=="o"或"o":得分+=2elif char=="U"或"U":得分+=1a="你的单词得分",得分,"在单词检查测试中"返回A
印刷体(元音(字))
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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语句放在最后一行。
另一个问题是,一个单词的分数应该从0开始,而不是从1开始吗?
首先,如果你要向
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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)) |
Time complexity is important
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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") |
输入一个词:你好
巴兰语代码,你的单词在元音检查中得了7分。
---2.4024055004119873秒---
我的代码,你的单词在元音检查中得了7分
---0.004721164703369141秒---