In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "what are the common problems of Python programmers". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn what are the common problems of Python programmers.
Pragmatic errors
Let's start with the basics, from what happens before those who are new to programming delve into grammar. At first, if you have already made up some programs, the following may seem very simple. If you have ever tried to teach beginners how to program, they may not be so simple.
The Python code entered at the interactive prompt
In the > interactive prompt, you can only enter the Python code, not the system command. From time to time, people type emacs,LS at this prompt, or commands like editing, which are not Python code. There are ways to invoke system commands (such as os.system and os.popen) in Python code, but not as directly as entering commands directly. If you want to start a Python file in an interactive prompt, use the import file instead of the system command python file.py.
Print statements (only) are required in the file
Because the interactive interpreter automatically outputs the results of the expression, you don't need to type the complete print statement interactively. This is a great feature, but keep in mind that in code files, you usually have to use print statements to see the output.
Be careful with the automatic extension in Windows
If you use notepad to edit code files in Windows, choose the type "all files" (all files) carefully when you keep them, and explicitly add a .py suffix to your files. Otherwise, notepad will add a .TXT extension to your file, making it impossible to run the program in some startup methods. To make matters worse, word processors such as words or WordPad add format characters by default, which are not recognized by Python syntax. So remember, always select "all files" (all files) under Windows and save them as plain text, or use a more "programming friendly" text editing tool, such as IDLE. In IDLE, remember to manually add the .py extension when saving.
The problem of clicking the icon under the window
Under the window, you can start a Python program by clicking on a Python file, but this can sometimes be problematic. First of all, the output window of the program disappears at the end of the program. To keep it from disappearing, you can add a call to raw_input () at the end of the file. In addition, remember that if there is a mistake, the output window disappears immediately. If you want to see your error message, call your program in another way. For example, boot from the system command line, use the import statement from the prompt, or the options in the IDLE menu, and so on.
Import is only valid for the first time
You can run it by entering a file in an interactive prompt, but this only works once in a session. The next import simply returns the loaded module. If you want to force Python to reload a file, call the function overload (module) to do this. Please use parentheses for reloading, but do not use parentheses for imports.
Blank lines (only) work in interactive prompts
Both blank lines and comments are ignored in the module file, but when you type code in the interactive prompt, the blank line indicates the end of a compound statement in other words, the blank line tells the interactive prompt that you have completed a compound statement. Don't type enter until you're really done. In fact, when you start a new statement, you need to type a blank line to end the current statement-the interactive prompt runs only one statement at a time.
Code error
Once you start writing serious Python code, the next bunch of pitfalls are even more dangerous. These are basic code errors across language features that often haunt careless programmers.
Don't forget the colon.
This is the most common mistake for novice programmers: don't forget to put a colon ":" at the end of the starting statement of the compound statement (the first line of the if,while,for wait statement). You may forget this at first, but it will soon become a subconscious habit. 75% of the students in the class can remember this that day.
Initialization variable
In Python, the name in an expression cannot be used until it is assigned, which is intentional: this avoids some typing errors and avoids the question of what the default should be (0, none, [],?). Remember to initialize the counter to 0, the list to [], and so on.
Start with the first column
Be sure to start with the top-level, unnested code in the leftmost first column. This includes code that is not nested in the module file, and code that is not nested in the interaction prompt. Python uses indentation to distinguish nested code segments, so the space to the left of your code means nested code blocks. Spaces are usually ignored except for indentation.
Indent consistent
Avoid mixing tabs and spaces to indent in the same code block unless you know how the system running your code handles tags. Otherwise, what looks like tag indentation in your editor may be seen as some white space insurance, with all tags or all spaces indented in each block of code; it's up to you to decide how much to use.
Use parentheses when calling a function
Whether a function requires arguments or not, you must add a pair of parentheses to call it. That is, functions that use functions () instead of function.Python are simply objects with special functions (calls), which are triggered by parentheses. Like all objects, they can be assigned to variables and use them indirectly: X = function:x (). In Python training, such errors often occur in the operation of files. You'll see a novice using file.close to close a problem instead of file.close (). Because it is legal to refer to a function in Python without calling it, file.close without parentheses is silently successful, but the file is not closed!
Do not use expressions or paths when importing
Use the folder path or file extension on the system's command line, but not in the import statement. That is, use import mod instead of import mod.py, or import dir / mod.py. In practice, this is probably the second most common mistake made by beginners. Because modules have suffixes other than .py (for example, pyc files), forcing a suffix is not only ungrammatical, but also meaningless. The format of the directory path related to the system is derived from the settings of your module search path, not the import statement. You can use dots in the file name to point to the package's subdirectories (for example, import dir1.dir2.mod), but the leftmost directory must be found through the module search path, and there is no other path format in the import. The incorrect statement import mod.py is considered by Python to record a package that loads a module mod, then attempts to find a module called pyridine in a directory called MOD, and may end up with a series of inexplicable error messages.
Don't write the ccode in Python
Here are some tips for unfamiliar Python ç programmers:
When testing with conditions, do not enter parentheses (for example, if (X = = 1):). It doesn't hurt to add parentheses if you like, but it's completely superfluous here.
Don't end your statement with a semicolon which is technically legal in Python, but it's useless unless you want to put many statements on the same line (for example, X = 1). Y = 2; Z = 3).
Do not embed assignment statements in the conditional test of the while loop (for example, while ((x = next ()!)! = NULL)). In Python, statements cannot appear where expressions are needed, and assignment statements are not an expression.
Programming error
Finally, I'll talk about the problems you might encounter when you use more functions (data types, functions, modules, classes, etc.) in Python. Due to the limited space, it is as concise as possible, especially for some advanced concepts. For more details, please read the Learning Python, 2nd edition of "Tips" and "Gotchas" chapter.
The call to open the file does not use the module search path
When you call open () in Python to access an external file, the module search path is not used in Python to locate the target file. It will use the absolute path you provide, or assume that the file is in the current working directory. The module search path only serves the module load.
Different types correspond to different methods.
List methods cannot be used on strings, and vice versa. In general, method calls are related to data types, but internal functions are usually available on many types. For example, the reverse method of a list is only useful for a list, but the LEN function works for any object with length
Immutable data types cannot be changed directly
Remember that you cannot directly change an immutable object (for example, tuple, string):
T = (1,2,3) T [2] = 4 # error
Build a new object with slices, joins, etc., and assign the value of the original variable to it according to requirements because useless memory is automatically reclaimed in Python, so this is not as wasteful as it seems:
T = T [: 2] + (4,) # No problem: t becomes (1, 2, 4)
Use simple for loops rather than simultaneous or scoping
When you want to traverse all the elements of an ordered object from left to right, using a simple for loop (for example, for x in seq:) is easier to write than a while--or range--based counting loop, and usually runs faster unless you absolutely need it, try to avoid using scope in a loop. Let Python solve the labeling problem for you in the following example, all three loop structures are fine, but the first one is usually better; in Python, simplicity is paramount.
S = "lumberjack" for c in S: print c # simplest for i in range (len (S)): print S [I] # too much I = 0 # too much while I
< len(S): print S[i]; i += 1 不要试图从那些会改变对象的函数得到结果 诸如像方法list.append()和list.sort()一类的直接改变操作会改变一个对象,但不会将它们改变的对象返回出来(它们会返回无);正确的做法是直接调用它们而不要将结果赋值经常会看见初学者会写诸如此类的代码: mylist = mylist.append(X) 目的是要得到附加的结果,但是事实上这样做会将无赋值给MYLIST,而不是改变后的列表。更加特别的一个例子是想通过用排序后的键值来遍历一个字典里的各个元素,请看下面的例子: D = {...}for k in D.keys().sort(): print D[k] 差一点儿就成功了--keys方法会创建一个键的列表,然后用某种方法来将这个列表排序 - 但是因为某种方法会返回无,这个循环会失败,因为它实际上是要遍历无(这可不是一个序列)要改正这段代码,将方法的调用分离出来,放在不同的语句中,如下: Ks = D.keys()Ks.sort()for k in Ks: print D[k] 只有在数字类型中才存在类型转换 在的Python中,一个诸如123 + 3.145的表达式是可以工作的 - 它会自动将整数型转换为浮点型,然后用浮点运算但是下面的代码就会出错了。: S = "42"I = 1X = S + I # 类型错误 这同样也是有意而为的,因为这是不明确的:究竟是将字符串转换为数字(进行相加)呢,还是将数字转换为字符串(进行连接)呢在Python的中,我们认为"明确比含糊好"(即,EIBTI(明确比隐含更好)),因此你得手动转换类型: X = int(S) + I # 做加法: 43X = S + str(I) # 字符串联接: "421" 循环的数据结构会导致循环 尽管这在实际情况中很少见,但是如果一个对象的集合包含了到它自己的引用,这被称为循环对象(cyclic object)。如果在一个对象中发现一个循环,Python会输出一个[... ],以避免在无限循环中卡住: >> > L = ['grail'] # referencing L itself in L will > L.append (L) # create a loop in the object > L [' grail', [...]]
In addition to knowing that these three points represent loops in the object, this example is also worth learning. Because you may inadvertently appear such a loop structure in your code and cause your code to go wrong. If necessary, maintain a list or dictionary to represent the objects you have visited, and then check it to see if you have encountered a loop.
The assignment statement does not create a copy of the object, just a reference
This is one of the core ideas of Python, and sometimes it can lead to mistakes when the behavior is wrong. In the following example, a list object is assigned to a variable named large, which is then referenced in the list. Changing the large size internally will also change the object referenced by the medium size, because they both point to the same object.
> > L = [1, 2, 3] # shared list objects > M = ['Xboxes, L,' Y'] # embeds a reference to L > M ['Xboxes, [1, 2, 3],' Y'] > > L [1] = 0 # also changes M > > M [[1, 0, 3],'Y']
Usually this is important only in slightly larger programs, and these shared references are usually what you need. If not, you can explicitly create a copy of them to avoid shared references; for lists, you can create a top-level copy by using a slice of an empty list:
> L = [1, 2, 3] > M = ['X', L [:],'Y'] # embeds a copy of L > L [1] = 0 # only changes L, but does not affect M > > L [1,0,3] > > M ['Xboxes, [1,2,3],' Y']
The range of slices starts from the default 0 to the maximum length of the sliced sequence. If both are omitted, the slice extracts all elements in the sequence and creates a top-level copy (a new, unshared object). For dictionaries, use the dictionary's dict.copy () method.
By default, Python treats the variable names assigned in a function as local, and they exist in the scope of the function and only when the function is running. Technically, pythons recognize local variables statically when compiling DEF code, not when they encounter assignments at run time. If you do not understand this point, it will cause people to misunderstand. For example, take a look at the following example, what happens when you assign a variable after a reference:
> X = 99 > def func ():... Print X # does not exist at this time. > func () # error!
You get an "undefined variable name" error, but the reason is subtle. When compiling this code, Python encounters a statement that assigns a value to X and assumes that X will be treated anywhere in this function. A local variable name, but then when the function is actually run, the assignment statement does not occur when the print statement is executed, so the Python reports an "undefined variable name" error.
In fact, what the previous example wants to do is vague: do you want to output the global X first and then create a local X, or is it a program error if you really want to output the global X, you need to declare it in a global statement, or refer to it by the name of the envelope module.
Default parameters and mutable objects
When the DEF statement is executed, the value of the default parameter is parsed and saved only once, not each time the function is called. This is usually what you want, but because the default value needs to keep the same object every time it is called, you should be careful when trying to change the variable default value (mutable defaults). For example, the following function uses an empty list as the default value, and then changes its value each time the function is called:
> def saver (x = []): # Save a list object. X.append (1) # and every time it is called. Print x # change its value. > > saver ([2]) # does not use the default value [2,1] > saver () # use the default value [1] > saver () # increases every call! [1,1] > > saver () [1,1,1]
Some people see this as a feature of Python-because variable default parameters maintain their state each time a function is called, they provide similar functions like static local function variables in the ç language, but it feels strange when you encounter it for the first time, and there is an easier way to save state between different calls (such as classes) in Python.
To get rid of this behavior, use a slice or method to create a copy of the default parameter at the beginning of the function, or move the expression of the default value into the function; as long as these values are in the function each time the function is called, you get a new object every time:
Def saver (x=None):... If x is None: X = [] # No parameters are passed in? ... X.append (1) # change the new list. Print x... > > saver ([2]) # does not use the default value [2,1] > saver () # will not change this time [1] > saver () [1]
Other common programming pitfalls
Here are some of the other pitfalls that cannot be detailed here:
The order of statements in the top-level file is fastidious: because running or loading a file runs its statements from top to bottom, be sure to put your unnested function calls or class calls after the function or class definition.
Reloading does not affect the name of the slave load: reloading is best used with the import statement. If you use the statement, remember to rerun the slave after reloading, otherwise you will still use the old name.
The order of mixing in multiple inheritance is particular: this is because the search for the superclass is from left to right, in the head of the class definition, if there is a duplicate name in the multiple superclass, then the leftmost class name shall prevail.
Empty in the trial statement, except that the clause may catch more errors than you might expect. Empty in the attempt statement, except that the clause means to catch all errors, even the real program error, and the sys.exit () call, will be caught.
Thank you for your reading, these are the contents of "what are the common problems of Python programmers?" after the study of this article, I believe you have a deeper understanding of the common problems of Python programmers, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.