我有问题,让这个后续计划工作,因为我想它。我有一个步骤让我困扰,我会很快地回顾一下什么是第一步。
程序采用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)
如果单位是
mbar
,但值是浮点值,则此检查也将是False
:这就是为什么你会收到“不是一个可接受的单位”的信息。您需要分别检查这两件事:值是整数(yes/no)还是单位有效(yes/no)。如果两者都是这样,则可以打印成功消息。否则,您将需要独立打印一条或两条失败消息。你知道吗
您应该对
except
子句使用else
,只有在int(pressure)
正确运行时,它才会运行。此外,不要更改变量的类型;这很混乱:相关问题 更多 >
编程相关推荐