如何仅打印最后一个输出?

时间:2021-02-12 19:59:34

标签: python python-3.x function

import colorama

ImportError                               Traceback (most recent call last)
<ipython-input-33-88ec09736251> in <module>()
----> 1 import colorama
2 frames
/usr/local/lib/python3.6/dist-packages/colorama/ansitowin32.py in <module>()
      4 import os
      5 
----> 6 from .ansi import AnsiFore, AnsiBack, AnsiStyle, Style, BEL
      7 from .winterm import WinTerm, WinColor, WinStyle
      8 from .win32 import windll, winapi_test
ImportError: cannot import name 'BEL'
---------------------------------------------------------------------------
NOTE: If your import is failing due to a missing package, you can
manually install dependencies using either !pip or !apt.
To view examples of installing some common dependencies, click the
"Open Examples" button below.

输出:

def cubroot(n):
    for p in range(n):
        if n>p*p*p:
            d=n-(p*p*p)
            print(p,"not exact with differnece",d)
        elif (p*p*p)==n:
            return print(p,"exact!")
    pass

cubroot(2000)

去除印刷品的凹痕正在打破循环

3 个答案:

答案 0 :(得分:2)

设置一个变量而不是打印。使用 break 来停止循环而不是 return

然后在最后打印变量。

def cubroot(n):
    if n == 0:
        return 0
    elif range < 0:
        n = -n
    for p in range(n):
        if n>p*p*p:
            d=n-(p*p*p)
            result = f"{p} not exact with difference {d}"
        elif (p*p*p)==n:
            result = f"{p} exact"
            break
    print(result)

答案 1 :(得分:1)

你不应该返回打印语句:只返回你想要打印的值并打印整个函数而不是这个

return print(p,"exact!")

但是这个

return int(p) + " exact!"

答案 2 :(得分:1)

这是为了满足您的要求而更改的功能:

def cubroot(n):
    for p in range(n):
        if (n ** (1 / 3) - 1) ** 3 < p ** 3 < n:
            d = n - p ** 3
            print(p, "not exact with differnece", d)
        elif p ** 3 == n:
            return print(p, "exact!")

cubroot(2000)

表达式 p ** 3 等价于 p * p * p。 我基本上改变了你的情况

p ** 3 < n

成为

(n ** (1 / 3) - 1) ** 3 < p ** 3 < n

另一种方式是:

def cubroot(n):
    for p in range(n):
        if p ** 3 < n and (p + 1) ** 3 > n:
            d = n - p ** 3
            print(p, "not exact with differnece", d)
        elif p ** 3 == n:
            return print(p, "exact!")

cubroot(2000)