Home > database >  turning for loop into a function python
turning for loop into a function python

Time:05-05

user_input_1 = str(input("Enter fruit name"))
variable_count_vowel = 0
vowels = set("AEIOUaeiou")

for x in user_input_1:
        if x in vowels:
                variable_count_vowel = variable_count_vowel   1

print("Number of vowels within fruit name",user_input_1,"=",variable_count_vowel)

I have been working on a task where the program counts the amount of specific vowels found within the users input and I would like to turn this for loop into a function.

CodePudding user response:

As mkrieger1 suggested, you might just define the function over the for loop and then indent it:

def vowel_count(text, vowels=set("AEIOUaeiou")):
    variable_count_vowel = 0
    for x in text:
            if x in vowels:
                    variable_count_vowel  = 1
    return variable_count_vowel

user_input_1 = str(input("Enter fruit name"))

print("Number of vowels within fruit name",user_input_1,"=",vowel_count(text))

CodePudding user response:

I'd recommend using a regular expression, within a function or not:

import re
user_input_1 = str(input("Enter fruit name"))
print(len(re.findall(r'[AEIOUaeiou]',user_input1)))

CodePudding user response:

There are many ways to do this. One way would be to use sum() in conjunction with a generator like this:

VOWELS = set('aeiouAEIOU')

def vowel_count(s):
    return sum(1 for c in s if c in VOWELS)

print(vowel_count('abc'))
  • Related