17 Error Analysis _python The Python novice often encounters

Source: Internet
Author: User
Tags in python

1 forgetting to add at the end of If, elif, else, for, while, class, Def declaration: (Leading to "syntaxerror:invalid syntax")

This error will occur in a code similar to the following:

If spam==
  print (' hello! ')

2 Use = instead of = = (cause "syntaxerror:invalid syntax")

= is the assignment operator and = = is equal to the comparison operation. This error occurs in the following code:

If spam=:
  print (' hello! ')

3 The wrong amount of indentation used. (causes "indentationerror:unexpected indent", "Indentationerror:unindent does not match any outer indetation level", and " Indentationerror:expected an indented block ")

Remember that indentation is used only after the end of a statement, and then you must revert to the previous indent format. This error occurs in the following code:

Print (' hello! ')
  Print (' howdy! ')
 
Or:
 
if spam==:
  print (' hello! ')
 Print (' howdy! ')
 
Or:
 
if spam==:
print (' hello! ')

4 forgot to call Len () in the FOR Loop statement (causing "TypeError: ' List ' object cannot be interpreted as")

Usually you want to iterate over a list or string of elements by index, which requires the range () function to be called. Remember to return the Len value instead of returning to the list.

This error occurs in the following code:

spam= [' Cat ', ' dog ', ' mouse '] for
iin range (spam):
  print (spam[i))

5 attempts to modify the value of string (causing "TypeError: ' str ' object does not support item assignment")
A string is an immutable data type that occurs in the following code:

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

And you actually want to do this:

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

6 Attempt to connect a non string value with a string (causing "Typeerror:can ' t convert ' int ' object to str implicitly")

This error occurs in the following code:

numeggs=
print (' I have ' + numeggs+ ' eggs. ')
 

And you actually want to do this:

numeggs=
print (' I have ' + str (numeggs) + ' eggs. ')
 
Or:
 
numeggs=
print (' I have%s eggs. '% (Numeggs))

7 in the end of the string forget the quotation marks (resulting in "syntaxerror:eol while scanning string literal")
This error occurs in the following code:

Print (hello! ')
 
Or:
 
print (' hello!)
 
Or:
 
myname= ' Al '
print (' My name is ' + myname+.) How to Are you? ')

8 A variable or function name spelling error (causing "Nameerror:name ' fooba ' is not defined")

This error occurs in the following code:

Foobar= ' Al '
print (' My name is ' + Fooba)
 
or:
 
spam= ruond (4.2)
 
or:
 
spam= Round (4.2)

9 Method Name spelling error (leading to "Attributeerror: ' str ' object has no attribute ' Lowerr ')

This error occurs in the following code:

Spam= ' is in lowercase. '
Spam= Spam.lowerr ()

10 reference exceeds list maximum index (causes "Indexerror:list index out of range")

This error occurs in the following code:

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

11 using nonexistent Dictionary key values (resulting in "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 attempt to use the Python keyword as the variable name (resulting in "syntaxerror:invalid syntax")

Python key cannot be used as a variable name, which occurs in the following code:

class = ' Algebra '
Python3 keywords are: And, as, assert, break, class, continue, Def, Del, elif, else, except, False, finally, for, from, Global, if, Import, in, are, lambda, None, nonlocal, not, or, pass, raise, return, True, try, while, with, yield

13 using the value added operator in a defined new variable (resulting in "nameerror:name ' foobar ' not defined")

Do not use 0 or an empty string as the initial value when declaring a variable, so using the spam = 1 of the self-added operator equals spam = spam + 1, which means that spam needs to specify a valid initial value.

This error occurs in the following code:

spam= 0
spam+=
eggs+= 42

14 use local variables in functions before defining local variables (there are global variables with the same name as local variables) (causes "unboundlocalerror:local variable ' foobar ' referenced before assignment") )

It is very complicated to use a local transformation in a function while there is a global variable with the same name, and the rule is: if anything is defined in a function, it is local if it is used in a function, otherwise it is a global variable.

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

This error occurs in the following code:

Somevar=
def myfunction ():
  print (somevar)
  somevar=
myfunction ()

15 try using range () to create an integer list (causing "TypeError: ' Range ' object does not support item assignment")

Sometimes you want to get an ordered list of integers, so range () looks like a good way to build this list. However, you need to remember that range () returns "Range object" instead of the actual list value.

This error occurs in the following code:

Spam= Range (spam[4]=)
-1

Maybe that's what you want to do:

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

(Note: Spam = range (10) can be done in Python 2 because the range () in Python 2 returns the list value, but the above error occurs in Python 3)

16 good at + + or-self-subtraction operator. (leading to "syntaxerror:invalid syntax")

If you're used to other languages such as C + +, Java, PHP, and so on, you might want to try using + + or--self-subtract a variable. There is no such operator in Python.

This error occurs in the following code:

spam= 1
spam++

Maybe that's what you want to do:

spam= 1
spam+= 1

17 forgetting to add the self parameter to the first parameter of the method (causing "typeerror:mymethod () takes no arguments (1 given)")

This error occurs in the following code:

Class Foo ():
  def myMethod ():
    print (' hello! ')
A= Foo ()
A.mymethod ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.