# user input
num = int(input("Please enter engine size: "))
# calculations
if num <= 1000:
print("The motor tax for your vehicle is €150")
elif num >= 1001 <= 1200:
print("The motor tax for your vehicle is €175")
elif num >= 1201 <= 1400:
print("The motor tax for your vehicle is €200")
elif num >= 1401 <= 1600:
print("The motor tax for your vehicle is €250")
elif num >= 1601 <= 1800:
print("The motor tax for your vehicle is €300")
elif num >= 1801 <= 2000:
print("The motor tax for your vehicle is €350")
else:
print("The motor tax for your vehicle is €500")
我知道我在这里可能犯了一个愚蠢的错误,我只是希望有人可以指出我正确的方向。
我正在尝试让python为每个指定的引擎尺寸打印相应的数量。
每次运行它的金额大于1000
时,它只会给我输出€175
。
非常感谢!
答案 0 :(得分:0)
这不是您想要的或期望的:
elif num >= 1001 <= 1200:
您应将其替换为:
elif num in range(1001, 1201):
注意:要检查<=
,您需要将范围的上限增加1 !!
否则,您可以将原来的内容写为:
elif 1001 <= num <= 1200:
答案 1 :(得分:0)
欢迎堆栈溢出!
我已将PL200的答案更新为您的问题的答案。这是一个改进您的代码的建议:
# Motor tax is based on ranges
if num <= 1000:
tax = 150
elif num <= 1200:
tax = 175
elif num <= 1400:
tax = 200
elif num <= 1600:
tax = 250
elif num <= 1800:
tax = 300
elif num <= 2000:
tax = 350
else:
tax = 500
print("The motor tax for your vehicle is €{}".format(tax))
由于if
/ elif
链,实际上不需要两个不等式。
或者您甚至可以避免长时间使用if / elif:
def get_tax(num):
"""Return the vehicle tax based on ranges"""
# Ranges are stored as "maximum size" / "tax"
tax_ranges = (
(1000, 150),
(1200, 175),
(1400, 200),
(1600, 250),
(1800, 300),
(2000, 350),
)
default_tax = 500
for max_size, tax in tax_ranges:
if num <= max_size:
return tax
return default_tax
num = int(input("Please enter engine size: "))
print(f"The motor tax for your vehicle is {get_tax(num)}")
注意:我在末尾添加了一个f-string
以进行打印,但是如果您的Python版本早于3.6,则您的Python版本可能不支持它。在这种情况下,只需将{get_tax(num)}
替换为"... {}".format(get_tax(num))
,然后删除字符串前的f