When writing programs, it is unlikely that your code will work perfectly on the first attempt. Finding and fixing errors is called debugging. There are three main types of errors.
A syntax error means your code breaks the rules of the Python language. The program will not run at all.
Common syntax errors include:
Print instead of print)Print("Hello")Capital P — Python is case-sensitive. The correct version is:
print("Hello")
print("Hello world')Mismatched quotes (double quote opening, single quote closing):
print("Hello world")
print("The answer is " + 42)Cannot concatenate a string and an integer. Fix with:
print("The answer is " + str(42))
A runtime error occurs while the program is running. The syntax is valid, but something goes wrong during execution.
Common runtime errors:
int("hello"))number = int(input("Enter a number: "))
result = 10 / number # Runtime error if user enters 0!
print(result)
Python raises a ZeroDivisionError because you cannot divide by zero. The program crashes at that line.
A logical error means the program runs without crashing, but produces the wrong result. These are the hardest to find because Python does not report them.
base = float(input("Enter the base: "))
height = float(input("Enter the height: "))
perimeter = base + height + base + base # Wrong formula!
print("The perimeter is", perimeter)
The formula for the perimeter of a rectangle should be 2 * (base + height), but the code adds base three times instead. The corrected line is:
perimeter = 2 * (base + height)
print() to check what your variables contain