Python 如何结束一个';试试';循环输入';而';环
我遇到了如何结束“try”循环的麻烦,这是因为我有“try”循环,下面是代码:Python 如何结束一个';试试';循环输入';而';环,python,python-3.x,Python,Python 3.x,我遇到了如何结束“try”循环的麻烦,这是因为我有“try”循环,下面是代码: import time class exe_loc: mem = '' lib = '' main = '' def wizard(): while True: try: temp_me = input('Please specify the full directory of the memory, usually it will be a
import time
class exe_loc:
mem = ''
lib = ''
main = ''
def wizard():
while True:
try:
temp_me = input('Please specify the full directory of the memory, usually it will be a folder called "mem"> ' )
if temp_me is True:
exe_loc.mem = temp_me
time.sleep(1)
else:
print('Error value! Please run this configurator again!')
sys.exit()
temp_lib = input('Please specify the full directory of the library, usually it will be a folder called "lib"> ')
if temp_lib is True:
exe_loc.lib = temp_lib
time.sleep(1)
else:
print('Invalid value! Please run this configurator again!')
sys.exit()
temp_main = input('Please specify the full main executable directory, usually it will be app main directory> ')
if temp_main is True:
exe_loc.main = temp_main
time.sleep(1)
我尝试使用break
,pass
,结束它,我甚至将它留空。我在解析时得到的是意外的EOF,我在网上搜索,他们说这是由于代码块未完成造成的。请告诉我,如果我的任何代码是错误的,谢谢
顺便说一句,我正在使用Python3,我不知道如何更具体地回答这个问题,如果您不理解,请问我。对不起,我的英语很差
编辑:解决方法是删除try
,因为我没有使用它,但我仍然想知道如何正确结束try
循环,谢谢。您还必须使用except
语句“捕获”异常,否则try没有用
所以,如果你做了如下事情:
try:
# some code here
except Exception:
# What to do if specified error is encountered
这样,如果try块中的任何位置出现异常,它将不会中断代码,但会被except捕获。您还必须使用except
语句“捕获”异常,否则try没有用
所以,如果你做了如下事情:
try:
# some code here
except Exception:
# What to do if specified error is encountered
这样,如果在try块中的任何位置出现异常,它不会破坏代码,但会被except捕获。您的问题不是中断
,而是try
子句的整体高级形状
try
需要except
或finally
块。您没有,这意味着您的try
子句实际上从未完成。因此,python一直在寻找下一位,直到到达EOF(文件末尾),这时它会抱怨
本手册将更详细地解释,但基本上您需要:
try:
do_stuff_here()
finally:
do_cleanup_here() # always runs, even if the above raises an exception
或
(您还可以同时使用除
和最终
)如果您不需要清理或异常处理,那就更容易了:只需完全去掉try
,让块直接位于该下,而为True
最后,作为一个术语:try
不是一个循环。循环是一段执行多次的代码——它是循环。try
执行一次。这是一个“子句”,而不是一个“循环”。你的问题不是中断,而是try
子句的整体、高级形状
try
需要except
或finally
块。您没有,这意味着您的try
子句实际上从未完成。因此,python一直在寻找下一位,直到到达EOF(文件末尾),这时它会抱怨
本手册将更详细地解释,但基本上您需要:
try:
do_stuff_here()
finally:
do_cleanup_here() # always runs, even if the above raises an exception
或
(您还可以同时使用除
和最终
)如果您不需要清理或异常处理,那就更容易了:只需完全去掉try
,让块直接位于该下,而为True
最后,作为一个术语:try
不是一个循环。循环是一段执行多次的代码——它是循环。try
执行一次。这是一个“子句”,而不是一个“循环”。嗨!谢谢你的回复。那么你的意思是我必须指定一个,除了,才能正确地结束尝试。仅供参考,这是一个尝试声明,而不是loop@SvenHakvoort我猜你大部分时间都在用Java或类似的语言?:-)在python中,我相信标准术语是“引发”异常,而不是“抛出”。(我犯了同样的错误,因为我主要用Java编程。)嗨!谢谢你的回复。那么你的意思是我必须指定一个,除了,才能正确地结束尝试。仅供参考,这是一个尝试声明,而不是loop@SvenHakvoort我猜你大部分时间都在用Java或类似的语言?:-)在python中,我相信标准术语是“引发”异常,而不是“抛出”。(我犯了同样的错误,因为我主要使用Java编程。)这不是有效的python语法&try
不创建循环这不是有效的python语法&try
不创建循环