我是新的编程,所以我正在练习投标。现在我在练习函数。在下面的代码中,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()
您可能需要参考教学材料,因为您似乎误解了函数的一般用途和逻辑顺序。
你的职能应该在外部,例如:
您的问题再次需要缩进while循环中:
^{pr2}$else: continue
是不必要的,因为您处于循环的末尾。但是,这只会问一次问题,您可能希望在while循环中这样做。您也不需要检查外部while循环中的
again == "y"
,因为您在这里控制流:我建议不要使用空的
input()
,因为任何代码都可以执行,接收字符串并转换为int
都是安全的(而且您可能会进行一些错误检查):把它们放在一起看起来像:
您的循环和
def
都是混乱的,您需要更像:因为你是编程新手,我也会在我的答案中得到一些基本的提示。在
无限循环
您试图通过首先设置
again = 'y'
来启动一个无限循环,然后使用此变量来计算while循环。因为不改变y的值,所以最好不要使用变量来创建这个无限循环。相反,请尝试以下方法:在循环中定义函数
在while循环中定义函数
main()
。据我所知,那是没有用的。省去第一个while循环。如果你定义了一个函数,它是永久的(很像变量),所以不需要每次都重新定义它。使用你的代码,你甚至不能调用函数,因为你永远不会结束第一个循环。在继续/中断不在循环中
这个错误很容易自圆其说,但我们还是来吧。如果您要结束第一个循环(在本例中,您不会这样做),下一件事就是调用您的函数
main()
。这将产生一个数字,并让用户猜测,直到他正确。当这种情况发生时,您将退出该函数(和循环)。在接下来,询问用户是否愿意再次播放。这只是一个输入语句。您将答案存储在变量“again”中。使用if语句进行检查(注意,这不是一个循环!)答案是什么。如果用户键入“y”,则希望用户再次播放,因此可以使用以下命令而不是使用
^{pr2}$again != 'y'
:如果输入了'n',则需要退出脚本,而不是通过键入
break
退出脚本,因为您不在循环中,只是在If语句中。您既可以不键入任何内容,也可以不输入if语句。因为if后面没有任何内容,所以您将退出脚本。您还可以使用exit()
,它将立即退出脚本。在最后,如果这两个问题都没有得到回答,您需要重复这个问题。可以将if语句放入循环中。你可以(如果你想的话)利用休息时间继续做这件事,但你最想避免这两件事。下面是一个例子:
基本中断/继续使用
最后,这里是
break
和continue
的一些基本用法。人们通常倾向于回避他们,但知道他们做什么是件好事。在使用
break
将退出当前所处的最内部循环,但显然只能在循环内部使用它(对于循环或while循环)。在使用
continue
将立即重新启动当前所在的最内部循环,而不管下一个代码是什么。而且,只能在循环内部使用。在一切都在一起
我希望我帮助过你!在
相关问题 更多 >
编程相关推荐