1

I've been tasked by my programming professor to create a program that calls for a user to enter as many positive integers (including zero) as they care to enter. Anything other than a positive integer stops input and calculates/displays the Sum, Average, and Count of the numbers.

The main issue I'm having has to do with returning multiple positive integers to be passed across the program. I can't seem to find what I need.

inputPostiveInteger()

Pass in nothing
Ask the user for a positive integer
Return the integer is the user inputs one
Return -1 if the user does not input a positive integer

The way he had the program shown to work would be example -

Enter a positive integer, anything else to quit: 1
Enter a positive integer, anything else to quit: 5
Enter a positive integer, anything else to quit: 10
Enter a positive integer, anything else to quit: cat
Sum 16
Average 5.3
Total numbers 3

I've tried multiple ways of try/except and while not clauses to get the input portion correct but can't seem to wrap my brain around this one.

I understand the formulas in how to calculate / display the average, counts, sum - but can't seem to get vetted integer entries down inside of multiple formulas.

Ex. for attemping the inputs

def inputPositiveInteger():
    try:
        userInt = int(input("Enter a positive integer, anything else to quit: ")) > -1
    except ValueError:
        return -1

def main():
    total = 0
    count = 0
    posInt = inputPositiveInteger()
    while posInt != -1:
        total += posInt
        count += 1

main()

total = 0
userInt = int(input('Enter a positive integer, anything else to quit: '))

while userNumber > -1:
    total += userInt
    userInt = int(input('Enter a positive integer, anything else to quit: '))
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Alex
  • 29
  • 1
  • In your try block , you don't encounter an error so it will never end , a value errors occurs for reasons like division by zero , I would recommend that instead of try you go with a simple break in an if statement , there is no reason to overly complicate such a simple task – Niteya Shah Oct 28 '18 at 09:33
  • you're just not returning the `userInt` from your function, so `posInt` will be getting set to `None` (functions implicitly return this value) – Sam Mason Oct 28 '18 at 09:51
  • You dont return from inputPositiveInteger if the input was valid, your while loops is endless or never hit as the input value never changes _inside_ of it. Did you debug your code in any kind or form? # https://stackoverflow.com/questions/1623039/python-debugging-tips – Patrick Artner Oct 28 '18 at 09:53

3 Answers3

3

i try to make my solution resemble your code a bit:

def inputPositiveInteger():
    try:
        userInt = int(input("Enter a positive integer, anything else to quit: "))
    except ValueError:
        return -1

    if userInt < 0:
        return -1
    return userInt

def main():
    total = 0
    count = 0
    posInt = inputPositiveInteger()
    while posInt != -1:
        total += posInt
        count += 1
        posInt = inputPositiveInteger()

    if count == 0:
        print("Sum:", None)
        print("Average:", None)
        print("Total numbers:", None)
    else:
        print("Sum:", total)
        print("Average:", total/count)
        print("Total numbers:", count)

main()

Also you may or may not have covered Arrays a.k.a. Lists which in my opinion would be the way to go, also here there is no try, except necessary:

def inputPositiveInteger():
    userInt = input("Enter a positive integer, anything else to quit: ")
    # str.isnumeric checks that a string only contains numbers and isn't empty
    if not userInt.isnumeric():
        return -1
    return int(userInt)

def main():
    posInt = inputPositiveInteger()
    nums = []
    while posInt != -1:
        nums.append(posInt)
        posInt = inputPositiveInteger()

    if nums:
        print("Sum:", sum(nums))
        print("Average:", sum(nums)/len(nums))
        print("Total numbers:", len(nums))
    else:
        print("Sum:", None)
        print("Average:", None)
        print("Total numbers:", None)

main()

Hope this helps, good luck with your class.

Philogy
  • 283
  • 1
  • 12
  • 1
    Upvoted for trying to replicate the code structure, although an excellent answer would explain, what the problem is with the OP's code. – Mr. T Oct 28 '18 at 09:53
1

Try this:

def finish(summ,count):
    print('Sum',summ)
    print('Count',count)
    print('Avg',round(summ/count,5))

summ = 0
count = 0
while True:
    try:
        userInt = int(input('Enter a positive integer, anything else to quit: '))
        if userInt >= 0:
            summ += userInt
            count += 1 
        else:
            finish(summ,count)
            break
    except:
        finish(summ,count)
        break
0

Thank you for the suggestion to narrow the input down, I ended up with this as the code for the final submission.

def calcAverage(total, count):
    return round(float(total) / float(count), 2)

# prompt user to enter posInt
def inputPositiveInteger():
    userInt = input("Enter a positive integer, anything else to quit: ")
    # return input if digit, else return -1
    if not userInt.isdigit():
        return -1
    return int(userInt)

def main():
    # call function
    posInt = inputPositiveInteger()
    nums = []
    while posInt != -1:
        nums.append(posInt)
        posInt = inputPositiveInteger()

    if nums:
        print("Sum", sum(nums))
        print("Average", calcAverage(sum(nums), len(nums)))
        print("Total numbers", len(nums))


main()
Alex
  • 29
  • 1