使用if / else语句计算价格

时间:2014-06-10 17:08:00

标签: python python-2.7

我写的功能......

def calculate_price(Thickness, Width, Price, Timbmet):
    foo = Thickness * Width;
    bar = foo * Price;
    if Timbmet == "n" or "N":
        foobar = ((bar / 100) * 15) + 100
        print foobar
    else:
        print bar



calculate_price(5., 4., 3., "y");

控制台输出为109,这是错误的,因为它不应该在if语句中执行代码,因为Timbmet参数与“n”或“N”不匹配。我做错了什么,为什么代码没有运行else部分?

2 个答案:

答案 0 :(得分:1)

将条件更改为 -

if Timbet in ["n", "N"]:

编程不像自然语言那样......

答案 1 :(得分:0)

条件Timbmet == "n" or "N"始终返回True,因为第二个子表达式"N"始终为True。您需要检查Timbet是否在列表/集合中:

if Timbet in ("n", "N"):
if Timbet in {"n", "N"}:  # even better but more confusing if we are not aware of the set construction syntax

...或在没有区分大小写的情况下进行检查:

if Timbet.lower() == "n":