簡體   English   中英

如何將打印語句與返回語句放在同一行?

[英]How do I put a print statement on the same line as a return statement?

我試圖在與返回語句相同的行上獲得一個打印語句,我該怎么做 go 呢?

我試圖將 print 語句放在 if 語句下方,但在 return 語句上方,並將結果打印在 return 語句上方。

def isleap(y):
    if y % 400 == 0:
        print("Year %d is divisible by 400, therefore it is a leap year" %y)
        return True
    elif y % 100 ==0:
        return False
    elif y % 4 == 0:
        return True
    else:
        return False

我正在導入上面的代碼以從另一個文件運行,即:

import leapyear
print (leapyear.isleap(1800))
print (leapyear.isleap(2019))
print (leapyear.isleap(2000))
print (leapyear.isleap(2012))

這是結果:

False
False
Year 2000 is divisible by 400, therefore it is a leap year
True
True

我希望結果有類似的東西

正確:2000 年可以被 400 整除,因此是閏年

都在同一行,涉及冒號。

您可以return True和 print 語句一起返回。 借助星*運算符,您可以將元組中的元素作為單獨的參數傳遞給print() function:

def func():
    return True, 'It works.'

print(*func())
# True It works.

如果打印語句的順序不重要,您可以將參數end=''添加到第一個print() function:

def func():
    print('It works.', end='')
    return True

print(func())
# It works.True

你可以這樣做:

def isleap(y):
    if y % 400 == 0:
        return True, ': Year %d is divisible by 400, therefore it is a leap year' %y 
    elif y % 100 ==0:
        return False, ''
    elif y % 4 == 0:
        return True, ''
    else:
        return False, ''


print(*isleap(1800), sep='')
print(*isleap(2019), sep='')
print(*isleap(2000), sep='')
print(*isleap(2012), sep='')


print()


# If you want to use it later.
ret = isleap(2000)
if ret[0]:
    print('Length of the message is:', len(ret[1]))

Output:

False
False
True: Year 2000 is divisible by 400, therefore it is a leap year
True

Length of the message is: 60

在我回答了這個問題之后,提出這個問題的人問如果他/她想重用結果怎么辦。 因此,我更新了與答案類似的答案。

暫無
暫無

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

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