程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

6 classic novice mistakes in Python, how many have you encountered?

編輯:Python

作者 | 快快

來源 | 快學Python

SyntaxError的來源

當您運行 Python 代碼時,The interpreter will be the first to parse it to convert it to Python 字節碼,然後執行.The interpreter will in the first phase of the program execution(Also known as the parsing stage)中發現 Python Any invalid syntax of.If the interpreter cannot parse your success Python 代碼,Somewhere in the code means you use an invalid syntax.The interpreter will try to show you that the locations of the.

當您第一次學習 Python 時,遇到 SyntaxError 可能會令人沮喪.Python Will try to help you determine the location of the code is invalid syntax,But it provides back might be a little confusing.有時,It refers to the code is very good.

注意:If your code is grammatically correct,You might cause other than SyntaxError 的異常.

今天,咱們就來看看Python中6A common grammar problem.

When you first met SyntaxError 時,To understand why there will be a problem,以及如何修復 Python Invalid syntax of the code,會很有幫助.

在下面的部分中,You will see may cause SyntaxError Some of the more common causes of,以及如何修復它們.

The abuse of the assignment operator (=)

在 Python There are several kinds of situation,You can't for object assignment.Some examples are assigned to the text and function call.在下面的代碼塊中,You can see some attempt to do this sample,以及由此產生的SyntaxError 回溯:

>>> len('hello') = 5
  File "<stdin>", line 1
SyntaxError: can't assign to function call
>>> 'foo' = 1
  File "<stdin>", line 1
SyntaxError: can't assign to literal
>>> 1 = 'foo'
  File "<stdin>", line 1
SyntaxError: can't assign to literal

The first example trying to value 5 分配給 len() 調用.SyntaxError The message is very useful in this case.It tell you can't give the function call assignment.

The second and the third example trying to allocate a string and an integer.The same rules apply to other literal values.Back in the news once again showed that there was a problem when you try to writing assignment.

Your intention is probably not for text or a function call assigned value.例如,If you accidentally left out the extra equal sign (=),就會發生這種情況,It converts the assignment to compare.如下所示,Comparison is valid:

>>> len('hello') == 5
True

拼寫錯誤、Omission or misuse Python 關鍵字

Python The keyword is a set of protected word,在 Python 中具有特殊含義.These words cannot be used as identifiers in your code、變量或函數名稱.They are part of the language,只能在 Python Allow the context of use.

Error using keywords common way has the following three:

  • ① 關鍵字拼寫錯誤;

  • ② 缺少關鍵字;

  • ③ Abuse of keyword;

如果您在 Python Keywords in spelt wrong code,則會收到 SyntaxError.例如,如果關鍵字 for 拼寫錯誤,會發生以下情況:

>>> fro i in range(10):
  File "<stdin>", line 1
    fro i in range(10):
        ^
SyntaxError: invalid syntax

該消息顯示 SyntaxError: invalid syntax ,But this is not helpful.Go back to Python Can detect the error first position.To fix these errors,請確保所有 Python Key words spelled correctly.

Keyword is another common problem when you completely forget write:

>>> for i range(10):
  File "<stdin>", line 1
    for i range(10):
              ^
SyntaxError: invalid syntax

再一次,The exception message is not so useful,But back really will try to indicate the right direction for you.If moving from the caret back,則可以看到 for Cycle in the syntax lack in 關鍵字.

You can also the misuse of the protected Python 關鍵字.請記住,Keyword is only allowed in certain circumstances to use.If you mistakenly use them,那麼您的 Python The code contains invalid syntax.A common example is used outside the loop continue 或 break.It is easy to occur throughout the development process,And when you are implementing things happened to move logic outside of the loop when:

>>> names = ['pam', 'jim', 'michael']
>>> if 'jim' in names:
...     print('jim found')
...     break
...
  File "<stdin>", line 3
SyntaxError: 'break' outside loop
>>> if 'jim' in names:
...     print('jim found')
...     continue
...
  File "<stdin>", line 3
SyntaxError: 'continue' not properly in loop

在這裡,Python Is a good way to tell you what exactly is the problem.消息“'break' 外循環”和“'continue' Not right circulation”Can help you determine what to do.If the code in a file,那麼 Python There will be the caret to the misuse of the keyword.

另一個示例是,如果您嘗試將 Python Keywords assigned to a variable or use keywords to define the function:

>>> pass = True
  File "<stdin>", line 1
    pass = True
         ^
SyntaxError: invalid syntax
>>> def pass():
  File "<stdin>", line 1
    def pass():
           ^
SyntaxError: invalid syntax

缺少括號、Square brackets and quotes

通常,Python The cause of the code is invalid syntax is missing or does not match the right parenthesis、方括號或引號.In these long lines nested parentheses or longer more blocks may be difficult to find.借助 Python 的回溯,You can find don't match or missing quotes:

>> message = 'don't'
  File "<stdin>", line 1
    message = 'don't'
                   ^
SyntaxError: invalid syntax

在這裡,Back to invalid code,One after the end of single quotes have t'.要解決此問題,You can be one of the following two changes:

  • ① Use the backslash escapes single quotes ('don't');

  • ② The entire string enclosed in double quotation marks("don't");

Another common mistake is to forget to turn off the string.For the double quotes and single string,Situation and the back is the same:

>>> message = "This is an unclosed string
  File "<stdin>", line 1
    message = "This is an unclosed string
                                        ^
SyntaxError: EOL while scanning string literal

The wrong grammar dictionary

You saw before,If you put a comma in the dictionary elements,您可能會得到 SyntaxError.Python Dictionary of another form of invalid syntax is the use of the equal sign (=) 來分隔鍵和值,Instead of using a colon:

>>> ages = {'pam'=24}
  File "<stdin>", line 1
    ages = {'pam'=24}
                 ^
SyntaxError: invalid syntax

同樣,This error message is not very helpful.然而,Duplicate rows and the caret is helpful!They pointed to the problem character.

如果您將 Python Grammar and other programming language syntax confused,Such problems are common.If you will define the behavior of the dictionary with dict() Invoke confusion,You can also see that.要解決此問題,You can use a colon to replace the equals sign.You can also switch to use dict():

>>> ages = dict(pam=24)
>>> ages
{'pam': 24}

使用錯誤的縮進

Other programming languages using curly braces said code block,而 Python 使用空格.這意味著 Python Expectations in the code blank behavior can be predicted.If a line in the code block contains the error on the number of Spaces,它將引發 IndentationError:

def foo():
    for i in range(10):
        print(i)
  print('done')
foo()

This may be difficult to see,但第 5 Line indentation only 2 個空格.應該和forLooping statements consistent,多4個空格.值得慶幸的是,Python Can be easily found that,And will tell you the problem soon.

不過,There are some ambiguity.print('done') 行是在 for After the loop or in for 循環塊內?When you run the above code,You will see the following error:

File "indentation.py", line 5
    print('done')
                ^
IndentationError: unindent does not match any outer indentation level

Although back looks like SyntaxError 回溯,但它實際上是一個 IndentationError.Error message is also very helpful.It tells you the indentation level does not match with any other indentation level.換句話說,print('done') Be indented 2 個空格,但是 Python Can't find any other fit the indentation level of the line.You can be sure to indent the code with the expected level alignment to quickly solve this problem.

定義和調用函數

When defined or call a function,您可能會在 Python Encountered in the invalid syntax.例如,If use a semicolon at the end of the function definition instead of a colon,則會看到 SyntaxError:

>>> def fun();
  File "<stdin>", line 1
    def fun();
             ^
SyntaxError: invalid syntax

The back is very useful,The caret directly pointing to the problem character.You can replace the semicolon is a colon to clear Python In this kind of invalid syntax.

此外,Function definitions and key parameters of the function call needs to be in the correct order.關鍵字參數總是在位置參數之後.Do not use this order will lead to SyntaxError:

>>> def fun(a, b):
...     print(a, b)
...
>>> fun(a=1, 2)
  File "<stdin>", line 1
SyntaxError: positional argument follows keyword argument

往期回顧

花 39 Dollars pleaseAIThe painter got aLogo

Deepfake 技術換臉真假難辨!

pandas常用的8個option設置!

7歲男童因下棋太快,被機器人夾斷手指?

分享
點收藏
點點贊
點在看

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved