0

I have a counter function, counter(), which is supposed to first count to 2 and return one function h() and then continue counting to 3 and return the function g() and break.

def h():

    return "hi"

def g():

    return "hallo"

def counter():
    i = 0
    # If i is equal or less than 2, return the function h() and continue
    while i <= 2:
        i = i +1
        return h(),i
        continue

        # If i equals 3, return function g() and break/end counting
        # The current issue with this code is that the function g()
        # isn't returned and the condition itself doesn't seem to
        # respond, or count up to 3 from 2.

        if i == 3:

            return g()



    return i
print counter()
5
  • 3
    After a function returns, there is no "and then". It's returned. Finished. Perhaps you mean to write a generator (with yield instead of return) but it doesn't look like that from the way you call it. Commented Feb 24, 2014 at 11:32
  • Is it possible to have several returns in some nested conditional solution though? Commented Feb 24, 2014 at 11:35
  • Sure, but only of them will actually return after any function call. Commented Feb 24, 2014 at 11:39
  • What exactly should print counter() print? Commented Feb 24, 2014 at 13:12
  • It shoud pass indexes 0,1 to h() and wait until they are returned from h() with new values and then multiply those values with the fourth item, index 3 by passing index 3 to the g() function where the multiplication of values for (0+1)*3 is done, equal to (a+b)* d. Commented Feb 24, 2014 at 13:33

2 Answers 2

1
return h(),i

the above line returns from the function, and the rest of the code is not run.

are you looking for print() ?

Sign up to request clarification or add additional context in comments.

1 Comment

I'm trying to avoid print since the h() function is actually a function that needs to be returned, not printed, since it has it's own loop throung some items in a stack, with print it loops through the whole stack.
1

Your problem is the return statement.

When a return statement is encountered the function terminates, and then passes the return value to the caller (or None).

Which means your code will only work until the first return is encountered, and then your loop will exit.

Perhaps you are looking for yield or print?

Comments

Your Answer

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.