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:
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
.
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
return print(p,"exact!")
but this
return int(p) + " exact!"
Here is the function altered to meet your requirement:
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
. 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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.