首页 > 解决方案 > 在我尝试打印在 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 语句中创建的变量未定义。

我尝试了一些东西,但代码似乎不起作用。

标签: python

解决方案


你的虫子在这里-

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变量永远不会被设置!


推荐阅读