SoFunction
Updated on 2024-10-29

An Introduction to Python Program Errors: Undefined Variables

Types of errors in Python programs

There are two types of errors in Python programs. One is syntax error. This is an error in which a statement is written in a way that does not conform to the syntax of the Python language. The second type of error is a logic error. This is an error where the program works, but does not function as expected, as in the case of a "miscalculation".

Variable undefined error

Variables in Python programs need to be defined before they can be used. If this is not done, a variable undefined error occurs. This is a syntax error.In Pycharm, syntax errors are marked with a red wavy line, as shown in Figure 1.

Figure 1 In Pycharm, syntax errors are marked with red wavy lines

Error messages for running Python programs

In Pycharm, a program that runs with an error will report an error message in the run window (i.e., the window where data is entered or results are output). Forcing the example in Figure 1 to run will present the error message shown in Figure 2.

Figure 2 Error message reported in the lower run window

In the error message, the display lists the traceback of the program. Here, the trace is not very long, but we will encounter a very long one later on. There is only one trace, and it points to line 3 in the file, which reads "print(mesage) #mesage is misspelled, missing an s", and there is an error. The file path is programmed in blue, indicating that it is a hyperlink; click on it, and the editor above lists that line of code and the code near it.

At the end of the error message, the conclusion of the error is given, NameError: name 'mesage' is not defined. Translated into Chinese, this means, NameError: variable name 'mesage' is not defined.

Learn to analyze the error messages of your Python program. Even though it's in English, you'll catch the gist of it if you read more. Using the error messages, you can locate errors and correct them faster.

Additional knowledge:python error "xxx is not defined"

Python keeps reporting "xxx is not defined" when using input() to accept a string.

For input(), it expects to be able to read a legal python expression, i.e. you must enclose the string in quotes when you type it in

The above this talk about Python program errors: variable undefined is all I have to share with you, I hope to give you a reference, and I hope you support me more.