-2
cube = 8
for guess in range(cube+1):
    if guess**3 == cube :
        print("Cube root of ", cube ," is ", guess)
    else :
        print("No integer cube is found ")

The result print out "No integer cube is found" several times, why ? Another one I tried is :

cube = 8
for guess in range(cube+1):
    if guess**3 == cube :
        print("Cube root of ", cube ," is ", guess)
    else:
        if guess**3 != cube :
            break
print("No integer cube is found ")

It just print the last line. Very confused in both ways. Thank you in advance

Ramen
  • 15
  • 1
  • This would be a *great* time to learn how to use a debugger. – Scott Hunter Jun 01 '23 at 17:42
  • Follow the execution logic step by step here: http://pythontutor.com… – deceze Jun 01 '23 at 17:43
  • 1
    You shouldn't print the "not found" message inside the loop, because it might be found later. You have to print it *after* the loop is done if it never found what it's looking for. – Barmar Jun 01 '23 at 17:44

1 Answers1

0

you can use a flag variable to keep track of whether an integer cube root has been found. Example

cube = 8
found = False

for guess in range(cube+1):
    if guess**3 == cube:
        print("Cube root of", cube, "is", guess)
        found = True
        break

if not found:
    print("No integer cube root found")
pyjedy
  • 389
  • 2
  • 9