写了一段代码,请师兄师姐帮看下,给些建议或更简单的方法
提示用户输入:1.重量; 2.地点编号
快递费算法:
首重:3公斤
3公斤以内: 东三省/宁夏/青海/海南 12元 新疆/西藏:20元 港澳台/国外:不接受寄件 其他:10元
超过3公斤部分:东三省/宁夏/青海/海南 每公斤10元 新疆/西藏:每公斤20元 港澳台/国外:联系总公司 其他:每公斤5元
用户输入重量和地点编号后显示快递费金额。
代码如下:
nqh=1001
name1=”东三省/宁夏/青海/海南”
xinxi=1002
name2=”新疆/西藏”
gangaotai=0000
name3=”港澳台/国外”
athon=1111
name4=”非偏远地区”
num=int(input(“请输入地点编号:”))
if num==nqh:
weight=float(input(“请输入快递重量(公斤):”))
if weight<=3:
print(“发往:”,name1,”,运费:”,weight12,”元!”)
else:
print(“发往:”,name1,”,运费:”,312+(weight-3)*10,”元!”)
elif num==xinxi:
weight=float(input(“请输入快递重量(公斤):”))
if weight<=3:
print(“发往:”,name2,”,运费:”,weight20,”元!”)
else:
print(“发往:”,name2,”,运费:”,320+(weight-3)*20,”元!”)
elif num==athon:
weight=float(input(“请输入快递重量(公斤):”))
if weight<=3:
print(“发往:”,name4,”,运费:”,weight10,”元!”)
else:
print(“发往:”,name4,”,运费:”,310+(weight-3)*5,”元!”)
else:
print(“不接受寄件!”)
不知是否规范或有没有更简单的方式?
建议:
改进后的代码如下:
locations = {1001: '东三省 / 宁夏 / 青海 / 海南', 1002: '新疆 / 西藏', 1111: '非偏远地区'}
def calculate_fee(weight, location): if location == 1001: if weight <= 3: return weight * 12 else: return 36 + (weight - 3) * 10 elif location == 1002: if weight <= 3: return weight * 20 else: return 60 + (weight - 3) * 20 elif location == 1111: if weight <= 3: return weight * 10 else: return 30 + (weight - 3) * 5 else: return None
location = int(input("请输入地点编号: ")) if location in locations: weight = float(input("请输入快递重量(公斤): ")) fee = calculate_fee(weight, location) if fee is not None: print("发往:", locations[location], ",运费:", fee, "元!") else: print("不接受寄件!") else: print("不接受寄件!")
来自ChatGPT