编辑Python程序

时间:2012-03-01 19:58:50

标签: python

Message = input("Enter a message: ")
vowels=Message.count('a')+ Message.count('i')+Message.count('e')+Message.count('u')+Message.count('o')
print ('There are ',vowels,' vowels.')

如何编辑功能以包含“元音(文本)”功能并仍然可以正常工作?

2 个答案:

答案 0 :(得分:1)

基本上你的程序没问题,但你的语法不正确。您需要一个适当的函数定义,如

# fn count vowels
def vowels(text):
    NumVowels = text.count('a') + text.count('e') + ...
    return NumVowels 

请注意,Python确实需要缩进。其余的很简单:

message = input("enter a message: ")
print ('there are', vowels(message), 'vowels')

我喜欢这个教程:http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-189-a-gentle-introduction-to-programming-using-python-january-iap-2011/index.htm

答案 1 :(得分:0)

#!/usr/bin/env python3.2

def Vowels(text):
    vowels = ['a', 'e', 'i', 'o', 'u']
    numvowels = sum(text.count(i) for i in vowels)
    return numvowels

if __name__ == '__main__':
    Message = input("Enter a message: ")
    vowels = Vowels(Message)
    print ('There are ',vowels,' vowels.')

它的工作方式相同,但有一些问题:

  • 我正在使用__main__后卫而你却没有。你应该是,你可能不知道它是什么,所以请看:http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#modules-scripts
  • 您使用大写字母表示函数名称。我跟着你,因为你似乎需要它。 Python社区中的约定是函数/方法名称应该都是小写的。像许多其他公约一样,这个惯例是由“PEP 8”驱动的。在此页面上搜索“功能名称”:http://www.python.org/dev/peps/pep-0008/
  • 如果最后一个print语句如下所示,代码将更具可读性:

    print("There are %s vowels" % vowels)

    还有其他方法可以做到这一点,但这个方法已经足够并且是一种常见的惯例。

  • 当你发帖时表示你正在使用Python 3会很好; - )