用一个接受字符串作为参数并返回字符串包含的元音数量的函数编写程序。应用程序应具有另一个函数,该函数接受字符串作为参数并返回该字符串包含的辅音数量。该应用程序应让用户输入字符串,并应显示元音的数量及其所包含的辅音的数量。
这是我到目前为止的代码:
def main():
mystr = input('Please enter a string: ')
mystr.lower()
index = 0
vowelSet = set(['a','e','i','o','u'])
vowels = 0
consonants = 0
def runVowels(mystr):
while index < len(mystr):
if mystr[index] in vowels:
vowels += 1
index += 1
print('This string consists of ' + mystr(vowels) + 'vowels')
def runConsonants(mystr):
while index < len(mystr):
if mystr[index] != vowels:
consonants += 1
index += 1
print('This string consists of ' + mystr(consonants) + 'consonants')
main()
我在哪里出错了,我在正确的轨道上吗?
下面的代码在python 2.7.3上进行了测试。
您需要研究变量作用域,不能在一种方法中定义变量,而在另一种方法中使用它。
研究一下什么是从用户那里获取输入的最佳方法,sys是一个非常好的库
始终,始终在使用变量之前初始化变量,内联提供了注释。
def main():
mystr = raw_input("Enter your String:")
mystr.lower()
#index = 0, index is useless here
vowelSet = set(['a','e','i','o','u'])
#vowels = 0, vowels is useless here
#consonants = 0, consonants is useless here
#Either pass vowelSet as argument or define them explicitly in the methods
runVowels(mystr, vowelSet)
runConsonants(mystr, vowelSet)
def runVowels(mystr, vowelSet):
#index, vowels needs to be defined and assigned a default value here
index = 0
vowels = 0
while index < len(mystr):
if mystr[index] in vowelSet:
vowels += 1
# You need to increment index outside of the condition
index += 1
print 'This string consists of ', vowels , 'vowels'
def runConsonants(mystr, vowelSet):
#index, consonants needs to be defined and assigned a default value here
index = 0
consonants = 0
while index < len(mystr):
if mystr[index] not in vowelSet:
consonants += 1
# You need to increment index outside of the condition
index += 1
print 'This string consists of ' , consonants , 'consonants'
main()
样品运行:
$ python vow.py
Enter your String:aeeiithy
This string consists of 5 vowels
This string consists of 3 consonants
同样,该程序仅打印一些元音。如果您需要数量“不同”的元音,那就有些不同了。希望这可以帮助 !
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句