Python: Exceptions & Errors - that's what they mean
If errors and exceptions in Python end a program spontaneously, that's pretty annoying. We explain what you can do in the case of exceptions or errors when programming with Python.
Python: Fix syntax errors
You must have noticed errors, such as syntax errors, when programming. However, these can be easily repaired:
- The compiler shows you where the error is.
- In Python IDLE you can check your program for syntax errors with [Alt] + [X].
Python: what are exceptions?
Exceptions occur during the execution of the program.
- An example of this is division by zero. If you execute the "10 * (1/0)" command in Python, there is nothing wrong with this. However, the "ZeroDivisionError" is output because Python cannot divide by zero.
- The "NameError" also occurs very often if, for example, you forgot to define a variable beforehand or made a typing mistake.
- You also cannot offset a number that is stored in a string and a number that is stored in an integer. You will receive the "TypeError".
Python: You can do that against exceptions
So that the Python program does not hang completely due to a small error, you can easily modify your code:
- As an example, a number should be entered and converted into an integer.
- First write "while True:" and below it, shifted to the right with the tab key, the command "try:".
- With this try command you can now insert the actual command: "x = int (input (" Please enter a number: "))". Below you should insert the "break" command.
- In addition to the try command, you must also add the "except ValueError:" command to the while loop. Under this command you can insert a command again, such as a print command. However, you should not add a break command here.
- The while loop asks for an input an infinite number of times. If this input is a letter, Python will trigger the ValueError and the loop will start over. If the input is a number, the break command ends the loop.
More tips about Python in the CHIP guides
Tip: You can find further programming tutorials on our Python programming language topic page. There we will show you, for example, how you can use the list append function in Python.