Syntax: Refers to the set of rules governing the structure of a programming language. In Python, these rules dictate how variables, functions, loops, and other elements should be written for correct interpretation by the interpreter.
Indentation: Unique among programming languages, Python uses indentation to define blocks of code such as loops and conditionals. Each level of indentation is denoted using four spaces.
def greet():
print("Hello, World!")
# Call the function
greet()
In this example, we define a function called greet()
. The indented lines below the function definition are part of its body.
def calculate_area(radius):
area = 3.14 * radius ** 2
return area
# Call the function with a value
print(calculate_area(5))
In this example, we create a function calculate_area()
that calculates and returns the area of a circle given its radius. We call this function with the argument 5 to print the result.
What causes it: Not defining or importing a variable before using it in your code.
# Bad code example that triggers NameError
print(my_variable)
Error message:
Traceback (most recent call last):
File "example.py", line 2, in <module>
print(my_variable)
NameError: name 'my_variable' is not defined
Solution: Define or import the variable before using it.
# Corrected code
my_variable = "Example"
print(my_variable)
Why it happens: You attempted to use a variable that has not been defined or imported.
How to prevent it: Always define or import variables at the top of your script, and check for typos in their names.
What causes it: Attempting to perform an operation on values of incompatible types.
# Bad code example that triggers TypeError
result = "5" + 3
Error message:
Traceback (most recent call last):
File "example.py", line 2, in <module>
result = "5" + 3
TypeError: can't concat str and int
Solution: Convert the numeric value to a string or vice versa before performing the operation.
# Corrected code
result = str(5) + str(3)
Why it happens: You tried to perform an arithmetic or concatenation operation on incompatible data types.
How to prevent it: Be aware of the data types you are working with and ensure they are compatible before performing operations.