Syntax errors occur when the Python interpreter encounters code that does not follow the correct syntax rules of the language. The most common causes of syntax errors are missing parentheses, incorrect indentation, or invalid characters.
# SyntaxError: Missing closing parenthesis
print("Hello, world!"
# Add a closing parenthesis
print("Hello, world!")
Name errors occur when you try to use a variable or a function that has not been defined or is out of scope.
# NameError: 'x' is not defined
result = x + 5
# Define the variable 'x' before using it
x = 10
result = x + 5
Indentation errors occur when the code is not indented properly, typically within a block of code such as a loop or a function definition.
# IndentationError: unexpected indent
for i in range(5):
print(i)
# Indent the 'print' statement to match the 'for' loop
for i in range(5):
print(i)
Type errors occur when you perform an operation on incompatible data types or pass the wrong number of arguments to a function.
# TypeError: unsupported operand type(s) for +: 'int' and 'str'
result = 5 + "hello"
# Convert the integer to a string before concatenating
result = str(5) + "hello"
Understanding common errors and knowing how to fix them is essential for debugging and maintaining your Python code effectively.