Home > Enterprise >  Why does my While loop omit the last input and adding a 0 in the list?
Why does my While loop omit the last input and adding a 0 in the list?

Time:12-04

I want to build a program that takes the amount of rainfall each day for 7 days and then output the total and average rainfall for those days.

Initially, I've created a while loop to take the input:

rainfall = 0
rain = []
counter = 1

while counter < 8:
    rain.append(rainfall)
    rainfall = float(input("Enter the rainfall of day {0}: ".format(counter)))
    counter  = 1
print(rain)

But the output that is generated is not what I expected:

[0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0]

It will enter a 0 as first value and then omit the last input (here the input is 1 to 7 as an example)

CodePudding user response:

In the first line of your while:

rain.append(rainfall)

at this point since you didn't reassign it rainfall is still the value that you set it to earlier:

rainfall = 0

and your while runs for the numbers

1, 2, 3, 4, 5, 6, 7

since those are the integers < 8

CodePudding user response:

This is the correct version for your aim.

rain = []
counter = 1

while counter <= 7:
    rainfall = float(input("Enter the rainfall of day {0}: ".format(counter)))
    rain.append(rainfall)
    counter  = 1
print(rain)

You were passing default parameter you created for rainfall. No need to set default rainfall.

  • Related