1

Okay I'm having a little trouble making this program that adds numbers to a blank list and then having the user choose when to quit the program, and when the user chooses to quit the program will automatically find the average and display it. But whenever the user quits the program it adds 'q' to the list and then obviously crashes it because it can't find the average with a letter in it.

def listsave():
list1 = []
x = None
while True:
    x = input('Enter integer (q to quit):')
    if x != 'q':
        list1.append(x)
    else:
        return sum(list1)/len(list1)
David Fite
  • 13
  • 3
  • Okay so nevermind, after testing, the program doesn't add 'q' to the list but it is turning the number into a string, which isn't great. So if I do this: add x = int(input('Enter integer (q to quit):')) It allows it to enter numbers as int, but now I can't quit the program since it won't allow the letter 'q' – David Fite Oct 19 '17 at 21:59

4 Answers4

0
def listsave():
    list1 = []
    x = None
    while True:
        x = input('Enter integer (q to quit):')
        if x != 'q':
            list1.append(float(x))
        else:
            return sum(list1)/len(list1)
Austin A
  • 566
  • 2
  • 15
0

I'm a dumbass I figured it out. You just force python to store it as a int with the int around the variable in append!

 def listsave():
 list1 = []
 x = None
  while True:
  x = input('Enter integer (q to quit):')
    if x != 'q':
     list1.append(int(x))
else:
    return sum(list1)/len(list1)
David Fite
  • 13
  • 3
0
def listsave():
    my_list = []
    while True:
        try:
            x = input('Enter integer (q to quit): ').strip()
            my_list.append(float(x))
        except ValueError:
            if x.lower() == 'q':
                break
            else:
                print('Input not an integer or "q"')
                continue
    return sum(my_list)/len(my_list)
Dalvenjia
  • 1,953
  • 1
  • 12
  • 16
0

I'd suggest something like the following. Note that you don't need to initialize x with x = None (and doing so isn't considered Pythonic). You also want to do as little as possible in a try block so you don't inadvertently catch unrelated errors.

def average_from_user_input():
    items = []

    while True:
        item = input('Enter integer (q to quit): ')

        if item in ('q', 'quit'):
            return sum(items) / len(items) if items else 0

        try:
            item = int(item)
        except ValueError:
            print('Please enter integers only')
        else:
            items.append(item)