怎么来试试:阻止来自:python中的块?

时间:2016-12-13 10:41:57

标签: python python-2.7 python-3.x

summ=0
average=0
count=0
try:
    while True:
        enterNumber=raw_input("Enter a number:")
        if enterNumber=='done':
            print summ
            print average
            print count
            break
        else:
            summ=summ+int(enterNumber)
            count=count+1
            average=float(summ/count)


except:
    print "Invalid number!" #when this block is reached the program ends,
                            #I want the program to continue till I enter                  
                            #'done'

3 个答案:

答案 0 :(得分:0)

try: ... except: ...块无法以任意方式控制程序流 - 它只是确保except(或elsefinally等其他对应方式只要发生异常,就会运行块。

要“回到”程序的另一部分,您必须使用另一个contrso结构。这里可能有用的是while

while True:
    try:
         # code goes here
         ...
    except:
         # handle exception
         ...
    else:
         # The else block of a `try` is
         # only entered when no exceptions occur
         break  # this gets out of the while block

答案 1 :(得分:0)

summ=0
average=0
count=0
while True:
  # add try/except under while's scope
  try:
    enterNumber=raw_input("Enter a number:")
    if enterNumber=='done':
        print (summ)
        print (average)
        print (count)
        break
    else:
        summ=summ+int(enterNumber)
        count=count+1
        average=float(summ/count)
  except Exception as e:
      print (e)
      print ("Invalid number!") #when this block is reached the program ends,
                              #I want the program to continue till I enter                  
                              #'done'

Enter a number: hey
invalid literal for int() with base 10: 'hey'
Invalid number!
Enter a number: 10
Enter a number: done
10
10.0
1

答案 2 :(得分:0)

这可能是您想要的版本:

enterNumber = None
summ = 0
average = 0
count = 0

while enterNumber != 'done':
    enterNumber = raw_input("Enter a number:")
    try:
        enterInt = int(enterNumber)
    except ValueError:
        print("Invalid number!")
        continue

    summ += enterInt
    count += 1

# average = summ/count        # this works in python 3
average = summ / float(count) # the safe way for python 2
print(summ)
print(average)
print(count)

请注意:

  • 您无需计算输入循环内的平均值。
  • try/catch仅包装可能引发异常的代码部分。
  • float(summ/count)(在您的版本中)进行整数除法(至少在python 2中); summ / float(count)可能是你想要的。
  • 当您输入Invalid number!时,此代码会打印done。这可以改善。