Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

incorrect value outputting from while loop

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)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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: "))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading