Home > Enterprise >  incorrect value outputting from while loop
incorrect value outputting from while loop

Time:02-13

Here is my code, why is 0 outputting instead of entered value?

cube = 0
value = int(input("Enter a value to be cubed or 0 to quit: "))

while value != 0:
    cube = value **3
    value = int(input("Enter a value to be cubed or 0 to quit: "))

print (value, "cubed is", cube)

CodePudding user response:

First thing you want to do is indent that print, so that it refers to the values inside the loop:

cube = 0
value = int(input("Enter a value to be cubed or 0 to quit: "))

while value != 0:
    cube = value **3
    value = int(input("Enter a value to be cubed or 0 to quit: "))
    print (value, "cubed is", cube)

But now every time you print the result, cube refers to the previous round. So you want to change the order:

# no need to do cube = 0, it contributes nothing
value = int(input("Enter a value to be cubed or 0 to quit: "))

while value != 0:
    cube = value**3
    print (value, "cubed is", cube)
    value = int(input("Enter a value to be cubed or 0 to quit: "))
  • Related