python循环中使用函数break-and-continue外部循环

2024-10-02 00:27:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我是新的编程,所以我正在练习投标。现在我在练习函数。在下面的代码中,break和continue都在循环之外,我不明白为什么。我尝试了不同的方法,但我唯一能做的就是最后一段代码。为什么在循环外中断并继续?
随机导入

again = 'y'

while again == "y" :
    def main():
        print "gues a number between 0 - 10."
        nummer = random.randint(1,10)
        found = False

        while not found:
            usergues = input("your gues?")
            if usergues == nummer:
                print 'Your the man'
                found = True
            else:
                print 'to bad dude try again'

main()  
again = raw_input('would you like to play again press y to play again   press n yo exit')
if again == 'n':
    break   #here it says it is outside the loop 
elif again != 'y':
    print 'oeps i don\'t know what you mean plz enter y to play again or n to exit'
else:
continue        #this is outside loop as well

#main()

Tags: to代码inputplayifmainprintbreak
3条回答

您可能需要参考教学材料,因为您似乎误解了函数的一般用途和逻辑顺序。
你的职能应该在外部,例如:

def main():
    again = 'y'
    while again == "y" :    

您的问题再次需要缩进while循环中:

^{pr2}$

else: continue是不必要的,因为您处于循环的末尾。
但是,这只会问一次问题,您可能希望在while循环中这样做。您也不需要检查外部while循环中的again == "y",因为您在这里控制流:

    while True:
        [snip]
        again = raw_input("would you like to play again press y to play again press n to exit")
        while again not in ('y', 'n'):
            again = raw_input("oops i don't know what you mean plz enter y to play again or n to exit")
        if again == 'n':
            break

我建议不要使用空的input(),因为任何代码都可以执行,接收字符串并转换为int都是安全的(而且您可能会进行一些错误检查):

usergues = int(raw_input("your guess?"))

把它们放在一起看起来像:

def main():
    while True:    
        print "guess a number between 1 - 10."
        nummer = random.randint(1,10)

        found = False
        while not found:
            usergues = int(raw_input("your guess?"))
            if usergues == nummer:
                print 'You're the man'
                found = True
            else:
                print 'Too bad dude try again'

        again = raw_input('would you like to play again press y to play again press n to exit')
        while again not in ('y', 'n'):
            again = raw_input('oops i don\'t know what you mean plz enter y to play again or n to exit')
        if again == 'n':
            break

main()

您的循环和def都是混乱的,您需要更像:

import random

again = 'y'

while again == "y" :
    print "gues a number between 0 - 10."
    nummer = random.randint(1,10)
    found = False

    while not found:
        usergues = input("your gues?")
        if usergues == nummer:
            print 'Your the man'
            found = True
        else:
            print 'to bad dude try again'

    while True:
        again = raw_input('would you like to play again press y to play again   press n to exit')
        if again == 'n':
            break
        elif again != 'y':
            print 'oeps i don\'t know what you mean plz enter y to play again or n to exit'
        else:
            break

因为你是编程新手,我也会在我的答案中得到一些基本的提示。在

无限循环

您试图通过首先设置again = 'y'来启动一个无限循环,然后使用此变量来计算while循环。因为不改变y的值,所以最好不要使用变量来创建这个无限循环。相反,请尝试以下方法:

while True:
    (some code)

在循环中定义函数

在while循环中定义函数main()。据我所知,那是没有用的。省去第一个while循环。如果你定义了一个函数,它是永久的(很像变量),所以不需要每次都重新定义它。使用你的代码,你甚至不能调用函数,因为你永远不会结束第一个循环。在

继续/中断不在循环中

这个错误很容易自圆其说,但我们还是来吧。如果您要结束第一个循环(在本例中,您不会这样做),下一件事就是调用您的函数main()。这将产生一个数字,并让用户猜测,直到他正确。当这种情况发生时,您将退出该函数(和循环)。在

接下来,询问用户是否愿意再次播放。这只是一个输入语句。您将答案存储在变量“again”中。使用if语句进行检查(注意,这不是一个循环!)答案是什么。如果用户键入“y”,则希望用户再次播放,因此可以使用以下命令而不是使用again != 'y'

^{pr2}$

如果输入了'n',则需要退出脚本,而不是通过键入break退出脚本,因为您不在循环中,只是在If语句中。您既可以不键入任何内容,也可以不输入if语句。因为if后面没有任何内容,所以您将退出脚本。您还可以使用exit(),它将立即退出脚本。在

最后,如果这两个问题都没有得到回答,您需要重复这个问题。可以将if语句放入循环中。你可以(如果你想的话)利用休息时间继续做这件事,但你最想避免这两件事。下面是一个例子:

while True:
    again = raw_imput('y for again or n to stop')
    if again == 'y':
        main()
        exit()  # use this if you don't want to ask to play again after the 2nd game
    elif again == 'n':
        print('bye!')
        exit()
    # no need for an 'else' this way
    # every exit() can be replaced by a 'break' if you really want to

基本中断/继续使用

最后,这里是breakcontinue的一些基本用法。人们通常倾向于回避他们,但知道他们做什么是件好事。在

使用break将退出当前所处的最内部循环,但显然只能在循环内部使用它(对于循环或while循环)。在

使用continue立即重新启动当前所在的最内部循环,而不管下一个代码是什么。而且,只能在循环内部使用。在

一切都在一起

import random
again = 'y'


def main():
    print ("gues a number between 0 - 10.")
    nummer = random.randint(1,10)
    found = False
    while not found:
        usergues = input("your gues?")
        if usergues == nummer:
            print ('Your the man')
            found = True
    else:
        print ('to bad dude try again')

main()
while True:
    again = input('would you like to play again press y to play again   press n yo exit')
    if again == 'n':
        print ('bye!')
        exit()  # you could use break here too
    elif again == 'y':
        main()
        exit()  # you can remove this if you want to keep asking after every game
    else:
        print ('oeps i don\'t know what you mean plz enter y to play again or n to exit')

我希望我帮助过你!在

相关问题 更多 >

    热门问题