2012-03-01 77 views
-4
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.') 

我该如何编辑函数以包含函数“元音(文本)”并仍然工作相同?编辑Python程序

+1

这是功课?您发布的代码没有任何意义,所以您还需要发布实际问题,以便我们可以指引您朝着正确的方向发展。 – gfortune 2012-03-01 20:06:46

+0

你读过Python教程了吗? http://docs.python.org/tutorial/ – dangerChihuahua007 2012-03-01 20:09:13

+0

'print“there are%d vowels”%sum((map(lambda x:Message.lower()。count(x),'aeiou')))' – inspectorG4dget 2012-03-01 20:15:06

回答

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

+0

函数定义必须位于函数所在的行之前叫做。为什么你不能编辑你的程序,并在上面调用函数的函数定义中添加一些行,就像我在答案中显示的那样? – 2012-03-01 20:37:28

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("There are %s vowels" % vowels)

    还有其他的方法来做到这一点,但是这个就足够了,这是一个通用的惯例。

  • 这将是一件好事,表明你正在使用Python 3,当你发布;-)