【问题标题】:Simple Python Temp Script简单的 Python 临时脚本
【发布时间】:2018-03-04 08:07:17
【问题描述】:

我编写了一个非常简单的临时脚本,它会提示用户输入并给出答案。如下所示,我提示用户输入 1,2 或 3。1 是 fah 到 cel,2 是 cel 到 feh,3 是退出程序。如果用户输入 1 或 2,另一个提示将要求他们输入他们想要转换的度数。此条目保存在变量中:

scale

我编写的函数应该将浮点数计算为正确的转换,并在打印正确的温度后循环回到主菜单。 try/except 语句中有一些逻辑会尝试将此输入转换为浮点数,如果不能,它将打印一个讨厌的 gram。当我运行这段代码时,一切似乎都运行良好,直到调用 fahtoCel 函数:

fc = fahtoCel(scale)

我很确定我的所有缩进都是正确的,并且研​​究了声明函数并在脚本中调用它们。我唯一的怀疑是我的函数调用在我的 try/except 语句中,也许范围不正确?我的代码:

def fahtoCel(number):
    return(number - 32.0) * (5.0/9.0)

while True:
    x = raw_input("""Please enter 1,2 or 3: """)
    if x == "3":
        exit(0)
    if x == "1":
        scale = raw_input("""Enter degrees in Fah: """)
        try:
            scale = float(scale)
            fc = fahtoCel(scale)
        except:
            print("Invalid Entry")
        continue
    print("%.2f degrees fah equals %.2f degrees Cel" % (scale, fc))
    if x == "2":
    #Do the same for cel to fah#

【问题讨论】:

  • 那么,您实际得到的错误是什么?您应该发布回溯。
  • 代码按预期工作。您没有得到任何输出,但是您不会尝试打印fc 的值,因为您调用continue 会导致您的print 调用被跳过。

标签: python function scope temp


【解决方案1】:

continue 将执行转移到while 循环的开头,因此无论try 语句的结果如何,您都永远不会到达print 语句。您需要进一步缩进:

try:
    scale = float(scale)
    fc = fahtoCel(scale)
except Exception:  # Don't use bare except! You don't want to catch KeyboardInterrupt, for example
    print("Invalid entry")
    continue
print("%.2f degrees fah equals %.2f degrees Cel" % (scale, fc))

不过,确实,您的try 声明过于宽泛。您应该担心捕获的唯一例外是float 可能引发的ValueError

try:
    scale = float(scale)
except ValueError:
    print("Invalid entry")
    continue
fc = fahtoCel(scale)
print("%.2f degrees fah equals %.2f degrees Cel" % (scale, fc))

【讨论】:

  • 好吧,我确实把缩进搞砸了!感谢您的反馈!在我进一步缩进之后,我能够得到正确的输出。如果用户不小心按下回车键而不是输入有效数字,ValueError 会捕获吗?
  • 是的;一个空字符串只是一个无效的浮点文字。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多