我正在尝试制作代码,以便书籍数量决定每个语句的用法。因此,如果我写20,预期的答案应该是95,而不是100。这意味着elif被忽略,并且只执行if语句(除了负的elif语句)。如何重写代码,使其不会忽略Book> 10和书> 20个elif陈述?
try:
book = raw_input('Enter amount of Books:\n')
Book = int(book)
red = Book - 10
if Book > 0:
print int(book) * 5
elif Book > 10:
print (red * 4.5) + (10 * 5)
elif Book < 0:
print ('Amount cannot be negative.')
elif Book > 20:
print (10 * 5) + (10 * 4.5) + (int(book) - 20 ) * 4
else:
print ('There has been a mistake. Please restart.')
except:
print ('Error.')
答案 0 :(得分:2)
elif语句意味着,如果,这意味着仅在第一个语句错误时评估语句,在您的情况下if book>0
为真且结果为100:其他条件未被评估。
你只需要修改你的条件顺序,也要注意你的缩进:
try:
book = raw_input('Enter amount of Books:\n')
Book = int(book)
red = Book - 10
if Book > 20:
print (10 * 5) + (10 * 4.5) + (int(book) - 20 ) * 4
elif Book > 10:
print (red * 4.5) + (10 * 5)
elif Book > 0:
print int(book) * 5
elif Book < 0:
print ('Amount cannot be negative.')
else:
print ('There has been a mistake. Please restart.')
except:
print ('Error.')
答案 1 :(得分:1)
您的第一个if语句将始终捕获n > 10
和n > 20
的情况。因此,您的条件应以基本情况开始;一个不容易实现的,例如:
if Book < 0:
print ('Amount cannot be negative.')
继续向前查看将首先捕获的案例,因为条件的顺序在您的案例中很重要,因为它们不是互斥的,即n > 20
。因此代码看起来如下所示:
if Book < 0:
print ('Amount cannot be negative.')
elif Book > 20:
print (10 * 5) + (10 * 4.5) + (int(book) - 20 ) * 4
elif Book > 10:
print (red * 4.5) + (10 * 5)
elif Book > 0:
print int(book) * 5
else:
print ('There has been a mistake. Please restart.')
答案 2 :(得分:0)
try:
book = raw_input('Enter amount of Books:\n')
Book = int(book)
red = Book - 10
if Book < 0:
print ('Amount cannot be negative.')
else:
if Book > 20:
print 50 + 45 + (Book - 20) * 4
elif Book > 10:
print (red * 4.5) + (10 * 5)
elif Book > 0:
print Book * 5
else:
print ('There has been a mistake. Please restart.')
except:
print ('Error.')
答案 3 :(得分:0)
尝试尽可能消除边缘情况。
放"/AUTOSAR/EcucDefs/Com/ComConfig/ComIPdu/ComIPduCancellationSupport"
涵盖所有大于10的值。范围:[10,)
因此,在此之后放置public String someMethod(String parm1, String parm2) {
final Function<String, Boolean> isValidString = parm -> parm.equals("Test") || parm.equals("Test2");
...
String parm1 = ...
if (parm1 != null && isValidString.apply(parm)) {
... do something
}
...
并不重要。
根据优先顺序陈述你的陈述。
Book > 10