【问题标题】:Why does my code work in IDLE but not when I save the file and double click the file为什么我的代码在 IDLE 中可以工作,但在我保存文件并双击文件时却不行
【发布时间】:2014-03-05 20:08:13
【问题描述】:

当我在 IDLE 中运行我的代码时,我的代码工作正常,但是当我在 CMD 中正常打开它时,它会显示一条错误消息并立即关闭,让我没有时间阅读错误消息。然而,我确实设法截取了错误消息,它说:

“文件”文件位置...“第 12 行,在编码中 返回 codecs.charmap_encode(输入,错误,encoding_map) UnicodeEncodeError:“charmap”编解码器无法在位置 102 编码字符“\u03c0”:字符映射到“

我不确定这意味着什么以及如何修复它,奇怪的是它在 IDLE 中有效但在 CMD 中无效。 CMD 和 IDLE 都在同一版本的 python 上,我的计算机上只安装了 1 个版本的 python,所以问题不在于版本不匹配。你知道它为什么工作然后不工作以及如何修复它吗?我使用的是 python 3.3.3。这是我的代码(它用于使用无限系列近似计算 Pi,用户输入他们想要使用的系列的多少项):

import math
go="Y"
while go=="Y" or go=="y" or go=="Yes" or go=="yes":
    count=input("The infinite series 1/1 - 1/3 + 1/5 - 1/7... converges to π/4, how many of these divisions would you like the computer to do?\n")
    if count.isdigit():
        count = int(count)
        pi=0
        realcount = 0
        while realcount <= count:
            realcount = realcount + 1
            if realcount / 2 == math.floor(realcount / 2):
                pi = pi - (1 / ((2 * realcount) - 1))
            else:
                pi = pi + (1 / ((2 * realcount) - 1))
        print("π ≈",4 * (pi))
        go=input("Would you like to try again?\n")
    else:
        go=input("Sorry you must input a positive integer, would you like to try again?\n")

【问题讨论】:

  • 最有可能是 PI 字符。尝试写出 PI,看看是否有帮助。就是它们,或者是您拥有print("π ≈",4 * (pi)) 的那个“等价”字符。很可能控制台使用的编码不能正确处理这些字符。
  • 附加提示:while 条件可以写成while go.lower() in ('y', 'yes'):
  • 谢谢你解决了我的问题。

标签: python cmd python-idle


【解决方案1】:

在代码中添加一行用于设置编码:

# -*- coding: utf-8 -*-
import math
go="Y"
while go=="Y" or go=="y" or go=="Yes" or go=="yes":
    count=input("The infinite series 1/1 - 1/3 + 1/5 - 1/7... converges to π/4, how many of these divisions would you like the computer to do?\n")
    if count.isdigit():
        count = int(count)
        pi=0
        realcount = 0
        while realcount <= count:
            realcount = realcount + 1
            if realcount / 2 == math.floor(realcount / 2):
                pi = pi - (1 / ((2 * realcount) - 1))
            else:
                pi = pi + (1 / ((2 * realcount) - 1))
        print("π ≈",4 * (pi))
        go=input("Would you like to try again?\n")
    else:
        go=input("Sorry you must input a positive integer, would you like to try again?\n")

【讨论】:

    【解决方案2】:

    这与代码中的字符 π(unicode '\u03c0')有关,python 解释器的默认编码是 ASCII,这意味着你不能在不告诉系统的情况下在源代码中使用非 ascii 字符。 您可以 1) 使用 pi 而不是 π,或 2) 在代码的开头添加一行:#coding=utf-8 告诉解释器您在源代码中使用的是 utf-8 编码。

    【讨论】:

      【解决方案3】:

      IDLE 和你的命令文件的区别在于源代码的编码。

      如果没有另外指定,Python 3 将源代码读取为 UTF-8 编码。官方文档有information on encodings,您可以在其中看到如何使用不同的编码。正确的编码取决于您系统的语言环境。或者更好的是,您可以简单地将源代码保存为 UTF-8。该过程取决于您的文本编辑器。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-12
        • 2018-01-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多