can a function return twice inside a for loop statement

Viewed 779

I have the following function that check whether a regex input is legit:

import re

def isvalid_regex():
    for _ in range(2):
        try:
            re.compile(input())
            return True
        except re.error:
            return False

The problem here is that I don't get a double input as I would expect by range(2). The function returns me False or True and exits. I guess a function cannot repeat return statements for the number of times of a for loop in range(x) exists right ? My goal is to have a double input and a double True or False return. For example as output:

True
False
2 Answers

return statement ends the function.
You have two options:

1. generator

You can learn about generator in: https://docs.python.org/3/howto/functional.html?#generators

def isvalid_regex():
    for _ in range(2):
        try:
            re.compile(input())
            yield True
        except re.error:
            yield False


for x in isvalid_regex():
    print(x)

input and output:

t
True
\\\
False

2. Build a list and return once

def isvalid_regex():
    results = []
    for _ in range(2):
        try:
            re.compile(input())
            results.append(True)
        except re.error:
            results.append(False)
    return results


for x in isvalid_regex():
    print(x)

input and output:

t
\\\
True
False

Note:

You might noticed that the order of execution is different. You can choose what fits your situation.

It is not clear what you want to do.

Functions do return only once, but they can return sequences, so you could use that "trick" for returning multiple values.

For example:

a = [1, 2]


def squarer(items):
    return [item ** 2 for item in items]


print(squarer(a))
# [1, 4]

If you want to exit from a function multiple times but then come back to its internal state (for convenience) then you should use a generator. To do so, you replace the return statement with a yield one. With this method, once a yield statement is reached, you get a value. Subsequent values from the generator can be obtained with next() or by using the generator in a for loop.

For example:

def squarer(item):
    for x in range(item):
        yield x ** 2


itr = squarer(4)
# <generator object squarer at 0x7f145c421eb8>
print(itr)
for x in itr:
    print(x)
# 0
# 1
# 4
# 9
Related