python - 使用 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
解决方案
你有一个简单的缩进错误;在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'))
推荐阅读
- javascript - JavaScript 自上一个日期/时间以来经过的时间
- azure - 首次应用后未输出 Terraform Azure mac 地址
- sails.js - Remove Fields when query at sails js
- python - 位数递减的最小数
- java - Remove multiple elements with multiple indexes from arraylist in java
- php - cURL error 8: Invalid Content-Length: value
- ios - 如何在单击关闭按钮时从数组中删除数据
- javascript - Post request works in postman but not in javascript fetch function
- javascript - Is module.exports equal exports
- amazon-dynamodb - what is DynamoDB's replication type?