简单的代码,但有点奇怪的问题。 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/