Home > Blockchain >  Using a 'for ... else' statement to return the loop variable
Using a 'for ... else' statement to return the loop variable

Time:10-18

I have this for...else statement code:

def someFunction():
    for i in range(first, last):
        if condition:
            return i
    else:
        return i   2

So I want to return the loop variable if certain condition happened. But if loop finished without problem then i 2 is returned instead.

The code works fine, but the ide is giving me a warning that "Local variable 'i' might be referenced before assignment".

so is there a better way to write my code?

CodePudding user response:

Consider a scenario where loop is NOT terminated by a return statement, then else block is executed since in your code variable i is local to for block and hence throws warning referenced before assignment.

CodePudding user response:

the warning from your ide is because of this case

>>> for i in []:
        print(i)
    else:
        print(i)


Traceback (most recent call last):
  File "<pyshell#94>", line 4, in <module>
    print(i)
NameError: name 'i' is not defined
>>> 

In case your range turn out to be empty them the for loop would neither create the i variable and assign it a value.

to get rip of the warning, and the potential exception, first assign i with some default value, like i=0 before you do the loop

CodePudding user response:

style 1:

var = range(first, last)

for i in var:
    if condition:
        return i
else:
    return list(var)[-1]   2  # <last-val>   2

style 2:

for i in var:
    if condition:
        return i
return i   2  # outside the 'else'

CodePudding user response:

Python follows indentation. Your else should be indent properly like below.

for i in range(first, last):
    if condition:
        return i
    else:
        return i   2
  • Related