【发布时间】:2016-09-21 19:34:31
【问题描述】:
我正在开发一个小程序,用户输入价格,然后程序会根据输入输出运费。
#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);
我对 python 和编程非常陌生,我不确定这是否是一个好方法,但我正在学习 if-else 语句,所以我想我会尝试一下。到目前为止,它仅在您输入“50”作为金额时才有效。它将仅根据国家/地区计算“50”。我不确定我哪里出错了,如果有人可以帮助和解释,那就太好了。
【问题讨论】:
-
您的第一个
if仅在小于或等于 50 时输入...您进行的下一个检查是它是否大于 50,这是不可能的 - 这样该块将永远不会执行...所以您的else子句是唯一可以执行的子句... -
Python 除了换行符之外没有行终止符——那些分号是完全没有必要的。这不是C! (或 Java,或 JavaScript,或其他任何东西)
标签: python variables if-statement