I am a bit new in python, and have just learned about the try except else and finally statement.
try:
x=int(input("enter a number:")
except:
print("you entered a wrong type of input, make sure to enter an integer value")
else:
print(f"running in else : {x}")
finally:
print(f"finally : {x 2}")
This will cause another exception in finally block NameError name 'x' is not defined
if I enter anything other than an integer value in my input statement
Does it mean we have to put all that is related to x in the else block and all that have nothing to do with x, in the finally block?
My actual script is very long but I'm trying to understand this concept from a smaller example
Is this a right intuition?
Please suggest me if otherwise
CodePudding user response:
I am inclined to think that you would want to give the user a second chance, and a third, and ...
So why not wrap it in a while-loop to enforce the presence of an x which is an integer at the end:
x=None
while x is None:
try:
x=int(input("enter a number:"))
except ValueError:
print(f"You entered a wrong type of input, make sure to enter an integer value")
CodePudding user response:
Finally blocks executes No matter what (unless you destory the laptop/PC).
No matter what happened previously, the final-block is executed once the code block is complete and any raised exceptions handled. Even if there's an error in an exception handler or the else-block and a new exception is raised, the code in the final-block is still run.
But, In this case you can use flags
inside the final
statement.
final = True #Flag true
try:
x=int(input("enter a number:"))
except:
print("you entered a wrong type of input, make sure to enter an integer value")
final = False #Flase if except
else:
print(f"running in else : {x}")
finally:
if final:
print(f"finally : {x 2}")