Python 2.7 Break函数没有结束程序

Python 2.7 Break function doesn't finish program

我不明白为什么 define gameover() 会循环。因为我认为 Break 应该 break While,然后定义 gameover() 完成。之后什么也没有,这意味着该程序应该终止。 我认为可以重写,但我想了解这段代码到底出了什么问题。谢谢。

import random
import sys

def play():
    print """\
    ************************************
    * "Guess the number" welcomes you! *
    *                                  *
    *        Difficulty Levels:        *
    *                                  *
    *  1 - Easy (you have 5 attempt)   *
    *  2 - Normal (you have 3 attempt) *
    *  3 - Hard (you have 1 attempt)   *
    *                                  *
    *             Let's go!            *
    ************************************
    """
    lvl = input("Select Difficulty Level: ")
    if lvl == 1:
        lvl = 5
    elif lvl == 2:
        lvl = 3
    elif lvl == 3:
        lvl = 1

    num = random.randrange(1,10)
    x = 0

    while num != x:
        if lvl == 0:
            print ("You lose.\n")
            gameover()
        else:
            x = input("Enter your number: ")
            if num > x:
                print ("It's bigger!\n")
            if num < x:
                print ("It's smaller!\n")
            pass
            lvl = lvl - 1

    print ("You win!")
    print num

def gameover():
    while True:
        restart = input("Would you like to play again? Please enter '1' for YES or '2' for NO: ")
        if restart==1:
            play()
        else:
            print "Thanks for playing!"
            break

def main():
    play()
    gameover()

main()

在失败的情况下,gameover()play() 中调用。 break 确实导致 gameover() 到 return,但是,执行 returns 到 play() 中的下一行 - 这是在它自己的循环中。您可以通过简单地调用 return 而不是在 play():

中调用 gameover() 来解决这个问题
    while num != x:
        if lvl == 0:
            print ("You lose.\n")
#            gameover()
            return
        else:
            .
            .
            .

这应该可以解决问题。