directory

Python2 upgrade Python3 error

1. Print becomes print()

2. Raw_Input becomes input

3. Integer and division problems

4. Major upgrade of exception handling

NameError: name ‘xrange’ is not definedw

6. Resolve the error message “Name ‘reload’ is not defined and AttributeError: module ‘sys’ has no att”

Error “Python Unicode is not defined

8. Resolve AttributeError: ‘diet’ object has no attribute ‘has_key’

9. Resolve the error message lmportError: No module named urllib2

Two, the program common error

1, solve “IndentationError: excepted the an indented bloc” error message

2, Resolve the error “No module named XX”

TypeError: ‘tuple’ object cannot be interpreted as an integer ‘TypeError: ‘tuple’ object cannot be interpreted as an integer

LOError: File not open for writing

5. Resolve the error “SyntaxError:invalid syntax”

TypeError: ‘STR’ object does not support item Assignment ‘TypeError:’ STR ‘object does not support item Assignment

TypeError: Can’t convert ‘int’ object to STR ERROR MESSAGE DECLARED

Wrong use of class variables

9. Misunderstand Python’s scope


 

Hello! Hello ah, I am gray little ape, a super will write bug program ape!

Summed up two days ago an article about Python introductory “【 tech-oriented testimonials 】 is the Python’s yi-ology” introductory tutorial, thumb up and support by a lot of friend, interested friends can go to have a look at, but also there are a lot of people leave a message or direct messages, I said, first contact with the basic knowledge is not strong, In the programming time will still encounter a lot of problems, so today here and you summary and record the common Python development error troubleshooting and solutions, I hope to help you learn Python programming, you can first collect attention! After the encounter slowly solve!

As you write and debug Python programs, you will encounter errors of one sort or another, most of which are caused by carelessness or syntax errors. So I summarized the common error types and detailed explanations and troubleshooting methods.

Python2 upgrade Python3 error

In current Python development, Python has two large version branches, 2.7 and Python3.x. Version 2.7 is older and may be implemented using Python2.7 in web tutorials, teaching documents, and published books,

However, most Python development today already uses 3.x, so some syntax errors may occur when we run Python 2.7 code directly in a Python 3.x environment. So let’s sum it up.

 

1. Print becomes print()

In the Python2 version, print is used as a statement, in the Python3 version print. It appears as a function. The following two pieces of code show the differences between the two versions.

The code for the Python 2.x version is as follows:

>>>i = 1
>>>print ' Python * * is'.'number', i

Pythonis number 1
Copy the code

The code for Python 3.x is as follows:

>>>i = 1
>>>print (' Python * * is ', * number', i) Pythonis number 1Copy the code

That is, in Python 3, all print content must be enclosed in parentheses.

 

2. Raw_Input becomes input

In Python 2, the input function is implemented through raw_input. In Python 3, this is done through input. Here’s the difference between two lines of code:

name = input('What is your name? \n') #python3 code

name = raw_input ("What is your name? \n") # python2 code
Copy the code

 

3. Integer and division problems

When you first learn to write Python programs, especially Python2 programs running in Python 3, you are likely to encounter “TypeError: ‘float* object cannot be interpreted as an integer ‘error For example, the following code runs successfully in Python 2:

batch = 200
for x in range(len(order_nos) / batch + 1) :# do something
Copy the code

Where order_nos is a list of orders, and when run in Python 3, TypeError:’float’ object cannot be interpreted as an INTEGER Float cannot be interpreted as an int. This is because in Python 3, int and long are unified as int, and int represents any integer of precision. In previous versions of Python 2, an integer floor was returned if the argument was int or long, and a proper approximation of the result was returned if the argument was float or complex. OverflowError is no longer raised when an int exceeds the local integer size. The long type is dead in Python 3, and the suffix L is deprecated.

Here’s a comparison of the two versions of division:

  • The result in version 1/2 #Python 2 is 0
  • In version 1/2 #Python 3 the result is 0.5, which makes sense

In contrast, division has changed, and the “/” in Python 3 always returns a floating point number, always denoting downward division. So when “TypeError: ‘float’ object cannot be interpreted as an INTEGER” occurs with respect to division “/”, simply change/to // “.

 

4. Major upgrade of exception handling

In Python 2 programs, exceptions are caught in the following format:

except Exception, identifier

In Python 3 programs, exceptions are caught in the following format:

except Exception as identifier

For example, here is the code to demonstrate Python 2 catching exceptions:

except ValueError, e: Python 2 handles a single exception
except (ValueError, TypeError), e: # Python 2 handles multiple exceptions
Copy the code

Here is a Python 3 example of catching exceptions:

except ValueError as e: Python3 handles a single exception
except (ValueError, TypeError) as e: # Python3 handles multiple exceptions
Copy the code

In Python 2 programs, exceptions are thrown in the following format:

raise Exception, args
Copy the code

In Python 3 programs, exceptions are thrown in the following format:

raise Exception(args)
Copy the code

For example, the following two lines of code demonstrate how both versions throw exceptions:

raise ValueError, e # Python 2.x method

raise ValueError(e) # Python 3.x method
Copy the code

 

NameError: name ‘xrange’ is not definedw

This error is also a version problem. Python2 uses the xrange() function, which was replaced by the range() function in Python3. So in Python 3 programs, you can solve this problem by simply changing xrange to range.

 

6. Resolve the error message “Name ‘reload’ is not defined and AttributeError: module ‘sys’ has no att”

Reload cannot be used directly in Python 3.6 programs. To be compatible with the Reload feature in Python 2, you need to add the following code:

import importlib
importlib.reload(sys)
Copy the code

 

Error “Python Unicode is not defined

It is common in Python 3 programs to encounter the error “Python Unicode is not defined”. This is because the Unicode type is no longer available in Python 3, and has been replaced by the new STR type. The original STR type in Python 2 is replaced by bytes in Python 3.

 

8. Resolve AttributeError: ‘diet’ object has no attribute ‘has_key’

For example, the following error reporting procedure:

>>> d={}
>>> d.has_key('name')

Traceback (most recent call last):

    File "<pyshell#l>", line 1.in <module>

        d.has_key(1name') AttributeError: * diet * obj ect has no attribute ' has_key * 
Copy the code

This is because has_key has been discarded in Python 3. The change method is to replace has_key with in:

>>> d={}
>>> 'name' in d

True
Copy the code

 

 

9. Resolve the error message lmportError: No module named urllib2

Urllib2 has been replaced by urllib.request in Python 3, so the solution is to change urllib2 to urllib.request.

 

Two, the program common error

1, solve “IndentationError: excepted the an indented bloc” error message

This is a lot of beginners often make a mistake, this mistake will make people want to cry! This error is not a syntactic error, but rather a problem of user code writing. Because Python is a very sensitive language to indentation, I think this is also a weakness of Python, the entire structure of the loop may rely on the form of indentation.

One of the most common mistakes you make early on is to mix Tab and Space keys to indent code, which is very error-prone and hard to spot with the naked eye. Many IDE editors have the option of showing whitespace, but even then, it’s hard to figure out what the problem is. Therefore, it is recommended that you only use the Tab key to indent code, or only use the Space key to indent code.

For example, if you write an if statement followed by a colon, many code editors will automatically indent the first line if you wrap it. Some code editors may not have this feature, so you’ll need to indent it manually, which is a good habit to get into. Please do not hit the space bar several times in a row, it is recommended to directly press the Tab key.

 

2, Resolve the error “No module named XX”

Without a doubt, this is probably the most common mistake you’ll ever encounter in learning and development. As the level of development and complexity of the program increases, more and more modules and third-party libraries will be used in the program. You will often get a “no module named XX” error because the library “XX” is not installed. When encountering this error, install library XX with the following command:

pip install ww
Copy the code

 

TypeError: ‘tuple’ object cannot be interpreted as an integer ‘TypeError: ‘tuple’ object cannot be interpreted as an integer

Take a look at the following code:

t=('a'.'b'.'c')
for i in range(t):
print (t [i])
Copy the code

TypeError: ‘tuple* object cannot be interpreted as an integer

This is a typical type error. In the code above, the rangeO function expects an integer as an argument, but instead receives a tuple as an argument. The solution is to change the input tuple t to len(t). For example, change range(t) in the code above to range(len(t)).

 

LOError: File not open for writing

This is a typical file manipulation permission problem, such as the following demo code will expose this error:

>>> f=open ("hello. py")
>>> f.write ("test")

Traceback (most recent call last):
File "<stdin>n" line 1.in <module> 
lOError:File not open for writing
Copy the code

Open (“hello.py”) does not add the read/write mode parameter to the input parameter of open(“hello.py”). This means that the file is opened in read-only mode by default. Write mode permission w+ :

f = open("hello. py"."w+")
f. write("test")
Copy the code

 

5. Resolve the error “SyntaxError:invalid syntax”

This error is usually caused by forgetting to add colons to the end of statements such as if, elif, else, for, while, class, and def, for example:

if spam == 42 print("Hello!")
Copy the code

The solution is to add the colon “:” at the end.

The same error can occur when “=” is incorrectly used instead of “==”. In Python programs, “=” is the assignment operator, and “==” is the equal comparison operation.

 

TypeError: ‘STR’ object does not support item Assignment ‘TypeError:’ STR ‘object does not support item Assignment

This error is usually caused by trying to modify the value of string, which is an immutable data type. For example, this error occurs in code like this:

spam = 'I have a pet cat'
spam[13] = 'r'
print(spam)
Copy the code

The modification method is:

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

 

TypeError: Can’t convert ‘int’ object to STR ERROR MESSAGE DECLARED

This error is usually caused by trying to concatenate a non-string value with a string, for example in code like this:

numEggs = 12
print('I have ' + numEggs + "eggs.")
Copy the code

The solution is to change it to:

numEggs = 12
print("i have "+ str(numEggs) + " eggs.")
Copy the code

You can also change it to:

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

 

Wrong use of class variables

Consider the following demonstration:

class A (object) :
    x = 1

class B (A) :
    pass

class C (A) :
    pass

print (A.x, B.x, C.x)
# 1 1 1

B.x = 2
print (A.x, B.x, C.x)
# 1 2 1

A.x = 3
print (A.x, B.x, C.x)
# 2, 3, 3
Copy the code

We only changed A.x, why was C.x also changed? In Python programs, class variables are treated internally as dictionaries, following the oft-referenced method resolution order (MRO). So in the above code, since the x attribute in class C is not found, it looks up to its base class (although ****Python supports multiple inheritance, there is only A in the above example). In other words, class C has no x attribute of its own, which is independent of A. Therefore, C.x is actually a reference to A.x.

 

9. Misunderstand Python’s scope

Python is LEGB based for action parsing, so there are a few things to be aware of in development, starting with the following code:

x = 10
def foo() :
    x += 1
    print(x)
foo ()

Traceback (most recent call last):
  File "D:/ Python/QRcode_Make/test.py", line 5.in <module>
    foo ()
  File "D:/ Python/QRcode_Make/test.py", line 3.in foo
    x += 1
UnboundLocalError: local variable 'x' referenced before assignment
Copy the code

The code above fails because the local variable x has no initial value and the external variable X cannot be introduced internally.

Look at the following list operations:

lst = [1.2.3]   # assign the list LST
lst. append (4)     # append () - * element 4
print(lst)
# [1, 2, 3, 4]

lst += [5]  # Merge two lists
print(lst)
# [1, 2, 3, 4, 5]

def fool() :
    lst.append(6)   The function looks for the external: 1st list

fool ()
print(lst)
# [1, 2, 3, 4, 5, 6]


def foo2() :
    lst += [6] # when merging lists, external lists will not be looked up, which is somewhat surprising

foo2 ()

Traceback (most recent call last):
  File "D:/ Python/QRcode_Make/test.py", line 26.in <module>
    foo2 ()
  File "D:/ Python/QRcode_Make/test.py", line 24.in foo2
    lst += [6] # when merging lists, external lists will not be looked up, which is somewhat surprising
UnboundLocalError: local variable 'lst' referenced before assignment
Copy the code

Fool can merge while Fool 2 is not. Fool can merge while Fool 2 is not.

This is because Fool does not perform an ASSIGNMENT to LST, while Fool 2 does. Remember, LST += [5] is short for LST = LST + [5], and we’re trying to assign to LST (Python treats it as a local variable). Also, the assignment we’re doing to the LST is based on the LST itself (which is again treated as a local variable by Python), but it’s not defined yet, so it’s wrong! It is important to distinguish between local variables and external variables.

If you have any questions or don’t understand, you are welcome to comment and leave a message!

Continue to update you with more technical sharing about Python!

Those who find it useful remember Thumb up attention Hey!

Grey ape accompany you to progress together!

At the same time, I recommend an official CSDN learning path of Python full stack Knowledge graph, which covers six Python modules and 100+ knowledge points. The content is comprehensive, difficulties and pain points are listed in a complete way. It can be said that every word in this knowledge graph is worth a lot of money. We spent 3 months polishing and polishing the Python knowledge system to give you practical experience and solve the development and interview problems! Great for Python learners!