缩短此特定代码

Kry*_*zyk 1 python code-complexity

我已经学习了几个星期的Python,并且在复活节之后,将有一个受控制的评估将计入我的GCSE等级,为此我也将被标记为类似于我的代码的标准.

问题是:编写一个Python程序,询问用户一个单词,然后计算打印输入单词的元音值.

我想知道的:

无论如何缩短这段代码?

并且:

如何在不打印"word"变量的情况下执行程序?

上面我给了一个我在代码中使用的量规(在控制流程部分).

score = 0

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

c = 0
for letter in word:
        print(word[c])
        c = c + 1
        if letter == "a":
                score = score + 5
        if letter == "e":
                score = score + 4
        if letter == "i":
                score = score + 3
        if letter == "o":
                score = score + 2
        if letter == "u":
                score = score + 1

print("\nThe score for your word is: " + score)
Run Code Online (Sandbox Code Playgroud)

Pad*_*ham 6

您可以使用sum和a dict,将元音作为键存储,并将相关值存储为值:

word = input("Input a word: ")

values = {"a":5,"e":4,"i":3,"o":2,"u":1}
print(sum(values.get(ch,0) for ch in word))
Run Code Online (Sandbox Code Playgroud)

values.get(ch,0)0如果ch单词中的每个字符都不是元音,则返回默认值,因此不在我们的字典中.

sum(values.get(ch,0) for ch in word)是一个生成器表达式,为生成器对象调用next()方法,变量被 懒惰地计算

关于你自己的代码,你应该使用if/elif.一个字符只能有一个值,如果总是被评估,但仅在前一个语句的计算结果为False时才计算elif:

score = 0
 # already a str in python3 use raw_input in python2
word = input("Input a word: ")

for letter in word:
        if letter == "a":
            score += 5 # augmented assignment same as score = score + 5
        elif letter == "e":
            score += 4
        elif letter == "i":
            score += 3
        elif letter == "o":
            score += 2
        elif letter == "u":
            score += 1
Run Code Online (Sandbox Code Playgroud)