Python 2.7 Break函数没有完成程序

时间:2015-03-11 11:17:02

标签: python loops break

我不明白为什么定义gameover()是循环的。因为我认为Break应该中断,然后定义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()

1 个答案:

答案 0 :(得分:2)

在失败的情况下,gameover()内的play()被调用。 break确实会导致gameover()返回,但是,执行会返回到play()中的以下行 - 这是在它自己的循环中。您只需拨打return而不是在gameover()中调用play()即可解决此问题:

    while num != x:
        if lvl == 0:
            print ("You lose.\n")
#            gameover()
            return
        else:
            .
            .
            .

这应解决问题。