Home  >  Article  >  Backend Development  >  Common mistakes that novices make when they first start learning Python

Common mistakes that novices make when they first start learning Python

伊谢尔伦
伊谢尔伦Original
2017-01-16 16:23:151364browse

When novices first start learning the Python language, they will make mistakes of one kind or another. We have made some summaries here, hoping to give some attention to friends who have just started learning Python.

Grammar Error

Grammar error is probably the most common mistake you make when you are still learning Python

>>> while True print "hi~"
  File "<stdin>", line 1    
  while True print "hi~"
               ^
SyntaxError: invalid syntax

There is an arrow Point to the place where the error was first discovered, here it points to print, because there is a missing colon after Tue

. Forgot to add at the end of if, elif, else, for, while, class, def statement: (resulting in "SyntaxError: invalid syntax ") This error will occur in code similar to the following:

if spam == 42 print(&#39;Hello!&#39;)

Use = instead of == (resulting in "SyntaxError: invalid syntax") = is the assignment operator and == is the equal comparison operation. This error occurs in the following code:

if spam = 42: print(&#39;Hello!&#39;)

Incorrect use of indentation. (Resulting in "IndentationError: unexpected indent", "IndentationError: unindent does not match any outer indetation level" and "IndentationError: expected an indented block") Remember that indentation increases only after statements that end with: and must be restored afterwards to the previous indentation format. This error occurs in the following code:

print(&#39;Hello!&#39;) 
   print(&#39;Howdy!&#39;)

Or:

if spam == 42: 
print(&#39;Hello!&#39;) 
print(&#39;Howdy!&#39;)

Or:

 if spam == 42: 
print(&#39;Hello!&#39;)

Forgot to call len() in the for loop statement (resulting in "TypeError: 'list ' object cannot be interpreted as an integer") Usually you want to iterate over the elements of a list or string by index, which requires calling the range() function. Remember to return the len value instead of the list. The error occurs in the following code:

spam = [&#39;cat&#39;, &#39;dog&#39;, &#39;mouse&#39;] for i in range(spam): 
     print(spam[i])

Try to modify the value of string (resulting in "TypeError: 'str' object does not support item assignment") string is an unavailable The error occurs in the following code:

spam = &#39;I have a pet cat.&#39; 
spam[13] = &#39;r&#39; print(spam)

And you actually want to do this:

spam = &#39;I have a pet cat.&#39; 
spam = spam[:13] + &#39;r&#39; + spam[14:] print(spam)

Attempt to connect to a non- String value vs. string (resulting in "TypeError: Can't convert 'int' object to str implicitly") The error occurs in code like this:

numEggs = 12 print(&#39;I have &#39; + numEggs + &#39; eggs.&#39;)

whereas you actually want to do this:

numEggs = 12 print(&#39;I have &#39; + str(numEggs) + &#39; eggs.&#39;)

Or:

 numEggs = 12 print(&#39;I have %s eggs.&#39; % (numEggs))

Forgot to add quotation marks at the beginning and end of the string (resulting in "SyntaxError: EOL while scanning string literal") This error occurs in the following code:

print(Hello!&#39;) 或者: print(&#39;Hello!)

Or:

myName = &#39;Al&#39; print(&#39;My name is &#39; + myName + . How are you?&#39;)

The variable or function name is spelled incorrectly (resulting in "NameError: name 'fooba' is not defined"). This error occurs in the following code:

foobar = &#39;Al&#39; print(&#39;My name is &#39; + fooba)

Or:

spam = ruond(4.2)

Or:

spam = Round(4.2)

The method name is spelled incorrectly (resulting in "AttributeError: 'str' object has no attribute 'lowerr'") This error Occurs in the following code:

spam = &#39;THIS IS IN LOWERCASE.&#39; spam = spam.lowerr()

Exception

Even if the statement and expression syntax are correct, the error occurs during execution. Errors may occur, which are called exceptions. Exceptions are not always fatal; you will learn how to deal with them in a moment. Many exception procedures do not handle it, but return an error message, for example:

>>> 10 * (1/0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>ZeroDivisionError: integer division or modulo by zero
>>> 4 + git*3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>NameError: name &#39;git&#39; is not defined
>>> &#39;2&#39; + 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>TypeError: cannot concatenate &#39;str&#39; and &#39;int&#39; objects
>>>

错误消息的最后一行就是异常消息,冒号前是异常的类型。上面的 ZeroDivisionError, NameError, TypeError, 都是系统内置的异常。

处理异常

可以自己编写程序来处理异常,比如下面这个例子,它会返回异常,直到用户输入有效数据为止。

>>> while True:
...     try:
...         x = int(raw_input("Please enter a number: "))
...         break...     except ValueError:
...         print "Oops! That was no valid number. Try again..."... 
Please enter a number: x
Oops! That was no valid number. Try again...
Please enter a number: 32x
Oops! That was no valid number. Try again...
Please enter a number: 038

使用 try 和 except ExceptionName 来处理异常

如果没有异常产生,except 段会被跳过

如果某处有异常产生,后面的语句会被跳过,如果产生的异常类型和except后的类型一致,except后的语句会被执行

如果发生异常,但和except后的类型不一致,异常会传递到try语句外面,如果没有相应处理,那么就会打印出像上 一个例子那样的信息。

一个try语句可能有多个except与之对应,分别处理不同类型的异常,最多只有一种处理会被执行。一个except可以包含多 个类型名,比如:

... except (RuntimeError, TypeError, NameError):
...     pass

注意上面的三种异常类型,必须用括号把它们括起来,因为在现代python中, except ValueError, e 的意思是 except ValueError as e:(后面会讲这是什么意思)

最后一个except一般不指定名字,用于处理其余情况

import systry:
    f = open(&#39;myfile.txt&#39;)
    s = f.readline()
    i = int(s.strip())
except IOError as e:    
       print "I/O error({0}): {1}".format(e.errno, e.strerror)
except ValueError:    
       print "Could not convert data to an integer."
except:    
       print "Unexpected error:", sys.exc_info()[0]    
       raise

try..except 语句还可以选择使用else,例如

for arg in sys.argv[1:]:    
     try:
        f = open(arg, &#39;r&#39;)    
   except IOError:        
           print &#39;cannot open&#39;, arg    
   else:        
           print arg, &#39;has&#39;, len(f.readlines()), &#39;lines&#39;
        f.close()

需要注意,一旦使用else,每个except后都要有else,这种方式用于需要指定某一异常不出现时执行什么操作。

except子句可以在异常名后指定参数,这些参数被存储在异常实例产生时的 instance.arg

>>> try:
...     raise Exception(&#39;spam&#39;, &#39;eggs&#39;)
... except Exception as inst:
...     print type(inst)
...     print inst.args
...     print inst
...     x, y = inst.args
...     print &#39;x =&#39;, x
...     print &#39;y =&#39;, y
... 
<type &#39;exceptions.Exception&#39;>
(&#39;spam&#39;, &#39;eggs&#39;)
(&#39;spam&#39;, &#39;eggs&#39;)
x = spam
y = eggs

异常处理不仅仅处理直接在try中出现的异常,还可以处理在try中调用函数的异常

>>> def mdiv():
...     x = 1/0
... 
>>> try:
...     mdiv()
... except ZeroDivisionError as detail:
...      print &#39;Handling run-time error:&#39;, detail
... 
Handling run-time error: integer division or modulo by zero

用户自定义异常

程序可以通过创建一个异常类来命令一个新的异常,这个异常类需要通过直接或者间接的方式由 Exception 类派生。

>>> class MyError(Exception):
...     def __init__(self, value):
...          self.value = value
...     def __str__(self):
...          return repr(self.value)
... 
>>> try:
...     raise MyError(1+5)
... except MyError as e:
...     print &#39;My exception occurred, value:&#39;, e.value
... 
My exception occurred, value: 6
>>> raise MyError(&#39;oops!&#39;)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
__main__.MyError: &#39;oops!&#39;

在上面的例子中,__ init __ (), 覆盖了默认的 init 函数,新的行为创建了 value 属性, 替换了原有的 创建args属性的行为。

其它类可以做的事情,通过定义Exception类都可以完成。但是Exception类总是被设计地非常简单, 它们提供一些属性,这样错误处理时就可能方便地提取出这些属性。 当设计一个模块处理多种异常时,常常先定义一个基本的类,其它类在此基础上处理一些特殊情况。

class Error(Exception):    
    """Base class for exceptions in this module."""
    pass
    
class InputError(Error):    
    """Exception raised for errors in the input.    
    Attributes:        
       expr -- input expression in which the error occurred        
       msg  -- explanation of the error    """

    def __init__(self, expr, msg):        
       self.expr = expr        
       self.msg = msg
class TransitionError(Error):    
    """Raised when an operation attempts a state transition that&#39;s not    
       allowed.    
       
       Attributes:        
          prev -- state at beginning of transition        
          next -- attempted new state        
          msg  -- explanation of why the specific transition is not allowed    
       """

    def __init__(self, prev, next, msg):        
        self.prev = prev        
        self.next = next
        self.msg = msg

在定义局部变量前在函数中使用局部变量

(此时有与局部变量同名的全局变量存在)(导致“UnboundLocalError: local variable 'foobar' referenced before assignment”) 在函数中使用局部变来那个而同时又存在同名全局变量时是很复杂的,使用规则是:如果在函数中定义了任何东西,如果它只是在函数中使用那它就是局部的,反之就是全局变量。 这意味着你不能在定义它之前把它当全局变量在函数中使用。 该错误发生在如下代码中: 

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

尝试使用 range()创建整数列表

(导致“TypeError: 'range' object does not support item assignment”) 有时你想要得到一个有序的整数列表,所以 range() 看上去是生成此列表的不错方式。然而,你需要记住 range() 返回的是 “range object”,而不是实际的 list 值。 该错误发生在如下代码中: 

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

也许这才是你想做: 

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

(注意:在 Python 2 中 spam = range(10) 是能行的,因为在 Python 2 中 range() 返回的是list值,但是在 Python 3 中就会产生以上错误)

错在 ++ 或者 -- 自增自减操作符。

(导致“SyntaxError: invalid syntax”) 如果你习惯于例如 C++ , Java , PHP 等其他的语言,也许你会想要尝试使用 ++ 或者 -- 自增自减一个变量。在Python中是没有这样的操作符的。 该错误发生在如下代码中: 

spam = 1
spam++

也许这才是你想做的: 

spam = 1 
spam += 1

忘记为方法的第一个参数添加self参数

(导致“TypeError: myMethod() takes no arguments (1 given)”) 该错误发生在如下代码中: 

class Foo(): def myMethod(): 
       print(&#39;Hello!&#39;) a = Foo() a.myMethod()


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn