Reputation: 151
I'm in trouble about how to end a 'try' loop, which is occurred since I have the 'try', here is the code:
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)
I tried end it by using break
, pass
, and I even leaves it empty what I get is Unexpected EOF while parsing
, I searched online and they said it is caused when the code blocks were not completed. Please show me if any of my code is wrong, thanks.
Btw, I'm using python 3 and I don't know how to be more specific for this question, kindly ask me if you did not understand. Sorry for my poor english.
EDIT: Solved by removing the try
because I'm not using it, but I still wanna know how to end a try
loop properly, thanks.
Upvotes: 0
Views: 82
Reputation: 43391
Your problem isn't the break
, it's the overall, high-level shape of your try
clause.
A try
requires either an except
or a finally
block. You have neither, which means your try
clause is never actually complete. So python keeps looking for the next bit until it reaches EOF (End Of File), at which point it complains.
The python docs explain in more detail, but basically you need either:
try:
do_stuff_here()
finally:
do_cleanup_here() # always runs, even if the above raises an exception
or
try:
do_stuff_here()
except SomeException:
handle_exception_here() # if do_stuff_here raised a SomeException
(You can also have both the except
and finally
.) If you don't need either the cleanup or the exception handling, that's even easier: just get rid of the try
altogether, and have the block go directly under that while True
.
Finally, as a terminology thing: try
is not a loop. A loop is a bit of code that gets executed multiple times -- it loops. The try
gets executed once. It's a "clause," not a "loop."
Upvotes: 1
Reputation: 3621
You have to also 'catch' the exception with the except
statement, otherwise the try has no use.
So if you do something like:
try:
# some code here
except Exception:
# What to do if specified error is encountered
This way if anywhere in your try block an exception is raised it will not break your code, but it will be catched by your except.
Upvotes: 1