0

我目前正在使用 Codecademy 熟悉 Python。我学得很快,并且已经安装并使用 Pyscripter 来制作我自己的程序以及 Codecademy 课程。通常,当我将代码从 Codecademy 复制并粘贴到 Pyscripter 并尝试运行它时,当它在 Codecademys 网站上完美运行时会出现错误。是否有不同版本的 Python 之类的?还是 codecademy 没有教授正确的基础知识?我已经包含了一个代码示例和我收到的错误。

def power(base, exponent):  # Add your parameters here!
    result = base**exponent
    print "%d to the power of %d is %d." % (base, exponent, result)

power(37, 4)  # Add your arguments here!

从 Pyscripter 收到的错误:消息文件名行位置
语法
错误无效语法(第 13 行)13 40

另一个例子:

from datetime import datetime
now = datetime.now()

print ('%s/%s/%s') % (now.year, now.month, now.day)

错误:消息文件名行位置
回溯
21类型错误:
% 的不支持的操作数类型:'NoneType' 和 'tuple'
我使用 %s 和 % 似乎有一段时间。

任何澄清将不胜感激。

4

1 回答 1

0

这是 Python 2 和 3 之间的区别,是的。

Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime
>>> now = datetime.now()
>>>
>>> print ('%s/%s/%s') % (now.year, now.month, now.day)
2014/2/23

Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime
>>> now = datetime.now()
>>>
>>> print ('%s/%s/%s') % (now.year, now.month, now.day)
%s/%s/%s
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for %: 'NoneType' and 'tuple'
>>> print ('{0}/{1}/{2}'.format(now.year, now.month, now.day))
2014/2/23

它的核心围绕print在 Python 2 中的语句和 Python 3 中的函数之间的区别。

于 2014-02-23T08:01:02.117 回答