while / try /除外十进制TypeError不起作用

时间:2018-07-01 09:44:12

标签: python exception while-loop try-catch decimal

我以为我最终可以在while / try / except循环之外使用一些东西,但是遇到了问题。我的任务是让用户输入计算机的请求编号,直到输入“ 0”为止。此后,将添加输入的数字。我的问题是,“例外”部分无法捕获非数字条目。如果输入了非数字条目,我会收到一条常规错误消息,该错误消息会停止程序。当我输入3个数字并且第4个输入是'm'时,会发生以下情况:

 on win32
Type "copyright", "credits" or "license()" for more information.
>>> 
 RESTART: C:/Users/Username/Documents/CISPROG1/Homework 5/Homework5.1.SumGenerator.py 
Enter 1st element (or type '0' to finish). 
1
Enter 2nd element (or type '0' to finish). 
2
Enter 3rd element (or type '0' to finish). 
3
Enter 4th element (or type '0' to finish). 
m
Traceback (most recent call last):
  File "C:/Users/Username/Documents/CISPROG1/Homework 5/Homework5.1.SumGenerator.py", line 24, in <module>
    + "%s element (or type '0' to finish). \n" % suffix()))
decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]
>>>

我认为这将是“ TypeError”,但并没有抓住它。实际上,甚至没有“ Exception”错误类型可以捕获它。如何捕获非数字输入?我认为问题与Python如何处理Decimal类型的非数字输入有关。

这是我的程序:

from decimal import *

#start:
lInputSequence = []
i = 1

def suffix():
    if i%10 == 1 and i != 11:
        return "st"
    elif i%10 == 2 and i != 12:
        return "nd"
    elif i%10 == 3 and i != 13:
        return "rd"
    else:
        return "th"

decInputElement = 1
while True:
    decInputElement = Decimal(input("Enter " + str(i)
                                    + "%s element (or type '0' to finish). \n" % suffix()))
    try:        
        if decInputElement == 0:
            break
        else:
            lInputSequence.append(decInputElement)
            i = i+1
    except TypeError:
        print("Please enter a number.")
print(lInputSequence)
print("The sum of these %s elements is %s" % (len(lInputSequence),sum(lInputSequence)))
#end

1 个答案:

答案 0 :(得分:0)

因此,问题似乎有两个方面:

  1. 为了捕获由十进制类型的不正确输入引起的错误,该输入必须位于“ try”块中。
  2. 从技术上讲该错误不是TypeError,因此如果不更改“ except”块中的错误类型,就不会捕获该错误。

解决方案:

  1. 将输入行移动到“ try”块(根据@Daniel Roseman)并
  2. 将错误类型更改为“异常”,这是一个主要错误类别,可捕获任何具体错误。

这并不能说明发生哪种错误,但是会捕获任何输入错误。

def run(self):
    self.phyconn = apsw.Connection(self.fileName)
    self.memconn = apsw.Connection(":memory:")
    try:#backup.__exit__() just make sure copy if finished,not close backup,so with is good,memconn is still exist when out
        with self.memconn.backup("main", self.phyconn, "main") as backup:
            # call with 0 to get the total pages
            backup.step(0)
            total = backup.pagecount

            stepped = 0
            one_percent = total if total < 100 else total // 100
            last_percentage = 0
            while stepped <= total:
                if self.cancel:
                    #self.progressCanceled.emit()
                    self.memconn=None
                    return
                backup.step(one_percent)
                stepped = stepped + one_percent
                stepped_percentage = stepped*100//total
                if stepped_percentage != last_percentage:
                    last_percentage = stepped_percentage
                    #self.progressChanged.emit(stepped_percentage)
                    websocket.UpdateLoadDBProgress(stepped_percentage,self.sid)