Problems encountered in python code and solutions, python code
1. Type determination and conversion of raw_input characters:
Raw_input is a character by default. If the input is a numeric character, you want to convert it automatically. That is, if the input is a, no operation is performed. If the input is 3, it is converted to an integer.
Try .. else t .. to convert the value of raw_input () to an int. If '23' is input, it is directly converted to a number 23, if 'xx' is entered, try to fail and then run the failed t part.
#! /Usr/bin/python27 # _ * _ coding: UTF-8 _ * _ def myint (s): try: eval (s) ### eval evaluate the string 'str' as a valid expression and return the computation result counter t NameError: ### name error return s response t SyntaxError :## syntax error return s else: return eval (s) a = raw_input ('Please input: ') print (myint ())
Note:
1. Add NameError to prevent input string errors:
Please input: aaa
Traceback (most recent call last ):
File "test. py", line 16, in <module>
Print (myint ())
File "test. py", line 6, in myint
Eval (s) ### eval evaluate the string str as a valid expression and return the calculation result
File "<string>", line 1, in <module>
NameError: name 'aaa' is not defined
2. When SyntaxError is added, errors in Chinese input can be prevented:
Please input: China
Traceback (most recent call last ):
File "test. py", line 16, in <module>
Print (myint ())
File "test. py", line 6, in myint
Eval (s) ### eval evaluate the string str as a valid expression and return the calculation result
File "<string>", line 1
China
^
SyntaxError: invalid syntax
2. When comparing and determining the Chinese characters stored in the dictionary or list, the following error occurs:
Ascii codec can't decode byte 0xe8 in position 0: ordinal not in range (128)
1. Cause Analysis: character problems ..
2. Solution: Add the following three lines to the problematic script:
Import sys
Reload (sys)
Sys. setdefaultencoding ('utf-8 ')