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

A few mistakes that 17 Python masters cant write

編輯:Python

source : Open source in China    

link :https://www.oschina.net/question/89964_62779

For the newcomer Pythonista In the process of learning to run the code is more or less will encounter some errors , It may seem like a lot of work at first . As the amount of code accumulates , Practice makes perfect when encountering some runtime errors, it can quickly locate the original problem . Here are some common 17 A mistake , When you write code that doesn't make many of these mistakes , Yours Python The skill is on the next level . In other words , When you become a qualified Python After developer , You may be “ I can't write it ” This kind of mistake .

1

Forget in if,for,def,elif,else,class Wait until the end of the statement  :

It can lead to “SyntaxError :invalid syntax” as follows :

if spam == 42
  print('Hello!')

2

Use = instead of ==

It can also lead to “SyntaxError: invalid syntax”

= It's an assignment operator and == It's a comparison operation . This error occurs in the following code :

if spam = 42:
  print('Hello!')

3

Wrong use of indent

Lead to “IndentationError:unexpected indent”、“IndentationError:unindent does not match any outer indetation level” as well as “IndentationError:expected an indented block”

Remember that indent increase is only used to : After the closing statement , And then you have to go back to the previous indent format . This error occurs in the following code :

print('Hello!')
  print('Howdy!')

perhaps :

if spam == 42:
  print('Hello!')
print('Howdy!')

4

stay for Forget to call... In the loop statement len()

Lead to “TypeError: 'list' object cannot be interpreted as an integer”

Usually you want to iterate through an index list perhaps string The elements of , This requires calling range() function . Remember to go back to len Value instead of returning this list .

This error occurs in the following code :

spam = ['cat', 'dog', 'mouse']
for i in range(spam):
  print(spam[i])

5

Try to modify string Value

Lead to “TypeError: 'str' object does not support item assignment”

string It's an immutable data type , This error occurs in the following code :

spam = 'I have a pet cat.'
spam[13] = 'r'
print(spam)

And the right thing to do is :

spam = 'I have a pet cat.'
spam = spam[:13] + 'r' + spam[14:]
print(spam)

6

Try to connect a non string value with a string

Lead to “TypeError: Can't convert 'int' object to str implicitly”

This error occurs in the following code :

numEggs = 12
print('I have ' + numEggs + ' eggs.')

And the right thing to do is :

numEggs = 12
print('I have ' + str(numEggs) + ' eggs.')

numEggs = 12
print('I have %s eggs.' % (numEggs))

7

Forget to quote at the beginning and end of the string

Lead to “SyntaxError: EOL while scanning string literal”

This error occurs in the following code :

