Question

Write a program to continuously ask the user to enter numbers until the user enters a number that is greater than 100. Then print the average value of the numbers before the last input. For instance, if the user enters 12, 23, 9, 15, 155, then the input terminates (because 155>100) and your program prints the average value of 12, 23, 9, 15, which is 14.75.

This is what I have so far and can't seem to get it to work correctly

def average():
 inputnum = 0
 numlist = []
while inputnum <=100:
 inputnum = input("Please input a number: ")
 inputnum = float(inputnum)
 numlist.append(inputnum)
average = sum(numlist)/len(numlist)
print(average)
Was it helpful?

Solution

Your program works fine for me, but the indentation is wrong. It has to be like this:

def average():
    inputnum = 0
    numlist = []
    while inputnum <=100:
        inputnum = input("Please input a number: ")
        inputnum = float(inputnum)
        numlist.append(inputnum)
    average = sum(numlist)/len(numlist)
    print(average)

average() # finally call the function

To exclude the number entered that is greater than 100, do this:

def average():
    inputnum = 0
    numlist = []
    while inputnum <=100:
        inputnum = input("Please input a number: ")
        inputnum = float(inputnum)
        numlist.append(inputnum) if inputnum <=100 else None
    average = sum(numlist)/len(numlist)
    print(average)

average() # finally call the function

For Jython:

def average():
    inputnum = 0
    numlist = []
    while inputnum <=100:
        inputnum = input("Please input a number: ")
        inputnum = float(inputnum)
        if inputnum <= 100:
            numlist.append(inputnum)
    average = sum(numlist)/len(numlist)
    print(average)

average() # finally call the function
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top