繁体   English   中英

为什么在我编写然后在执行简单计算的 python 中使用 if 语句打印时没有显示任何内容?

[英]Why do I get none displayed when I write and then print using if statement in python that does simple computation?

尝试编写一个函数,根据产品的重量计算运输产品的地面成本。

def ground_cost(weight):
  if weight<=2:
    price= 1.5*weight + 20
  elif  (weight>2) and (weight<=6):
    price=3*weight + 20
  elif (weight>6) and (weight<=10):
    price=4*weight + 20
  else:
    price=4.7*weight + 20
    return price

print(ground_cost(8.4))

我使用简单的 if 和 elif 语句来执行此操作,但每次都显示 NONE。

我预计输出为 53.6,但没有显示。

您的 return 语句嵌入在最后的else子句中,它需要与您的初始if缩进相同。 在您的代码示例中,这永远不会达到,因此该函数返回None的默认值,因为没有遇到 return 语句。

正确缩进 return 语句:

def ground_cost(weight):
  if weight<=2:
    price= 1.5*weight + 20
  elif  (weight>2) and (weight<=6):
    price=3*weight + 20
  elif (weight>6) and (weight<=10):
    price=4*weight + 20
  else:
    price=4.7*weight + 20
  return price

print(ground_cost(8.4))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM