发生这种情况是因为您的程序执行elif clothes_total > 150
在它甚至考虑elif clothes_total > 200
. 下面是 if 语句的工作原理:
这:
if condition1:
do thing1
elif condition2:
do thing2
elif condition2:
do thing3
与此相同:
if condition1:
do thing1
else:
if condition2:
do thing2
else:
if condition2:
do thing3
如果你想执行里面的和里面的东西if clothes_total > 150
,if clothes_total > 200
有四个选项:
选项1(只需将所有内容从一个添加到另一个):
if clothes_total < 150:
print "<h4> TOTAL : %s </h4>" % tot_price
elif 150 < clothes_total < 200: # define a maximum as well
print "15% Discount: $"
print clothes_total * 0.85
print "<h4> FIFTEEN: $ %s </h4>" % tot_price1
print "15% Discount + $30 off: $"
print 0.85 * (clothes_total - 30)
print "<h4> THIRTY: $ %s </h4>" % tot_price2
elif clothes_total > 200:
print "15% Discount + $30 off: $"
print 0.85 * (clothes_total - 30)
print "<h4> THIRTY: $ %s </h4>" % tot_price2
选项 2(嵌套 if 语句):
if clothes_total < 150:
print "<h4> TOTAL : %s </h4>" % tot_price
elif 150 < clothes_total:
print "15% Discount: $"
print clothes_total * 0.85
print "<h4> FIFTEEN: $ %s </h4>" % tot_price1
if clothes_total > 200:
print "15% Discount + $30 off: $"
print 0.85 * (clothes_total - 30)
print "<h4> THIRTY: $ %s </h4>" % tot_price2
elif clothes_total > 200:
print "15% Discount + $30 off: $"
print 0.85 * (clothes_total - 30)
print "<h4> THIRTY: $ %s </h4>" % tot_price2
选项 3(不else
,只是if
s):
if clothes_total < 150:
print "<h4> TOTAL : %s </h4>" % tot_price
if 150 < clothes_total
print "15% Discount: $"
print clothes_total * 0.85
print "<h4> FIFTEEN: $ %s </h4>" % tot_price1
if clothes_total > 200:
print "15% Discount + $30 off: $"
print 0.85 * (clothes_total - 30)
print "<h4> THIRTY: $ %s </h4>" % tot_price2
这将执行最后两个if
块,这可能不是您想要的。但是请注意,在执行所有这些 if 语句的条件时,您会在运行时失败,尤其是在它们是复杂条件的情况下
选项 4(范围条件):
if clothes_total < 150:
print "<h4> TOTAL : %s </h4>" % tot_price
elif 150 < clothes_total < 200: # define the bounds of the range of acceptable values
print "15% Discount: $"
print clothes_total * 0.85
print "<h4> FIFTEEN: $ %s </h4>" % tot_price1
elif clothes_total > 200:
print "15% Discount + $30 off: $"
print 0.85 * (clothes_total - 30)
print "<h4> THIRTY: $ %s </h4>" % tot_price2
这使您可以缩短所需的 if 语句,并保证在任何给定时间只输入一个块。
希望这可以帮助