下面的代码在python2.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()
样本运行:
^{pr2}$
同样,这个程序只打印元音的数量。如果你需要“不同”元音的数量,那就有点不同了。
希望这有帮助!在