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

Why is my while loop not adding the values for the total

I’m supposed to find the weight of the dogs and while the loop did work, when I got an error and tried the variable, it just gave me 0.
I’m being asked to start a fixed loop 5 times and to enter the foodweight.

This is what i have right now


for loop in range(5):
    foodweight=int(input("Please enter the weight of the food:"))
    while foodweight<0 or foodweight>200:
        print("Invalid, weight cant be less than 0 or more than 200")
        foodweight=int(input("Please enter the actual weight of the food:'"))
        totalweight+=foodweight    
print(totalweight)

Instead of for example printing 400, it prints 0

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

>Solution :

If thats the correct indentation then you only ever add values that you enter after an invalid input first

unindent the line appending to total weight

while foodweight<0 or foodweight>200:
    print("Invalid, weight cant be less than 0 or more than 200")
    foodweight=int(input("Please enter the actual weight of the food:'"))
totalweight+=foodweight    
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