print(Hello!')

print('Hello!)

myName = 'Al'
print('My name is ' + myName + . How are you?')

8

Misspelling variable or function name

Lead to “NameError: name 'fooba' is not defined”

This error occurs in the following code :

foobar = 'Al'
print('My name is ' + fooba)

spam = ruond(4.2)

spam = Round(4.2)

9

Misspelling method name

Lead to “AttributeError: 'str' object has no attribute 'lowerr'”

This error occurs in the following code :

spam = 'THIS IS IN LOWERCASE.'
spam = spam.lowerr()

10

Reference exceeds list Maximum index

Lead to “IndexError: list index out of range”

This error occurs in the following code :

spam = ['cat', 'dog', 'mouse']
print(spam[6])

11

Use a dictionary key that does not exist

Lead to “KeyError:‘spam’”

This error occurs in the following code :

spam = { 'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'}
print('The name of my pet zebra is ' + spam['zebra'])

12

Try to use Python Keyword as variable name

Lead to “SyntaxError:invalid syntax”

Python Key cannot be used as variable name , This error occurs in the following code :

class = 'algebra'

Python3 The key words are :and, as, assert, break, class, continue, def, del, elif, else, except, False, finally, for, from, global, if, import, in, is, lambda, None, nonlocal, not, or, pass, raise, return, True, try, while, with, yield

13

Use the value-added operator... In a new variable definition

Lead to “NameError: name 'foobar' is not defined”

Do not use... When declaring variables 0 Or an empty string as the initial value , In this way, we use a sentence of the autoincrement operator spam += 1 be equal to spam = spam + 1, It means spam You need to specify a valid initial value .

This error occurs in the following code :

spam = 0
spam += 42
eggs += 42

14

Use local variables in functions before defining local variables ( At this time, there is a global variable with the same name as the local variable )

Lead to “UnboundLocalError: local variable 'foobar' referenced before assignment”

It's very complicated to use local variables in a function and have a global variable with the same name at the same time , The rule of use is : If anything is defined in a function , If it's only used in functions, then it's local , On the contrary, it's a global variable .

This means that you can't use it as a global variable in a function before defining it .

This error occurs in the following code :

someVar = 42
def myFunction():
  print(someVar)
  someVar = 100
myFunction()

15

Try to use range() Create a list of integers

Lead to “TypeError: 'range' object does not support item assignment”

Sometimes you want to get an ordered list of integers , therefore range() Looks like a good way to generate this list . However , You need to remember range() The return is “range object”, Not the actual list value .

This error occurs in the following code :

spam = range(10)
spam[4] = -1

Write it correctly :

spam = list(range(10))
spam[4] = -1

( Be careful : stay Python 2 in spam = range(10) It can be done , Because in Python 2 in range() The return is list value , But in Python 3 The above mistakes will occur in )

16

non-existent ++ perhaps -- Self - increment and self - decrement operators .

Lead to “SyntaxError: invalid syntax”

If you are used to, for example C++ , Java , PHP Wait for other languages , Maybe you want to try to use ++ perhaps -- To increase or decrease by one variable . stay Python There is no such operator in .

This error occurs in the following code :

spam = 1
spam++

Write it correctly :

spam = 1
spam += 1

17

Forget to add... For the first parameter of the method self Parameters

Lead to “TypeError: myMethod() takes no arguments (1 given)”

This error occurs in the following code :

class Foo():
  def myMethod():
      print('Hello!')
a = Foo()
a.myMethod()

After reading it , Believe that if you are rolling every day Python Words , Few of the above mistakes have been made .

Finally, what mistakes do you often make ?

 Recommended reading :
introduction :  The most complete zero Foundation Python The problem of   |  Zero Basics 8 Months Python  |  Actual project  | learn Python That's the shortcut
dried food : A short comment on crawling Douban , The movie 《 The rest of us 》 | 38 year NBA Best player analysis  |    From people's expectation to public praise ! Tang Dynasty detective 3 disappointing   |  Laugh at the story of the new Yitian dragon slaying  |  Riddle answer King  | use Python Make a massive sketch of my little sister  | Mission impossible is so hot , I use machine learning to make a mini recommendation system movie
Interest : Pinball game   |  squared paper for practicing calligraphy   |  Beautiful flowers  |  Two hundred lines Python《 Cool run every day 》 game !
AI:  A robot that can write poetry  |  Color the picture  |  Forecast revenue  |  Mission impossible is so hot , I use machine learning to make a mini recommendation system movie
Gadget : Pdf turn Word, Easily handle forms and watermarks ! |  One touch html Save the page as pdf!|   bye PDF Withdrawal charges ! |  use 90 Lines of code create the strongest PDF converter ,word、PPT、excel、markdown、html One click conversion  |  Make a nail low-cost ticket reminder ! |60 Line of code to do a voice wallpaper switcher, look at my little sister every day !|

Annual hot money copy

  • 1). Oh my god !Pdf turn Word use Python Easy to handle !

  • 2). learn Python It's delicious ! I use 100 Line of code to make a website , Help people PS Travel pictures , Earn a chicken leg to eat

  • 3). Premiere billions , Hot all over the net , I analyzed 《 My sister 》, Discovered the secrets  

  • 4).80 Line code ! use Python Make a dorai A Dream separation  

  • 5). What you have to master 20 individual python Code , short , Useful  

  • 6).30 individual Python Strange sexual skills Collection  

  • 7). I summed up 80 page 《 Rookie Science Python Select dry goods .pdf》, Is dry  

  • 8). bye Python! I have to learn Go 了 !2500 Word depth analysis !

  • 9). Found a licking dog welfare ! This Python Reptile artifact is great , Automatically download sister pictures

Click to read the original , see B My station 20 A video !


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