简体   繁体   中英

Continuing a while loop after breaking a nested for loop

I'm looking for a more pythonic way to continue a while loop after meeting some criteria in a nested for loop. The very clunky code that has worked for me is:

tens = ['30','40','50','60','70','80','90','00']
z=0
while z==0:
    num = input('Please enter a number: ')
    z=1    
    for x in tens:
        if num[0]=='0' or x in num:
            print('That was an invalid selection, please try again.\n')
            z=0  # There has GOT to be a better way to do this!
            break
print(num+' works, Thank You!')

I can use try/except as answered in this question :

tens = ['30','40','50','60','70','80','90','00']
while True:
    num = input('Please enter a number: ')  
    try:
        for x in tens:
            if num[0]=='0' or x in num:
                print('That was an invalid selection, please try again.\n')
                raise StopIteration
    except:
        continue
    break
print(num+' works, Thank You!')

The challenges I'm facing are

a) continue the while loop (request a new input) when the if is satisfied (in other words, break the for loop and continue the while loop in the same step)

b) run the tens iterable from scratch with every new input tested.

Note: this problem relates to Reddit Challenge #246 Letter Splits

UPDATE: incorporating answer supplied by Håken Lid, code becomes

tens = ['30','40','50','60','70','80','90','00']
while True:
    num = input('Please enter a number: ')
    if num[0]=='0' or any(t in num for t in tens):
        print('That was an invalid selection, please try again.\n')
        continue
    break
print(num+' works, Thank You!')

I haven't solved the "break/continue from a nested for-loop" but substituting the loop with an any() function definitely worked for me.

Your for loop is not needed. Just use in keyword. But apart from that your use of break is fine.

tens = ['30','40','50','60','70','80','90','00']
while True:
    num = input('Please enter a number: ')
    if num in tens:
       break
    print('That was invalid selection, please try again.\n')
print(num+' works, Thank You!')

In most of the cases having nested loops is bad design.

Your functions always should be small as possible. Applying to that rule you will never break first rule of SOLID (Single responsible principle).

Your code may look like this:

tens = ['30','40','50','60','70','80','90','00']

def main():
    while 1:
        num = input('Please enter a number: ')
        if nested_test(num):
            print('That was an invalid selection, please try again.\n')
            break

def nested_test(num):
    for x in tens:
        if <some test>:
            return True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM