Problems encountered in Python code and their solutions

Source: Internet
Author: User

One, for raw_input input characters for type judgment and conversion:

Raw_input input Default is a character, if the input is a numeric character, want to automatically convert, that is: input is a, do not operate, if the input is 3, that is converted to an integer.

You can use try: Except. method, let the program convert the value of raw_input () input to int, if the input is ' 23 ' is converted directly to the number 23, if the input is ' xx ' will try to fail and then run the except part.

#!/usr/bin/python27#_*_ coding:utf-8 _*_defMyint (s):Try: eval (s)## #eval将字符串str当成有效的表达式来求值并返回计算结果    exceptNameerror:## #名称错误        returnsexcept SyntaxError: # # #语法错误return S    Else:        returnEval (s) a= Raw_input ('Please input:')Print(Myint (a))


Special Note:

1, plus nameerror, can prevent the input string error:

Please INPUT:AAA
Traceback (most recent):
File "test.py", line +, in <module>
Print (Myint (a))
File "test.py", line 6, in Myint
Eval (s) # # #eval将字符串str当成有效的表达式来求值并返回计算结果
File "<string>", line 1, in <module>
Nameerror:name ' AAA ' is not defined

2, plus syntaxerror, can prevent input errors in Chinese:

Please input: China
Traceback (most recent):
File "test.py", line +, in <module>
Print (Myint (a))
File "test.py", line 6, in Myint
Eval (s) # # #eval将字符串str当成有效的表达式来求值并返回计算结果
File "<string>", line 1
China
^
Syntaxerror:invalid syntax

Second, in order to store in the dictionary or list in the Chinese comparison of the judgment, the following error occurred

ASCII codec can ' t decode byte 0xe8 in position 0:ordinal not in range (128)

1. Cause Analysis: Character issues.

2. Workaround: Add the following three lines to the problematic script:

Import Sys
Reload (SYS)
Sys.setdefaultencoding (' Utf-8 ')

Problems encountered in Python code and their solutions

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.