分享
三行代码  ›  专栏  ›  技术社区  ›  Jake Arthur

无法在python 3中触发elif/else条件

  •  0
  • Jake Arthur  · 技术社区  · 5 天前

    我有一个程序,对以下部分有问题:

    device = input("Is the device a pump/compressor or a turbine: ")
    
    
    Work_pump = mdot*(hout-hin)
    Work_turbine = mdot*(hin-hout)
    
    if device == "pump" or "compressor":
        print("Pump/compressor work rate =  ",Work_pump/1000," kW")  # significant figures should be addressed
    elif device == "turbine":
        print("Turbine work rate = ",Work_turbine/1000," kW")
    else:
       print("Device invalid, input in lower case")
    

    我无法触发elif和else语句,即使 device == "turbine"

    3 回复  |  直到 5 天前
        1
  •  1
  •   Tabulate    5 天前

    这只是个小问题。改变

    if device == "pump" or "compressor":
    

    if device == "pump" or device == "compressor":
    

    如果你不想处理资本化问题,你可以使用 device.lower()

    if device.lower() == "pump" or device.lower() == "compressor"
    
        2
  •  0
  •   yoskovia Giorgos Kavalieratos    5 天前
    if device == "pump" or device == "compressor":
        # significant figures should be addressed
        print("Pump/compressor work rate =  ",Work_pump/1000," kW")  
    elif device == "turbine":
        print("Turbine work rate = ",Work_turbine/1000," kW")
    else:
       print("Device invalid, input in lower case")
    

    是正确的代码。

        3
  •  0
  •   Ann Zen    5 天前

    你犯了个小错误:

    if device == "pump" or "compressor":
        print("Pump/compressor work rate =  ",Work_pump/1000," kW")  # significant figures should be addressed
    

    if device == "pump" or device == "compressor":
        print("Pump/compressor work rate =  ",Work_pump/1000," kW")  # significant figures should be addressed
    
        4
  •  0
  •   sabik    5 天前

    if device in ("pump", "compressor"):
        print("Pump/compressor work rate =  ",Work_pump/1000," kW")  # significant figures should be addressed
    

    如果不同设备类型的数目越来越大,这一点尤其方便;您可以使用预定义的常量,这样您就不会一遍又一遍地重复相同的列表:

    if device in DEVICES_PUMP_GROUP:
        ...
    elif device in DEVICES_TURBINE_GROUP:
        ...