簡體   English   中英

Python 從函數中打印括號

[英]Python prints the parenthesis from the function

簡單的代碼,但有點奇怪的問題。 Python 傾向於在打印函數中打印括號和逗號。 這只發生在第 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 編寫的代碼,其中 print 是一個函數

>>> 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

用:

from __future__ import print_function

作為腳本中的第一行。 然后python 2.7打印兼容python 3打印

由於您使用的是 python 2.7,所以 print 是一個語句(不是函數),因此它不接受任何參數,並且在調用時不帶括號(感謝 bruno 在評論中指出這一點)。 所以在前兩個打印語句中,您只是打印一個元組。 在最后一個實例中,括號將單個元素分組,因此什么都不做。

print('a', 'b') # print tuple
print ('a', 'b') # print tuple, but whitespace makes it more clear what's happening
print('a') # print string
print ('a') # print string, but whitespace makes it more clear what's happening

打印文本時使用正確的格式:

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("%s is a leap year." % year_str)
    else:
        print("%s is not a leap year." % year_str)
else:
    print("Invalid year.")

print不是Python2 中的方法,而是語句 除非你想打印一個元組,否則你應該跳過使用括號。

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 str(year_str) +" is a leap year."
        else:
            print str(year_str) +" is not a leap year."
    else:
        print "Invalid year."

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM