Where to write 'return' in code with multiple returns

Screen Link:

Hi, I’m having trouble figuring out where to place the second ‘return’ in codes with multiple ‘returns’

In My Code #1, the second ‘return’ is aligned with ‘if’ whereas in

My Code #2, the second ‘return’ is aligned with ‘for’.

What is the difference between the two? Also, does anyone have any tips on how to decide where to put the second ‘return’?

My Code #1:

def check_eng(string):
    for character in string:
        if ord(character) > 127:
            return False
        return True

My Code #2:

def check_eng(string):
    for character in string:
        if ord(character) > 127:
            return False
    return True
1 Like

The only thing you need to know is that return just stops and exits the function call and returns any value you might be providing with the return statement.

That’s pretty much it in terms of what you need to know about return as of now.

Based on that, you then look at what you want your function to do before you exit it and what you wish for your function to return after it exits.

So, looking at both the codes, what code lines will get executed and in which order before they reach the return statements?

  • For Code 1, when will your code reach return True?
  • For Code 1, when will your code reach return False?
  • For Code 2, when will your code reach return True?
  • For Code 2, when will your code reach return False?

To answer the above questions -

  • Break your code down.
  • Take a sample input for the function. Just a small one.
  • Write down what operations take place based on that input for both of your codes.
  • Write down when you hit those return statements based on those operations.
  • Compare the two.

If you get stuck again following the above process, feel free to ask further questions.

2 Likes