Reputation: 3
I'm still new to python and have just started learning. The task given is to find the amount of punctuation, vowels, and constants in a given text. But whenever I run the code it just gives me a 0
.
def getInfo(text):
pun = [".", ",", " ", "\'", "\"", "!"]
vowels = ["a", "e", "i", "o", "u"]
count = 0
count2 = 0
count3 = 0
for char in text:
if char in pun:
count += 1
return count
if char.lower() in vowels:
count2 += 1
return count2
if (not char.lower() in vowels) and (not char.lower() in pun):
count3 += 1
return count3
Upvotes: 0
Views: 70
Reputation:
When program reaches return it exits from loop.
def getInfo(text):
pun = [".", ",", " ", "'", '"', "!"]
vowels = ["a", "e", "i", "o", "u"]
count = 0
count2 = 0
count3 = 0
for char in text:
if char in pun:
count += 1
if char.lower() in vowels:
count2 += 1
if (not char.lower() in vowels) and (not char.lower() in pun):
count3 += 1
return "count: {0}, count2: {1}, count3: {2}".format(count, count2, count3)
print(getInfo("We are in 2020."))
Output:
count: 4, count2: 4, count3: 7
Upvotes: 1
Reputation: 665
You are using return
keyword, that's, all the code below will not run and the function will returns the variable count
.
Please, verify this.
Upvotes: 0
Reputation: 13349
Return should be outside the loop.
It should be :
def getInfo(text):
pun = [".", ",", " ", "\'", "\"", "!"]
vowels = ["a", "e", "i", "o", "u"]
count = 0
count2 = 0
count3 = 0
for char in list(text):
if char in pun:
count += 1
if char.lower() in vowels:
count2 += 1
if (not char.lower() in vowels) and (not char.lower() in pun):
count3 += 1
return (count, count2, count3)
getInfo('myname.is hello world!')
# (4, 6, 12)
Upvotes: 0
Reputation: 2782
You are retuning value after checking punctuation, rest of them are ignored. So you are getting 0. Your code is valid for punctuation check.
Upvotes: 1