无法理解价值错误试试

时间:2013-01-01 17:11:53

标签: python python-2.7

有人可以解释这段代码对我有用吗? 我从try命令下来不明白它。 这个while循环对我有用。但是我不明白它是如何工作的。

price = 110 #this i get
ttt = 1 #this i get

while price< 0 or price> 100: #this i get
    if ttt >=2: #this i get
        print "This is an invalid entry" #this i get
        print "Please enter a number between 0 and 100" #this i get
    try: #From here i do not understand , but without it, it does not work
          price= int(raw_input("Please enter the price : "))
    except ValueError:
      price = -1   
    ttt +=1

由于我是学习者,我真的不想采用更复杂的方式来做这件事。 我只想完全理解循环中发生的事情。

3 个答案:

答案 0 :(得分:2)

try:启动一个代码块,可以处理异常。 except ValueError子句意味着如果在块中抛出 ValueError异常,那么该异常将被except下的代码捕获并处理。

在这种情况下,这意味着如果有人输入的值不是有效整数,price将设置为-1

由于price现在设置为-1,因此while循环再次要求定价(-1 < 0True):

while price< 0 or price> 100:  # price was set to -1, so the while loop condition is True.

以下简要说明异常如何破坏程序:

>>> int('not an integer')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'not an integer'
>>> try:
...     int('not an integer')
... except ValueError:
...     print 'Caught the exception, no problemo!'
... 
Caught the exception, no problemo!
>>> try:
...     price = int('not an integer')
... except ValueError:
...     price = -1
... 
>>> price
-1

有关其工作原理的详情,请参阅Python tutorial on exception handling

答案 1 :(得分:2)

try ... except处理异常。异常处理是一个广泛的主题,对于python,你可以在这里阅读更多相关内容:http://docs.python.org/2/tutorial/errors.html#handling-exceptions

在您的情况下,输入来自用户:

raw_input("Please enter the price : ")

并将其转换为整数:

int(...)

现在会发生什么,当用户输入&#34;新年快乐&#34;?它不是一个数字,它是一个错误的值,它是ValueError。函数int raisesValueError,当它无法产生结果时。

如果该条件不会被处理,程序将在那里停止。您可以将关键部分包装到try语句中,并指定您想要发生的事件,而不仅仅是退出。在你的情况下,价格只是设置为-1:

price = -1  

最后应该确保用户输入0到100之间的price,这就是全部。

答案 2 :(得分:2)

try语句是一种在崩溃之前捕获代码的方法,或者是对未捕获的异常退出的方法。某些函数可能会抛出可能导致应用程序崩溃/强制退出的错误,并且try块会占用可能的错误,并允许您对其执行某些操作。

即。 - &GT;尝试打开日志文件但未找到文件的应用程序...

  

UnCaught:Force-quite,IOException。
  抓住:执行另一个创建文件的代码块。

在您的示例中,它将从提示中获取原始数据,并将其分配给整数值...但是abc无法转换为整数,因此通常会崩溃...一个TRY块,它将返回-1,表示它没有收到预期的结果。