🐍 When an error is reported by Python, you certainly don't want the code to stop abruptly. You would want some actions to be taken if an error is reported. For this, 'Try' is used in Python.
'Try' executes a code. 'Except' captures errors and carries out actions when a certain or any error is reported in the lines executed by Try. 'Else' is optional and follows Except. Lines in Else is executed if no errors are reported. 'Finally' comes at the end and is optional too. Lines in Finally are executed irrespective of errors found or not.
'Try' executes a code. 'Except' captures errors and carries out actions when a certain or any error is reported in the lines executed by Try. 'Else' is optional and follows Except. Lines in Else is executed if no errors are reported. 'Finally' comes at the end and is optional too. Lines in Finally are executed irrespective of errors found or not.
Example:
#Runs on Jupyter Notebook
while True:
try:
result = int(input("Provide an integer:"))
except:
print("That is not an integer.")
continue
else:
print(f"The integer you entered is {result}")
break
finally:
print("Let's do it again.")
'Continue' and 'Break' comes to use when a while loop is used. Since we wanted to repeat the task again and again until an integer is input by user, we have used 'While' loop. Break is used to end while loop abruptly. Continue is used to inform our program to go on without stopping.
Comments
Post a Comment