Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

python - Break out of a while loop using a function

Is there any way to break out of infinite loops using functions? E.g.,

# Python 3.3.2
yes = 'y', 'Y'
no = 'n', 'N'
def example():
    if egg.startswith(no):
        break
    elif egg.startswith(yes):
        # Nothing here, block may loop again
        print()

while True:
    egg = input("Do you want to continue? y/n")
    example()

This causes the following error:

SyntaxError: 'break' outside loop

Please explain why this is happening and how this can be fixed.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As far as I'm concerned you cannot call break from within example() but you can make it to return a value(eg : A boolean) in order to stop the infinite loop

The code:

yes='y', 'Y'
no='n', 'N'

def example():
    if egg.startswith(no):
        return False # Returns False if egg is either n or N so the loop would break
    elif egg.startswith(yes):
        # Nothing here, block may loop again
        print()
        return True # Returns True if egg is either y or Y so the loop would continue

while True:
    egg = input("Do you want to continue? y/n")
    if not example(): # You can aslo use "if example() == False:" Though it is not recommended!
        break

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...