Python嵌套ifelse只执行

2024-05-12 14:48:13 发布

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

我做这个练习,计算寄一个小包裹的费用。Te邮局对前300克收取R5,之后每100克收取R2(四舍五入),最高不超过1000克。你知道吗

weight = raw_input("What are the weight of you parcel: ")    

if weight <= 1000:
   if weight <= 300:
      cost = 5
     print("You parcel cost: " + cost)
   else:
      cost = 5 + 2 * round((weight - 300)/ 100)
      print("You parcel cost: " + cost)
else:
    print("Maximum weight for amall parcel exceeded.")
    print("Use large parcel service instead.")

当我执行空闲控制台时,我只执行最后的else语句。你知道吗


Tags: youinputrawifwhatelse费用r2
3条回答

weight在第1行变成string type,然后在if statement中比较weightint。通过将用户输入转换为int来修复此问题

将第一行更改为:

weight = int(raw_input("What are the weight of you parcel: "))

另外,如果您使用python3,我会将raw_input更改为input

weight强制转换为int,weight = int(weight)。现在它是一个字符串,与1000相比,它的计算结果总是False。你知道吗

首先,你有压痕问题。第二,比较字符串和int。然后,比较。。。你知道吗

>>> (350 - 300) / 100
0
>>> (350 - 300) / float(100)
0.5

你应该自己检查,但是round(0) = 0,和round(0.5) = 1。你知道吗


下面是解决问题的代码

weight = int(raw_input("What are the weight of you parcel: "))

if weight <= 1000:
  if weight <= 300:
    cost = 5
  else:
    cost = 5 + 2 * round((weight - 300) / float(100))
  print("Your parcel cost: {}".format(cost))
else:
  print("Maximum weight for small parcel exceeded.")
  print("Use large parcel service instead.")

相关问题 更多 >