magnetrtk
magnetrtk

Reputation: 11

How to write code where you don't define a variable

I am trying to solve this problem below

Assume s is a string of lower case characters. Write a program that counts up the number of vowels contained in the string s. Valid vowels are: 'a', 'e', 'i', 'o', and 'u'. For example, if s = 'azcbobobegghakl', your program should print:

Number of vowels: 5

I wrote the following code

s='azcbobobegghakl'
count = 0
for vowels in s:
    if vowels in 'aeiou':
        count += 1
print ('Number of vowels: ' + str(count))

This was not correct. I learned that you should not define "azcbobobegghakl" as s or g or anything else for that matter. Do I need to use a certain function to accomplish this?

Upvotes: 1

Views: 225

Answers (3)

magnetrtk
magnetrtk

Reputation: 11

s = str(input("Enter a phrase: "))
count = 0
for vowel in s:
    if vowel in 'aeiou':
        count += 1
print("Number of vowels: " + str(count))

This seems to work on python but it is not the right answer.

Upvotes: 0

Taku
Taku

Reputation: 33714

You can use a list comprehension and then count the list.

print("Number of vowels: {}".format(len([vowel for vowel in input() if vowel in "aeiou"])))

The question is asking to count the number of vowels in any string, not just the example azcbobobegghakl, therefore you should replace the fixed string with an input().

Upvotes: 2

Aaron Brock
Aaron Brock

Reputation: 4536

What you have seems to do the task required by the question, however, if the do want it in the form of a function you can restate the code you already have as a function:

def count_vowels(s):
  count = 0
  for vowels in s:
      if vowels in 'aeiou':
          count += 1
  print ('Number of vowels: ' + str(count))

Then, you can execute your program with the following:

count_vowels('azcbobobegghakl')

Upvotes: 1

Related Questions