Search code examples
pythonstringpython-3.xstring-length

Output of program for user input giving different length for consonant with user input. input 1 --> abc input2--> 'abc'


""" why this 4 in second user input as 'abc'.ii know that it is counting quotes as python will take input 'abc' as " ' abc ' " hence counting 5 as length how to remove this issue for getting correct answer like other input as shown above n below"""

to get count vowels n consonants

 def get_count(words):
    words=str(input('Enter:')).lower()
    vowels = ['a','e','i','o','u']
    v_count = 0
    c_count = 0
    for letter in words:
        if letter in vowels:
            v_count += 1
        else:
            c_count+=1
    print("vowel : {}".format(v_count), "consonant: {}".format(c_count))
get_count(input)

Result:

Enter:aBc
vowel : 1 consonant: 2
Enter:'abc'
vowel : 1 consonant: 4-  ??? why

Blockquote

Enter:abc
vowel : 1 consonant: 2

Solution

  • Long answer: So your string is 'abc' which is 5 characters long. python is checking:

    • if first character ' is in vowels and it is not so consonant = 0+1
    • second character is a, it is in vowels so vowels = 0+1
    • third b which is not in vowels, so consonant = 1+1 (which is 2 now)
    • fourth c which is not in vowels, so consonant = 2+1 (which is 3 now)
    • fifth character is ' which is not in vowels, so consonant = 3+1 (which is 4 now)

    so in the end we get: vowel : 1 consonant: 4

    Short answer: your input is considered as a five character long string, and your script iterates over each element including single quotations.