Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the difference between using range in the first program and not using it in the second program?

For an assignment, I needed to make a program that counts the vowels and consonants in a string using for i in range(0, len(str)):

I put this program together using what I learned, but I can’t really wrap my head around why it works.

vowelCount = 0
consonantCount = 0

sentence = input("Enter your sentence: ")

for char in range(0, len(sentence)):
    if sentence[char] in "aeiouAEIOU":
        vowelCount += 1
    if sentence[char] in "bcdfghjklmnpqrstvwxyBCDFGHJKLMNPQRSTVWXYZ":
        consonantCount += 1

print("There are", vowelCount, "vowels")
print("There are", consonantCount, "consonants")

Why am I getting the range of the length of the sentence?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here’s an alternative program I wrote without the range.

vowelCount = 0
consonantCount = 0

sentence = input("Enter your sentence: ")

for i in sentence: 
    if i in "aeiouAEIOU":
        vowelCount += 1
    if i in "bcdfghjklmnpqrstvwxyBCDFGHJKLMNPQRSTVWXYZ":
        consonantCount += 1

print("There are", vowelCount, "vowels")
print("There are", consonantCount, "consonants")

Why do I need to use sentence[char] in the range version? Why the brackets?

>Solution :

Your program is going through sentence one letter at a time. For each letter (retreived by sentence[char]) it checks whether it is in the list of vowels (if yes, increment vowelCount) or in the list of consonants (if yes, increment consonantCount).

The form a in b for strings a and b checks whether a is contained somewhere as exact substring in b. So if a is just a single letter, it checks whether b contains the letter a anywhere.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading