简体   繁体   English

如何仅打印最后一个 output?

[英]How do I print the last output only?

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)

output: output:

0 not exact with differnece 2000
1 not exact with differnece 1999
2 not exact with differnece 1992
3 not exact with differnece 1973
4 not exact with differnece 1936
5 not exact with differnece 1875
6 not exact with differnece 1784
7 not exact with differnece 1657
8 not exact with differnece 1488
9 not exact with differnece 1271
10 not exact with differnece 1000
11 not exact with differnece 669
12 not exact with differnece 272

de-denting the print is breaking the loop消除印刷品正在打破循环

Set a variable instead of printing.设置变量而不是打印。 Use break to stop the loop rather than return .使用break来停止循环而不是return

Then print the variable at the end.然后在最后打印变量。

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)

You should not return print statements: return just the value you want to print and print the whole function so not this你不应该返回打印语句:只返回你想要打印的值并打印整个 function 所以不是这个

return print(p,"exact!")

but this但是这个

return int(p) + " exact!"

Here is the function altered to meet your requirement:这里是 function 修改以满足您的要求:

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)

The expression p ** 3 is the equivalent of p * p * p .表达式p ** 3等价于p * p * p I basically changed your condition我基本上改变了你的状态

p ** 3 < n

to be成为

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

Another way is this:另一种方式是这样的:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM