Skip to main content
 首页 » 编程设计

python之缩短这个特定的代码

2025年05月04日14落叶无声

我已经学习 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) 

请您参考如下方法:

您可以使用 sum 和 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)) 

values.get(ch,0) 将返回 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