变量没有在if语句中更新

时间:2018-06-10 12:47:01

标签: python python-3.x

price = input("How much: ") 
country = input("which country are you from :")
tax = 0
total = int(price) + (int(price)*(tax/100)) 


if country =="Canada" : 

   province = input("Which province? :")
   if province == "Alberta" :
       tax = 5
       print(total)
   elif province == "Ontario" : 
       tax = 13
       print(total)
   else : 
       tax = 11
       print(total)
else : 
     tax = 0
     print(total)

此代码不会更新税金,因此不会计算总税额。任何人都可以建议任何解决方案吗?

4 个答案:

答案 0 :(得分:4)

问题是您在将total更改为正确值之前计算tax。您可以通过移动计算来解决此问题,以便在设置tax后进行。

price = input("How much: ")
country = input("which country are you from :")
tax = 0

if country == "Canada":
    province = input("Which province? :")
    if province == "Alberta":
        tax = 5
    elif province == "Ontario":
        tax = 13
    else:
        tax = 11
else:
    tax = 0

total = int(price) + (int(price)*(tax/100))
print(total)

答案 1 :(得分:1)

嗯,问题是,您在使用total的if语句之前预先计算了tax = 0。这总是会返回相同的值。 每次更新税时都要尝试计算总数。 像这样:

tax = 5
total = int(price) + (int(price)*(tax/100)) 
print(total)

答案 2 :(得分:1)

看看这个简单的例子。我认为它可以帮助您“重新思考”您的数据结构。祝你好运!

taxes = {
    'Canada': {
        'Alberta': 5,
        'Ontario': 13,
        'default': 11
    }
}

def taxfunc(price, tax):
    return price + price*tax/100

price = int(input("How much: "))
country = input("which country are you from :").title()

if country in taxes:
    province = input("Which province? :").title()
    tax = taxfunc(price, taxes[country].get(province, taxes[country]['default']))
    print('Your tax is: {}'.format(tax))
else:
    print('no data')

答案 3 :(得分:0)

试试这个:获得tax后,然后计算total。在将值分配给total之前,您的代码问题是计算tax。您的total始终仅适用于tax = 0。但是将total计算移到底部将解决问题。

price = input("How much: ") 
country = input("which country are you from :")
tax = 0        

if country =="Canada" :     
   province = input("Which province? :")
   if province == "Alberta" :
       tax = 5
   elif province == "Ontario" : 
       tax = 13
   else : 
       tax = 11
else : 
   tax = 0

total = int(price) + (int(price)*(tax/100))
print(total)