Python 3.4函数“error”outpu

2024-09-23 20:14:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有问题,让这个后续计划工作,因为我想它。我有一个步骤让我困扰,我会很快地回顾一下什么是第一步。
程序采用2个参数,pressure和unit,如果pressure是整数,单位是“pascal”、“torr”、“atm”或“mbar”,我希望它返回“pressure=”,pressure,unit。这很管用。如果我没有输入一个正确的单位,我希望函数打印“单位”不是一个可接受的单位”,这是可行的。

有问题的部分:当可变压力给定一个浮点数为35.2或字符串为“test”,但我给变量单位一个正确的单位,如毫巴,我得到输出

Enter an integer and a unit(seperated by ,): 3045.2,mbar '3045.2' is not an integer 'mbar' is not an accepted unit
显然,这不是我想要的工作,“mbar”是一个公认的单位。任何帮助都将不胜感激。编辑:我很新的编程整体所以请记住:X
我编写的程序:

pressure, unit = input("Enter an integer and a unit(seperated by ,): ").split(',')
def func(pressure, unit):
    try:
        pressure=int(pressure)
    except ValueError:
        print("'"+pressure+"'" + " is not an integer")
    if(isinstance(pressure,int) and (unit == "pascal" or unit == "mbar" or unit == "atm" or unit == "torr")):
        print("pressure =",pressure,unit)
    elif(unit != "pascal" or unit != "mbar" or unit != "atm" or unit != "torr"):
        print("'"+unit+"'" + " is not an accepted unit")
func(pressure, unit)

Tags: orand程序anisnotunit单位
2条回答

如果单位是mbar,但值是浮点值,则此检查也将是False

if(isinstance(pressure,int) and (unit == "pascal" or unit == "mbar" or unit == "atm" or unit == "torr")):

这就是为什么你会收到“不是一个可接受的单位”的信息。您需要分别检查这两件事:值是整数(yes/no)还是单位有效(yes/no)。如果两者都是这样,则可以打印成功消息。否则,您将需要独立打印一条或两条失败消息。你知道吗

您应该对except子句使用else,只有在int(pressure)正确运行时,它才会运行。此外,不要更改变量的类型;这很混乱:

def func(str_pressure, unit):
    try:
        pressure = int(str_pressure)
    except ValueError:
        print("'{}' is not an integer".format(str_pressure))
    else:
        # `pressure` is assigned
        if unit in {"pascal", "mbar", "atm", "torr"}:
            print("pressure = {} {}".format(pressure, unit))
        else:
            print("'{}' is not an accepted unit".format(unit))

pressure, unit = input("Enter an integer and a unit(seperated by ,): ").split(',')
func(pressure, unit)

相关问题 更多 >