【问题标题】:Code runs on command prompt but not on hydrogen代码在命令提示符下运行,但不在氢气上
【发布时间】:2020-11-23 18:32:14
【问题描述】:

我刚刚开始使用 Internet 上提供的信息进行编程(python3)。现在我正在学习如何使用 try/except。我的问题是我编写的代码在 Windows 10 的命令提示符下运行良好,但在抛出错误的 shell(Atom/Hydrogen)中运行良好(第 6 行,NameError),因为我没有定义变量“fish” ,我知道通常情况相反,但我只是想了解我是否犯了错误。代码如下:

>try:
>>    fish = int (input("please enter your age "))
>except:
>>    print("That's not a number ")
>>    exit(0)
>if fish <= 15:
>>    parentLicense = input ("have one of your parents have a license? (yes/no) ")
>>    if parentLicense == "yes":
>>>        print ("You can fish")
>>    else:
>>>        print("So sad, you or one of your parents need a license")

【问题讨论】:

    标签: python-3.x command-prompt try-except hydrogen


    【解决方案1】:

    嗨,Chiron,欢迎来到社区。您收到未定义错误的原因是因为在 try 语句中的某些情况下 fish 可能是未定义的。 你应该使用

    try:
        # try stuff
    except ValueError:
        # do stuff when theres an error
    else:
        # stuff if try stuff works
    

    else 只有在没有引发异常时才会被调用。我会避免使用bare except,因为它会导致问题并且不是好的做法。

    【讨论】:

    • 感谢您的回答和欢迎。关于没有规范的“除外”的建议非常有用,我不知道这不是一个好习惯,我发现它对输入语句很有用,特别是在为了避免python的默认错误信息。
    • @Chiron 不客气,如果答案有助于解决问题,请接受它作为答案:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-27
    相关资源
    最近更新 更多