Identify Invalid Identifier Names
In this step, we will focus on identifying invalid identifier names in Python. Understanding what makes an identifier invalid is just as important as knowing the rules for valid names. Attempting to use an invalid identifier will result in a SyntaxError when you try to run your Python code.
Let's create a new Python file named invalid_identifiers.py in the ~/project directory using the VS Code editor.
In the invalid_identifiers.py file, type the following code. This code contains examples of invalid identifier names. We will intentionally include these to see the errors they produce.
## Invalid identifier: starts with a digit
## 1variable = 10
## Invalid identifier: contains a space
## my variable = "hello"
## Invalid identifier: contains a special character (@)
## user@name = "Alice"
## Invalid identifier: contains a special character (-)
## product-id = "XYZ123"
## Invalid identifier: using a Python keyword
## class = "Math"
## Invalid identifier: using another Python keyword
## for = 100
## Invalid identifier: contains a special character ($)
## total$amount = 50.75
## Invalid identifier: contains a special character (%)
## discount%rate = 0.15
print("Attempting to define invalid identifiers will cause a SyntaxError.")
Save the file by pressing Ctrl+S (or Cmd+S).
Now, let's try to run this Python script from the terminal. Make sure you are in the ~/project directory and execute the following command:
python invalid_identifiers.py
Since all the invalid identifiers are commented out, the script will run without errors and print the message.
Attempting to define invalid identifiers will cause a SyntaxError.
Now, let's uncomment one of the invalid identifiers to see the error. Remove the # from the beginning of the line ## 1variable = 10. The line should now be 1variable = 10.
Save the file again.
Now, run the script again:
python invalid_identifiers.py
This time, you should see a SyntaxError indicating that the identifier is invalid because it starts with a digit.
File "/home/labex/project/invalid_identifiers.py", line 4
1variable = 10
^
SyntaxError: invalid decimal literal
You can try uncommenting other invalid identifiers one by one and running the script to see the different types of SyntaxError messages they produce. Remember to comment out the previous invalid identifier before uncommenting the next one to isolate the error.
This step helps you recognize common mistakes when naming identifiers and understand the importance of following the naming rules to avoid syntax errors.