=
operator. For example:python
my_variable = "Hello, World!"
print(my_variable) # Outputs: Hello, World!
# Creating and printing a list of numbers
my_list = [1, 2, 3, 4]
print(my_list) # Outputs: [1, 2, 3, 4]
# Creating and printing a dictionary with student data
student_data = {
"name": "Alice",
"age": 25,
"city": "New York"
}
print(student_data) # Outputs: {'name': 'Alice', 'age': 25, 'city': 'New York'}
```
- Step-by-step explanations: After creating a variable, you can perform various operations on it, such as arithmetic calculations (e.g., adding, subtracting, multiplying, or dividing), string concatenation, and more.
What causes it: This error occurs when you try to use an undefined variable in your code.
print(undefined_variable)
Error message:
NameError: name 'undefined_variable' is not defined
Solution: Make sure that the variable exists and is properly spelled before using it.
my_variable = "Hello, World!"
print(my_variable) # Outputs: Hello, World!
Why it happens: The interpreter does not know about the variable because it hasn't been defined yet.
How to prevent it: Always declare your variables before using them in your code.
What causes it: This error occurs when you try to perform an operation on objects of incompatible types.
my_number = 42
my_string = "Hi"
print(my_number + my_string)
Error message:
TypeError: can't concatenate 'int' and 'str' objects
Solution: Make sure that the operands have compatible types before performing operations on them.
my_number = 42
my_string = "Hi"
print(str(my_number) + my_string) # Outputs: '42Hi'
Why it happens: The interpreter cannot perform the operation because the operands have different types.
How to prevent it: Be aware of the data types and their compatibility when performing operations in your code.
What causes it: This error occurs when there is a mistake in the syntax (the structure) of your Python code.
print(my_number = 42)
Error message:
SyntaxError: invalid syntax
Solution: Make sure that you are using valid Python syntax when writing your code.
my_number = 42
print(my_number) # Outputs: 42
Why it happens: The assignment operator =
should be placed after the variable name, not before.
How to prevent it: Always follow Python's syntax rules when writing your code.
myVariable
or my_variable
.=
operator.