缩短这个特定的代码

Shortening down this specific code

我已经学习 Python 几个星期了,复活节刚过,将进行一次对照评估,该评估将计入我的 GCSE 成绩,为此我也会根据标准进行评分类似于我的代码的长度。

问题是:编写一个 Python 程序,要求用户输入一个词,然后计算打印出输入的词的元音值。

我想知道的:

Is there anyway of shortening down this code?

还有:

How can the program be executed without printing out the "word" variable?

上面给出了我在代码中使用的规则(在控制流部分)。

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)

您可以使用 sumdict,将元音存储为键并将关联值存储为值:

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

values.get(ch,0) 将 return 0 作为默认值,如果单词中的每个字符 ch 不是元音,因此不在我们的字典中。

sum(values.get(ch,0) for ch in word) 是一个 generator expression,其中变量 在为生成器对象调用 next() 方法时延迟求值

关于您自己的代码,您应该使用 if/elif 的代码。一个字符只能有一个值,if's 总是被求值,而 elif's 只在前一个语句求值为 False 时被求值:

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

这是工作代码:

word = input("Input a word: ")

values = {"a":5,"e":4,"i":3,"o":2,"u":1}
score = sum(values[let] for let in word if let in values)

print("\nThe score for your word is: " + score)