SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Tony Gaddis
Chapter:
More About Strings
Exercise:
Programming Exercises
Question:9 | ISBN:9780132576376 | Edition: 2

Question

Vowels and Consonants
Write a program with a function that accepts a string as an argument and returns the number of vowels that the string contains. The application should have another function that accepts a string as an argument and returns the number of consonants that the string contains. The application should let the user enter a string and should display the number of vowels and the number of consonants it contains.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Vowels and Consonants Program code:

#Method countVowels
def countVowels(string):
    vowels = 'aeiouAEIOU'
    vowel_count = 0

    # Iterate over each character in the string
    for char in string:
        # Check if the character is a vowel
        if char in vowels:
            vowel_count += 1
    return vowel_count
#Method countConsonants
def countConsonants(string):
    consonants = 'bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ'
    consonant_count = 0

    # Iterate over each character in the string
    for char in string:
        # Check if the character is a consonant
        if char in consonants:
            consonant_count += 1

    return consonant_count
# Promt and read the string from the user
string = input("Enter a string: ")

# Call the count_vowels and count_consonants functions
vowel_count = countVowels(string)
consonant_count = countConsonants(string)

# Display the counts of vowels and consonants
print("Number of vowels:", vowel_count)
print("Number of consonants:", consonant_count)

Executed Output:

Enter a string: Hello Python
Number of vowels: 3
Number of consonants: 8

 

0 0

Discussions

Post the discussion to improve the above solution.