计算raw_input数字

时间:2016-02-14 15:48:04

标签: python counting raw-input

python 2.7:计算用户输入的数量。 我无法弄清楚如何计算raw_input ...这是我到目前为止所拥有的:

while True:
    datum = raw_input('enter a number: ')  
    if datum == 'done': break                  

count = 0                                    
for line in datum:                           
    if datum == int(datum):
         count = count + 1 

print 'count', count

3 个答案:

答案 0 :(得分:0)

您可以使用tryexcept

count=0应该在while

之前

尝试:

count = 0 

while True:
    datum = raw_input('enter a number: ')  
    if datum == 'done': break                  

    try:
        int(datum)
        count += 1
    except ValueError:
        pass

print 'count', count

答案 1 :(得分:0)

datum = []
total = 0
count = 0
while True:
    data = raw_input('enter a number: ')  
    if data == 'done': break                  
    datum.append(data)
for i in datum:
    try:
        total = total + int(i) 
        count += 1
    except:
        pass
print 'count', count, ' total',total

答案 2 :(得分:0)

count = 0
while True:
     dat_num = raw_input('enter a number: ')
     if dat_num == 'done':break
     else:
          dat_num = int(dat_num)
          count += dat_num
     print 'count', count