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程序
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程序
基本上你的程序是可以的,但是你没有正确的语法。您需要一个合适的函数定义,如
# 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')
函数定义必须位于函数所在的行之前叫做。为什么你不能编辑你的程序,并在上面调用函数的函数定义中添加一些行,就像我在答案中显示的那样? – 2012-03-01 20:37:28
#!/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的代码将更具可读性如果最后的打印语句是这样的:
print("There are %s vowels" % vowels)
还有其他的方法来做到这一点,但是这个就足够了,这是一个通用的惯例。
这将是一件好事,表明你正在使用Python 3,当你发布;-)
这是功课?您发布的代码没有任何意义,所以您还需要发布实际问题,以便我们可以指引您朝着正确的方向发展。 – gfortune 2012-03-01 20:06:46
你读过Python教程了吗? http://docs.python.org/tutorial/ – dangerChihuahua007 2012-03-01 20:09:13
'print“there are%d vowels”%sum((map(lambda x:Message.lower()。count(x),'aeiou')))' – inspectorG4dget 2012-03-01 20:15:06