简体   繁体   中英

How to store arbitrary number of inputs from user?

Just wondering how I would store the inputs for an average sum of square roots problem.

The user can input as many numbers as they until they type 'end'

here is what i have for that

while(True):
    x = input("Enter a number please:")
    if x == 'end':
        break

You can append these values to a list. Sum and then divide by the length for the average.

nums = []
while True:
    x = input("Enter a number:")
    if x == 'end':
        avg = sum(nums) / len(nums)
        print("And the average is....", avg)
        break
    elif x.isdigit():
        nums.append(int(x))
    else:
        print("Try again.")

The next thing you'd want to learn about is a data structure such a list . You can then add items to the list on the fly with list.append .

However, it's noteworthy that where ever you're learning Python from will certainly go over lists at one point or another.

If you mean that you want to store all the x values given, just use a list. l = [] l.append(x).

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