2016-09-21 75 views
0

我正在开发一个小程序,用户输入一个价格,然后程序会根据输入输出运输成本。根据用户输入选择正确的else语句

#Initilaize variables 

lowUS = 6.00; 
medUS = 9.00; 
highUS = 12.00; 
lowCan = 8.00; 
medCan = 12.00; 
highCan = 15.00; 

#Greet user and ask for input 
print("Welcome to Ben's shipping calculator!"); 
print("We will calculate your shipping cost for you!"); 


orderTotal = float(input("Please input your total amount.")); 
country = input("In which country do you reside? Please type C for Canada or U or USA. "); 

#Validate input 
while country not in {'u', 'c', 'C', 'U'}: 
    print ("Invalid input. Please try again. ") 
    country = input("In which country do you reside? Please type C for Canada or U or USA. "); 

#Determine how much the shipping fee is 
if country == 'U' or country == 'u': 
    if orderTotal <= 50.00: 
     if orderTotal > 50.00 and orderTotal <= 100.00: 
      if orderTotal > 100.00 and orderTotal <= 150.00: 
       if orderTotal > 150.00: 
        print("Your shipping is free and your grand total is", orderTotal) 
       else: 
        print("Your shipping fee is: ", highUS); 
        orderTotal = (orderTotal + highUS); 
      else: 
       print("Your shipping fee is: ", medUS); 
       orderTotal = (orderTotal + medUS); 
     else: 
      print("Your shipping fee is: ", lowUS); 
      orderTotal = (orderTotal + lowUS); 

elif country == 'c' or country == 'C': 
    if orderTotal <= 50.00: 
     if orderTotal > 50.00 and orderTotal <= 100.00: 
      if orderTotal > 100.00 and orderTotal <= 150.00: 
       if orderTotal > 150.00: 
        print("Your shipping is free and your grand total is", orderTotal) 
       else: 
        print("Your shipping fee is: ", highCan); 
        orderTotal = (orderTotal + highCan); 
      else: 
       print("Your shipping fee is: ", medCan); 
       orderTotal = (orderTotal + medCan); 
     else: 
      print("Your shipping fee is: ", lowCan); 
      orderTotal = (orderTotal + lowCan); 

print("Your grand total is: $", orderTotal); 

我很新的蟒蛇和编程,我不知道这是去它的好方法,但我学习if-else语句,所以我想我会试试看。到目前为止,只有当您输入金额为“50”时才有效。它将根据国家计算仅为“50”。我不确定我出错的地方,如果有人能帮忙解释,那会很好。

+0

你的第一个'if'只有在它小于或等于50时才进入......你做的下一个检查是如果它大于50,那么它将不会执行......因此, 'else'子句是唯一可以执行的子句... –

+0

Python除了换行符外没有行结束符 - 这些分号完全没有必要。这不是C! (或Java,或JavaScript,或其他任何东西) – MattDMo

回答

1

你的第一个if只有在它小于或等于50时才会进入下一个检查是否它大于50它不能被执行...所以你的else子句是唯一可以执行的语句......基本上,嵌套的if语句不会执行,因为这样做的条件已从排除的if中排除。

你最好的重组逻辑:

if orderTotal > 150: 
    # do something 
elif orderTotal > 100: 
    # do something 
elif orderTotal > 50: 
    # do something 
else: # 50 or under... 
    # do something else 
+0

好吧,我现在看到了这个错误,我实际上正在考虑这样做,但并非100%确定它是否正确。谢谢! – legendaryxv2

0

您的逻辑是有点扭曲。如果量< = $ 50时,那么它是不是> $ 50或< = $ 100所以任何下面是嵌套“如果”永远不会执行:

if orderTotal <= 50.00: 
    if orderTotal > 50.00 and orderTotal <= 100.00: 
     # ** this will never run ** 
    else: 
     # This will run, if orderTotal <= 50.00 

什么都不会发生,如果orderTotal > 50.00,因为没有elseif orderTotal <= 50.00测试。 @Jon Clements的答案显示了构建代码的正确方法。