首页 > 解决方案 > 使用 if elif 和 else 打印不同的语句

问题描述

我在 thonny 中创建了一个代码,它需要 3 个输入来确定商品的价格。如果价格符合特定要求并且只有一个折扣符合条件,我还希望能够提供折扣并打印折扣结果。如果没有折扣符合条件,我只想打印商品的价格。

请在我尝试过的下面查看我的代码

if sqFt > BIG_DESK:
    if wood == 'oak' or wood == 'mahog':
        discount = DISC_1
        discAmnt = discount * price
        discPrice = price - discAmnt

elif wood == 'oak' or drawers > DISC_DRAWER:
    discount = DISC_2
    discAmnt = discount * price
    discPrice = price - discAmnt

elif price > DISC_PRICE:
    discount = DISC_3
    discAmnt = discount * price
    discPrice = price - discAmnt

print("\nThe price of the desk is $", format(price,',.2f'))
print("\nThe discounted price is $", format(discPrice,',.2f'))
print("\nYou qualified for a", format(discount,'.0%'),"and saved",format(discAmnt,',.2f'))


else:
    print("\nThe price of the desk is $", format(price,',.2f'))

如前所述,如果可以应用折扣,我希望它打印价格、价格减去折扣以及折扣和折扣金额。

我在带有错误语句的 else 语句中不断收到错误SyntaxError: invalid syntax

标签: pythonif-statement

解决方案


你有一个简单的缩进错误;在print最后elif一个被突出的之后终止整个if块。

根据您希望代码实际执行的操作,可以缩进 theprint使其成为 的一部分elif,或者将 the 放在else其他print语句之前。如果else应该控制是否在其他打印后打印某些内容,请创建一个控制第二个if / else块的变量,可能像这样:

eligible = True

if sqFt > BIG_DESK:
    if wood in ['oak', 'mahog']:   # notice also "in" operator
        discount = DISC_1
        discAmnt = discount * price
        discPrice = price - discAmnt
elif wood == 'oak' or drawers > DISC_DRAWER:
    discount = DISC_2
    discAmnt = discount * price
    discPrice = price - discAmnt
elif price > DISC_PRICE:
    discount = DISC_3
    discAmnt = discount * price
    discPrice = price - discAmnt
else:
    eligible = False

print("The price of the desk is $", format(price,',.2f'))
if eligible:
    print("The discounted price is $", format(discPrice,',.2f'))
    print("You qualified for a", format(discount,'.0%'),"and saved",format(discAmnt,',.2f'))


推荐阅读