只想检查一下这是什么答案。这是我的考试问题之一,我被告知我的课程不正确(我应该使用"否则"而不是" elif"。你们有什么想法?
问题:根据流程图编程。 https://ibb.co/kxe4N5
我的回答:
price = input("What is the item price?: $")
ship = input("Choose your shipping method(Normal/Express): ")
price = int(price)
if (price < 100):
if (ship == 'Normal'):
checkout = 1.1 * price
elif(ship == 'Express'):
checkout = 1.2 * price
else:
if(ship == 'Normal'):
checkout = price
elif(ship == 'Express'):
checkout = 1.04 * price
print("The checkout amount is: $" + str(checkout))
答案 0 :(得分:0)
由于你只有两个可能的值,如果第一个为假而第二个必须为真,那么为什么else
稍微好于elif
(因为后者你需要检查)另一个条件)即使它们产生相同的结果。
编辑:在输入分支之前验证输入是一个好习惯,这样您就可以确保ship
变量包含两个允许值中的一个。
答案 1 :(得分:0)
回答您的问题:为什么else
代替elif
。在这种情况下,您没有其他选择,因此else
语句是合适的。另外,查看你的图表,检查是在 Normal 方法上,它不是这样的:它是正常的还是表达的,但它是正常的。
但这意味着您已正确检查输入。
所以你的答案是正确的,因为如果出现错误的参数会引发错误。但是如果没有检查和else
语句,则不会检测到错误。如果有两个else
,那么您可以使用1.04结帐。
另外,我会有一些评论:
您不测试输入是否有效。 (您可以为此添加while
循环),
转换不应为int()
,而应为float()
,否则您将价格向下舍入,
dict
,而不是写同一行4次,list
。支票上有这样的东西(我只是给出一些指示):
while 'shipping method is not Normal nor Express':
ship = input("Choose your shipping method(Normal/Express): ")
if ship in ['Normal', 'Express']:
break
else:
print('{} is not an available shipping method'.format(ship))
列表:
coeff = [1.1, 1.2, 1, 1.04]
...
checkout = price * coeff[idx]
答案 2 :(得分:0)
下面的代码段应该可行。建议不要使用elif,因为它只有一张支票。但是,我们都是学生,我们最终会学到更好的东西。检查以下代码,仅限于否则。
item_price = 200
shipping_method = 'express'
checkout_amount = 0
if item_price < 100:
checkout_amount = 1.1 * item_price if shipping_method == 'normal' else 1.2 * item_price
else:
checkout_amount = item_price if shipping_method == 'normal' else 1.04 * item_price
print("checkout_amount = {}".format(checkout_amount))
答案 3 :(得分:0)
在共享示例中,使用简单的“if”和“else”足以实现目标。 'if'和'elif'最适合需要'C'或unix中典型'case'语句的情况(在python中不可用)
请看下面给出的实施:
def displayCheckOutAmmount(item_price, shipping_method):
def calculateItemPrice(n=1.1, nn=1.2): return n*item_price if shipping_method=='normal' else item_price*nn
return calculateItemPrice( n=1.1, nn=1.2) if item_price < 100 else calculateItemPrice( n=1, nn=1.04)
In [52]: displayCheckOutAmmount(80, "normal")
Out[52]: 88.0
In [53]: displayCheckOutAmmount(80, "normal1")
Out[53]: 96.0