我创建了一个程序,根据购买的图书数量应用折扣和运费。它运行正常,但是当我输入“0”或更少的零售价时,我没有返回错误消息“无效条目”。但是,输入零或更少的错误消息似乎正常运行。
discountRate = .4
first_BookShipping = 3
additional_Books= .75
costOfBook = input("Enter book retail price:" )
floatCostOfBook=float(costOfBook)
numberOfBooks = input("Enter number of books purchased from wholesaler: ")
intNumOfBooks=int(numberOfBooks)
bookDisc1 = floatCostOfBook*discountRate
bookDisc2 = floatCostOfBook*(intNumOfBooks-1)*discountRate
CostofFirstBook = floatCostOfBook-bookDisc1+first_BookShipping
CostofAddBooks = floatCostOfBook*(intNumOfBooks-1)-bookDisc2+additional_Books
def bookcost():
if intNumOfBooks == 1:
totalcost = CostofFirstBook
return round(totalcost, 2)
elif intNumOfBooks > 1:
totalcost = CostofFirstBook+CostofAddBooks
return round(totalcost, 2)
elif floatCostOfBook <= 0:
print("Invalid Entry")
elif intNumOfBooks < 1:
print("Invalid entry")
else:
print("Internal Error")
print("The total wholesale price of books purchased is {}: ".format(bookcost()))
代码上下文(改编自“Think Python”的第2章练习):
思考?此外,如果有人提出如何使我的代码更清洁或更有效地写这个的方法,我对批评不敏感。只要考虑到我是初学者编码器,所以我还没有内化一些方法。
答案 0 :(得分:2)
您需要将逻辑更改为
def bookcost():
### here ###
if floatCostOfBook <= 0:
print("Invalid Entry")
### end
elif intNumOfBooks == 1:
totalcost = CostofFirstBook
return round(totalcost, 2)
elif intNumOfBooks > 1:
totalcost = CostofFirstBook+CostofAddBooks
return round(totalcost, 2)
elif intNumOfBooks < 1:
print("Invalid entry")
else:
print("Internal Error")
首先检查floatCostOfBook
。
答案 1 :(得分:1)
检查是否应在计算或您在代码中执行的任何其他操作之前完成有效输入。 在这种情况下,在每次输入后检查是理想的。 这将解决代码中的错误并使代码更清晰。
所以你会选择类似的东西:
while True:
costOfBook = input("Enter book retail price:" )
floatCostOfBook = float(costOfBook)
if floatConstOfBook <= 0:
print("It should be greater than zero")
else:
break
答案 2 :(得分:1)
首先我建议使用all_lower_case_with_underscore变量名。
然后,由于python是动态类型的,我只是将cost_of_book转换为float而不是创建另一个变量。
然后,空间填充您的操作员。
然后你想要抛出一个实际的异常,你想要围绕你的输入值包装一个try块。当你得到输入时,最好处理它。
discount_rate = .4
first_book_shipping = 3
additional_books= .75
try:
cost_of_book = float(input("Enter book retail price:" ))
except(ValueError):
print("Oops! That was no valid number. Try again...")
else:
if cost_of_book <= 0:
raise ValueError("Please enter a cost greater than 0")
try:
number_of_books = int(input("Enter number of books purchased from
wholesaler: "))
except(ValueError):
print("Oops! That was no valid number. Try again...")
else:
if number_of_books <= 0:
raise ValueError("Please enter a number of books greater than 0")
#commutative property of multiplication saves some computing
book_disc_1 = cost_of_book * discount_rate
book_disc_2 = book_disc_1 * (num_of_books-1)
first_book_cost = cost_of_book - book_disc_1 + first_book_shipping
#try to keep lines at 79 char limit, using continuation with'\'
add_books_cost = cost_of_book * (num_of_books-1) - book_disc_2 \
+ additional_books
def bookcost():
if num_of_books == 1:
total_cost = cost_of_first_book
return round(total_cost, 2)
elif num_of_books > 1:
total_cost = cost_of_first_book + add_books_cost
return round(total_cost, 2)
total = bookcost()
print("The total wholesale price of books purchased is " + str(total))
答案 3 :(得分:0)
追踪您的bookcost()函数。 (提示:你确定它甚至到了“无效条目”部分吗?)