【问题标题】:Implementation of try/except in Python?python中try/except的实现?
【发布时间】:2013-11-13 06:01:36
【问题描述】:

我只是被这段代码弄糊涂了:

print("Welcome to Healthometer, powered by Python...")
miles = input("How many miles can you walk?: ")
if float(miles) <= 0:
    print("Who do you think you are?!! Go and walk 1000 miles now!")
elif float(miles) >= 10:
    print("You are very healthy! Keep it up!")
elif float(miles) > 0 and miles < 10:
    print("Good. Try doing 10 miles")
else:
    print("Please type in a number!")
    miles = float(input("How many miles can you walk?: "))
    if miles <= 0:
        print("Who do you think you are?!! Go and walk 1000 miles now!")
    elif miles >= 10:
        print("You are very healthy! Keep it up!")
    elif miles > 0 and miles < 10:
        print("Good. Try doing 10 miles")

但是,看看错误: http://i.stack.imgur.com/PYT80.png

有人告诉我在 Python 中尝试 try/except,但在查看文档后,我不知道该做什么以及如何使用代码中的所有其他 if 和 elif 来实现它。 我试过这样做:

print("Welcome to Healthometer, powered by Python...")
try:
    miles = float(input("How many miles can you walk? "))
except ValueError:
    print("That is not a valid number of miles")

if float(miles) <= 0:
    print("Who do you think you are?!! Go and walk 1000 miles now!")
elif float(miles) >= 10:
    print("You are very healthy! Keep it up!")
elif float(miles) > 0 and miles < 10:
    print("Good. Try doing 10 miles")
else:
    print("Please type in a number!")
    miles = float(input("How many miles can you walk?: "))
    if miles <= 0:
        print("Who do you think you are?!! Go and walk 1000 miles now!")
    elif miles >= 10:
        print("You are very healthy! Keep it up!")
    elif miles > 0 and miles < 10:
        print("Good. Try doing 10 miles")

但它给出了:第 7 行,在 如果浮动(英里)

我正在使用 Python 3.3.2

【问题讨论】:

  • 你刚刚发布了这个问题,他们确实告诉你如何使用它。 stackoverflow.com/questions/19736589/…
  • 是的,他们做到了,但不知道如何在代码中实现它!
  • 当我将它放入代码时,我遇到了一大堆错误。
  • 你得到这个“这不是一个有效的里程数”对吗?
  • @jeremyne​​albrown:请您将其写为答案并给出更正的代码。非常感谢!

标签: python-3.x


【解决方案1】:

我回答了你的另一个问题,但我想我也可以在这里回答。

while True:
    try:
        miles = float(input("How many miles can you walk?: "))
        break
    except:
        print("Please type in a number!")

#All of the ifs and stuff
#Make sure not to put these in the loop, they go AFTER!!

代码很简单:

  • 它将继续尝试将输入转换为浮点数,如果失败则循环回到开头。
  • 当最终成功时,它会从循环中中断并转到您放置在下方的代码。

编辑:

为了进一步解释,您收到错误 NameError: name 'miles' is not defined 的原因是因为 Try/Except 会失败,并且不会将 miles 定义为输入。相反,它会打印“请输入...”,然后继续到ifs。

这就是你需要循环的原因。它使您的代码不断尝试定义miles,直到成功,然后才从循环中中断并进入逻辑。

【讨论】:

  • 你仍然需要在尝试之前声明miles/除非其他明智的 if 语句将失败。
  • @jramirez 哦,真的吗?我使用 python 2.7,你不需要在那个版本中。你确定你需要在 python 3.3 中吗?
  • @TimTimmy 抱歉,我不确定你在说什么。什么?
  • 经过大量汗水和汗水,我选择了你的答案 - 请注意 - - 如果更好,我可能会选择另一个答案,但你的是 3.3 Python!
  • @TimTimmy 很高兴我能帮上忙。
【解决方案2】:

发生的情况可能是您陷入了 except 块,因此 miles 变量永远不会被声明,而您的其余代码需要该变量。通过添加raise,它将强制您的代码退出,以便在输入出现问题时其余代码永远不会运行。

try:
    miles = float(input("How many miles can you walk? "))
except Exception, e:
    print("That is not a valid number of miles")
    raise e

编辑:

我明白你现在要做什么了。这将使您的代码按预期工作。顺便说一句,你处理这个问题的方式不是很好。您需要阅读有关如何处理用户输入的更多信息。

miles = None
try:
    miles = float(input("How many miles can you walk? "))
except ValueError:
    print("That is not a valid number of miles")

【讨论】:

  • “e”代表什么?
  • e 是异常的一个实例
  • 我正盯着一个满是我看不懂的代码的屏幕。 :( Value Error 是什么?Miles = None 的意义何在?抱歉浪费您的时间!
【解决方案3】:

如果输入无效,则会执行 except 语句,但您的脚本会继续执行。你有几个选择。您可以使用 sys.exit() 告诉 python 退出应用程序,或者您可以实现一些其他行为,例如告诉用户重试或默认为某个硬编码值。

像这样使用退出:

import sys

try:
    miles = float(input("How many miles can you walk? "))
except Exception, e:
    print("That is not a valid number of miles")
    sys.exit()

或者您可以要求用户再试一次:

miles = None
def ask():
    global miles
    try:
        miles = float(input("How many miles can you walk? "))
    except: 
        print("Invalid input, try again")
        ask()

ask()
# remaining code here

【讨论】:

  • 这么难 - jeremyne​​albrown 或 jramirez 作为公认的答案?如果我选择你们中的一个,另一个不会对我满意!
  • 考虑您的最终用户。他们是否会理解异常或友好消息的输出以及刚刚关闭的应用程序?
  • 无需抱歉。所有的答案都非常相似。这几乎可以归结为品味问题。希望你喜欢学习 Python!
  • 确实是非常礼貌的评论。感谢您的合作。
猜你喜欢
  • 2019-06-26
  • 1970-01-01
  • 2018-03-19
  • 2013-11-21
  • 1970-01-01
  • 2011-04-25
  • 2021-07-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多