Search code examples
pythonraw-input

How can I create a list from raw_input ?


while true:
    n = raw_input("put your family member's age. if you are done, put 'done'") # if I put int on n, I cannot put done.
    if int(n) == int():
        continue
    if n == str():
        print "ERROR"
        continue
    if n == "done":
        break
print #I couldn't make it

I want to make this program to count the number of family members and the sum of the family member's age

Q1. should I put int on n? but if I put int on n, It makes error when I put done. I want to put only numbers and 'done' in n

Q2. How can I count n? should I have to make a list?

Python is attractive thing. but when I meet problem, it makes me crazy.


Solution

  • Using this, you append to a list, then print the list and the sum once the user types done. isdigit() avoids the need for a try-except, however keep in mind it only works for positive values, without decimal places. For ages, it should be quite appropriate:

    age_list = []
    while True:
        n = raw_input("put your family member's age. if you are done, put 'done'")
        if n.isdigit():
            age_list.append(int(n))
        elif n == "done":
            break
        else:
            print "ERROR"
    
    print age_list
    print sum(age_list)