Program not giving the expected result

前端 未结 1 404
执念已碎
执念已碎 2021-01-28 05:12

I\'m currently following an intro to cs course in python. The code is given below.

school = \'Massachusetts Institute of Technology\'
numVowels = 0
numCons = 0
         


        
1条回答
  •  抹茶落季
    2021-01-28 05:32

    Your code seems to be case sensitive. A quick fix would be

    school = 'Massachusetts Institute of Technology'
    numVowels = 0
    numCons = 0
    
    for char in school.lower():
        if char in "aeiou":
            numVowels += 1
        elif char in "om":
            print(char)
        else:
            numCons -= 1
    
    print('numVowels is: ' + str(numVowels))
    print('numCons is: ' + str(numCons))
    

    resulting in

    m
    numVowels is: 12
    numCons is: -24
    

    Though note that your code isn't counting consonants, just characters that aren't vowels or m.

    Maybe consider the following instead:

    import string
    school = 'Massachusetts Institute of Technology'
    numVowels = 0
    numCons = 0
    
    for char in school.lower():
        if char in "aeiou":
            numVowels += 1
        elif char in string.ascii_letters:
            numCons += 1
    

    Though it really depends what you're trying to do with your resulting numVowels and numCons variables. Without an explict expected output, it's tough to say.

    0 讨论(0)
提交回复
热议问题