简体   繁体   中英

Using while loop to count the number of user inputs

I try to create a while loop function, where program takes six separate user inputs that are in float numbers (meters). Each input is accepted, if number is larger than zero. Each input is dismissed, if number is less than zero.

While loop is supposed to count up to six user inputs and then print:

  • The number of successful inputs
  • The number of dismissed inputs
  • The largest input is
  • The mean of all inputs is

My challenge is that I do not understand how to user while loop so that it counts until a certain number of inputs, and then stops

Here are example outputs:

Give the latest user input: 86.2
Give the latest user input: 81.2
Give the latest user input:  79.6
Give the latest user input:  89.3
Give the latest user input:  -1
Give the latest user input:  86.5

There were 5 succesful input(s).
There were 1 dismissed input(s).
The highest input was 89.3.
The mean of all inputs was 84.56 meters.

How about something like:


nums = []
while len(nums)<6:
  n = int(input())
  if n > 0:
    nums.append(n)

print(nums)
print(min(nums))
print(max(nums))

Giving:

[2, 2, 3, 4, 1, 4]
1
4

try

sum=0
count=0
good_count=0
max_val=-1
while count<6:
    number = int(input())
    if number > 0:
        sum=sum + number
        good_count=good_count+1
        if number>max_val:
            max_val=number            
    count=count + 1
print('there were {0} valid inputs'.format(good_count))
print('there were {0} invalid inputs'.format(count-good_count))

if good_count>0:
    print('the average value was '  ,sum/good_count)
    print('the maximum input values was ', max_val)
else:
    print('there were no valid inputs so an average cannot be calculated')
    print('there were no valid inputs so a maximum value does not exist')```

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM