Python 打印函数中的括号

标签 python

简单的代码,但有点奇怪的问题。 Python 倾向于在 print 函数中打印括号和逗号。这只发生在第 5 行和第 7 行,但不会发生在最后一行。知道出了什么问题吗?

例如每行的输出:

(2016年,是闰年)

(2015,不是闰年)

年份无效。

year_str = input("Please enter a numerical year: ")
year = float(year_str)
if year == int(year) and year > 0:
    if (year/4)==int(year/4) and (year/100)!=int(year/100) or (year/400)==int(year/400):
        print(year_str, " is a leap year.")
    else:
        print(year_str, "is not a leap year.")
else:
    print("Invalid year.")

最佳答案

您的问题是您正在使用为 python 3 编写的代码,where print is a function :

>>> import sys; sys.version_info.major
3
>>> print('a', 'b')
a b

但是在 python 2 中运行它,它是一个语句:

>>> import sys; sys.version_info.major
2
>>> print ('a', 'b')
('a', 'b')

如果您正在编写要在 python 2 和 python 3 中以相同方式打印的代码,您可以使用

from __future__ import print_function
print('a', 'b')  # works as expected in both versions of python

关于Python 打印函数中的括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51241722/

相关文章:

python - 如何将 a= ['raj' 、 'rj' 、 'reba' ] 与 b=[1,2,2] (整数)相乘以获得 c = ['raj' 、 'rj' 、 'rj' 、 0x1045679 的输出10、 'reba']

python - 整数值之间的条件前向填充

python - 只能是存储在 pygame.sprite.Group 中的矩形对象

python re.search错误TypeError : expected string or buffer

python - Flask 分页问题

python - WTForms 中的选择验证不会在数据库更新时更新

python - 用于查找 { } 内所有文本的正则表达式,包括空格和换行符

python - 使用 Matplotlib 和 NumPy 在图像上绘制圆圈

python - Django REST 框架 - 带有附加参数的 HyperlinkedRelatedField

python - 带有 LXML 元素的 XPath