0

I want the function to return two types of value, string and integer when counting vowels in a word. Upon invoking I'm getting only the y value, but not the x. Can you explain why is this happening?

def cnt_vow(s):
 x = 0
 y = ''
 for char in s:
 if char in 'aeuio':
 y = y + char
 x = x + 1
 return y 
 return x
cnt_vow('hello')

expected: 'eo', 2

was: 'eo'

Martijn Pieters
1.1m326 gold badges4.2k silver badges3.5k bronze badges
asked Oct 27, 2012 at 15:17

3 Answers 3

2

If you want both, try returning a tuple

return x,y

return always leaves the current function, so code after it will never be executed.

answered Oct 27, 2012 at 15:18
Sign up to request clarification or add additional context in comments.

2 Comments

yes, it works that way. So the return command just returns the value from the loop without even noticing the second return statement?
@minerals: Correct. Read return x as 'return x to where I was called, and leave this place now!'
2

You'll have to use a tuple to return multiple values:

return (y, x)

where the parenthesis are usually optional.

When calling this function, you can then unpack the two values again:

vowels, count = cnt_vow('hello')

Once python sees a return statement the function execution ends, a second statement is never reached.

answered Oct 27, 2012 at 15:19

Comments

1

Once your code hits the first return statement, it returns the specified value immediately.

What you're looking for is:

 return y, x
answered Oct 27, 2012 at 15:19

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.