为什么我的代码在IDLE中能运行但保存后双击文件却不能?
当我在IDLE中运行我的代码时,一切正常,但当我在CMD中打开它时,出现了错误信息,窗口瞬间关闭,让我没有时间去看错误信息。不过,我还是成功截图了错误信息,内容是:
“文件 '文件位置...' 第12行,在 encode 函数中 return codecs.charmap_encode(input,errors,encoding_map) UnicodeEncodeError: 'charmap' 编解码器无法在位置102编码字符 '\u03c0': 字符映射到”
我不太明白这是什么意思,也不知道该怎么解决。而且奇怪的是,代码在IDLE中能正常工作,但在CMD中却不行。CMD和IDLE都是同一个版本的Python,我电脑上只安装了一个版本,所以问题不是版本不匹配。你知道为什么在一个环境下能工作而在另一个环境下不行吗?还有怎么解决这个问题?我使用的是Python 3.3.3。以下是我的代码(这是用无限级数计算π的近似值,用户可以输入想要使用的级数项数):
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")
3 个回答
IDLE和你的命令文件之间的区别是因为源代码的编码方式不同。
Python 3 默认会把源代码当作UTF-8编码来读取,除非你另有说明。官方文档里有关于 编码的信息,你可以在那儿看到如何使用不同的编码。正确的编码方式取决于你系统的语言设置。更简单的方法是,你可以直接把源代码保存为UTF-8格式。具体操作要看你使用的文本编辑器。
在你的代码中加一行来设置编码:
# -*- 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")
这里说的是代码中的字符π(unicode '\u03c0')。Python解释器默认使用的编码是ASCII,这意味着如果你想在代码中使用非ASCII字符,就必须告诉系统怎么做。你可以选择两种方法:1)用pi代替π,或者2)在代码的开头加一行:#coding=utf-8
,这样就告诉解释器你在代码中使用的是utf-8编码。