在Python中实现try / except?

时间:2013-11-01 23:10:20

标签: python-3.x

我对此代码感到非常困惑:

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,但在查看文档之后,我不知道该怎么做以及如何使用代码中的所有其他ifs和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行,in     如果float(miles)&lt; = 0: NameError:名称'miles'未定义

我正在使用Python 3.3.2

3 个答案:

答案 0 :(得分:2)

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

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定义为输入。相反,它会打印“请输入...”,然后继续if

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

答案 1 :(得分:1)

可能发生的事情是你正在进入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")

答案 2 :(得分:0)

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

像这样使用退出:

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