python - 在我尝试打印在 python 中的 if 语句中创建的变量后,我的代码中出现名称错误
问题描述
Python程序来计算发送包裹的成本。
以下程序在尝试打印总成本时出现名称错误:
price_of_parcel = float(input(" enter the price of parcel in rands (R) : R "))
total_distance = float(input(" enter the total distance to the parcel destination in (km): km "))
parcel_route = input(" do you want it by Air or Freight? (Air / Freight): ").strip().lower()
parcel_insurance = input(" do u want full insurance or limited insurance? ( Full / Limited) : ").strip().lower()
parcel_nature = input(" do you want parcel as gift or as no gift? (Gift / No Gift) : ").strip().lower()
parcel_urgency = input( " do you want a standard or priority delivery? ( Priority / Standadard ) : ").strip().lower()
if parcel_route == "Air" :
p_route = total_distance * 0.36
totalcost = p_route
if parcel_route == " freight " :
p_route = total_distance * 0.25
totalcost = p_route
if parcel_insurance == " full " :
p_insurance = 50.00
totalcost = p_route + p_insurance
if parcel_insurance == " limited " :
p_insurance = 25.00
totalcost = p_route + p_insurance
if parcel_nature == " gift" :
p_gift = 15.00
totalcost = p_route + p_insurance + p_gift
if parcel_nature == " no gift " :
p_gift = 0
totalcost = p_route + p_insurance + p_gift
if parcel_urgency == " Priority" :
urgency = 50.00
totalcost = p_route + p_insurance + p_gift + urgency
if parcel_urgency == " standard " :
urgency = 20.00
totalcost = p_route + p_insurance + p_gift + urgency
if parcel_route == "air" and (parcel_insurance == " full" or "limited") and (parcel_nature == "gift" or "no gift") and (parcel_urgency == "priority" or "standard"):
totalcost = totalcost = p_route + p_insurance + p_gift + urgency
print( " the total cost for the parcel is : " + str(totalcost))
else:
if parcel_route == "freight" and (parcel_insurance == " full" or "limited") and (parcel_nature == "gift" or "no gift") and (parcel_urgency == "priority" or "standard"):
totalcost = p_route + p_insurance + p_gift + urgency
print( " the total cost for the parcel is : " + str( totalcost))
名称错误表明在 if 语句中创建的变量未定义。
我尝试了一些东西,但代码似乎不起作用。
解决方案
你的虫子在这里-
parcel_route = input(" do you want it by Air or Freight? (Air / Freight): ").strip().lower()
parcel_route
是一个小写的字符串,没有尾随或前导空格。因为你用过strip() and lower()
但是,在您的if
条款中,您也有大写字母和空格!
if parcel_route == "Air" :
p_route = total_distance * 0.36
totalcost = p_route
if parcel_route == " freight " :
p_route = total_distance * 0.25
totalcost = p_route
结果,这两个if
块都没有被执行,并且你的p_route
变量永远不会被设置!
推荐阅读
- prolog - CHR:如何在规则中调用 Prolog 代码
- wordpress - wp_get_nav_menu_items 多级子菜单
- javascript - jquery 仅扩展多个具有相似名称的 textarea 中的一个 textarea
- c# - 使用ajax将值从MVC视图传递到控制器
- google-apps-script - 将数据从一个工作簿过滤到另一个工作簿和 Google 表格中第二个工作簿中的工作表
- maven - Maven 编译器插件 - 将参数发送到 javac(类路径或 cp)
- ms-access - 如何关闭特定字段的正确大小写更正?
- python - 使用 tkinter 和 schedule 模块制作“屏幕储物柜”
- c - 在 C 头文件原型中捕获缺少的分号
- reactjs - 设置了 headers 和 axios 但是为什么会发生 cros 错误?