【问题标题】:TypeError unsupported Operand type(s) for %: Float and NoneTypeTypeError 不支持 % 的操作数类型:Float 和 NoneType
【发布时间】:2014-03-28 04:02:11
【问题描述】:

很抱歉用一个菜鸟问题打扰您,但我是 Python 新手。基本上这是一个家庭作业,我无法理解我做错了什么。我想我拥有我需要的一切,但我不断收到类型错误。任何帮助表示赞赏。谢谢!

def Main():
    Weight = float(input ("How much does your package weigh? :"))
    CalcShipping(Weight)

def CalcShipping(Weight):

    if Weight>=2:
        PricePerPound=1.10

    elif Weight>=2 & Weight<6:
        PricePerPound=2.20

    elif Weight>=6 & Weight<10:
        PricePerPound=float(3.70)

    else:
        PricePerPound=3.8

    print ("The total shipping cost will be $%.2f") % (PricePerPound) 


Main()

【问题讨论】:

  • @MartijnPieters 我认为你的意思是“按位”。
  • @SilasRay 你可能忽略了not
  • 我假设这是 Python 3 代码,对吧?
  • 在我的一个关于布尔运算的问题上令人尴尬的误读,它会出现...... :)
  • 它们都是布尔值,但一个是逻辑的,另一个是按位的。

标签: python typeerror nonetype


【解决方案1】:

print() 函数返回None;您可能想将% 操作移到函数调用中:

print ("The total shipping cost will be $%.2f" % PricePerPound) 

请注意,您的 if 测试使用的是 bitwise and operator &amp;;您可能想改用 and,使用布尔逻辑:

elif Weight >= 2 and  Weight < 6:
    PricePerPound = 2.20

elif Weight >= 6 and Weight < 10:
    PricePerPound = 3.70

或者,使用比较链:

elif 2 <= Weight < 6:
    PricePerPound = 2.20

elif 6 <= Weight < 10:
    PricePerPound = 3.70

查看您的测试,您太早测试Weight &gt;= 2;如果 Weight 介于 2 和 6 之间,您将匹配第一个 if 并完全忽略其他语句。我想你想要:

PricePerPound = 1.10

if 2 <= Weight < 6:
    PricePerPound = 2.20

elif 6 <= Weight < 10:
    PricePerPound = 3.70

elif Weight >= 10:
    PricePerPound = 3.8

例如价格是1.10,除非您的包裹重量为2或更多,之后价格逐渐上涨。

【讨论】:

    猜你喜欢
    • 2017-06-06
    • 2018-06-20
    • 1970-01-01
    • 1970-01-01
    • 2014-05-10
    • 1970-01-01
    • 2020-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多