简体   繁体   中英

Trouble creating a loop that filters for integers and a certain value

I am trying to create a basic program that prompts the user for a number and adds that number to a list. If the value entered is not an integer it should display 'Please enter a whole number' and if the value entered is "done" then the program should stop looping, count the number of values in the list, sum them, and give the average.

start = 0

while start == 0:
    prompt = int(input('enter a number: '))
    print(prompt)

    # create an empty list
    our_list = []

    # add user input to our_list
    our_list.append(prompt)

    # Count Script
    count = len(our_list)

    # Total script
    total = sum(our_list)

    #Average script
    average = total/count

    try:
        prompt = type(int)
        for input in prompt:
            if prompt == 'done':
                print('Done!')
                print(total(count, total, average))
                start = 1

    except ValueError:
        print("Please enter a whole number")

Right now I receive a "Type" object is not iterable error. Not sure how I should change this. Appreciate any help as this is my third week starting to code.

your issue is that you assign a type into the value of prompt. Then you say for input in prompt. Here it expects prompt to be a sequence but instead you make it a type val. You can simplyfy and clean up a lot of this code and write it something like

num_list = []
while True:
    user_input = input("enter a number (or done to quit): ")
    try:
        num_list.append(int(user_input))
    except ValueError as ve:
        if user_input == "done":
            break
        else:
            print("Enter whole number or done")

count = len(num_list)
total = sum(num_list)
average = total / count
print(f"""Count: {count}
Total: {total}
Average: {average}""")

OUTPUT

enter a number (or done to quit): 5
enter a number (or done to quit): 3
enter a number (or done to quit): 7.6
Enter whole number or done
enter a number (or done to quit): 45
enter a number (or done to quit): re
Enter whole number or done
enter a number (or done to quit): 3
enter a number (or done to quit): done
Count: 4
Total: 56
Average: 14.0

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