将代码块分解为多种功能
问题描述:
我已经编写了一个简单的程序,用于计算给定折扣阈值和折扣百分比(如下所示)的项目的输入数量的总成本。将代码块分解为多种功能
#Initializing the variables
cost_per_item = 27 #Without discount
discount_percent = 27
discount_threshold = 20
#Get the quantity of item to be priced
n_items = int(input("How many items? "))
#Calculate the total cost
cost = n_items * cost_per_item #line 1
if n_items > discount_threshold: #line 2
cost = cost * (1 - discount_percent/100) #line 3
#Printing the results
print('{} items cost ${:.2f}'.format(n_items, cost))
的线条标出的#line 1至#行3我要投入到所谓的calculation_function以及具有调用程序的主要功能的独立的功能,所以像
def calculation_function(parameters):
def main():
#Call the main function to run the program
main()
所以该方案的总体目标需要相同,我只想通过将其提取到功能中来改进其设计。道歉,我的解决方案应该看起来像样的模板是非常基本的,我从来没有做过任何功能提取。
答
在任何语言中提取函数都非常简单。步骤如下:
- 写一个函数名和空代码块,就像你在你的问题中做的一样。确保传递所需的变量,但常量可能是全局的或在提取的函数中定义的。
- 将代码块从原始位置复制到功能块的内部
- 将代码块过去的功能调用。
- 如果您的函数返回稍后使用的值,请确保将该值捕获到调用作用域中的变量中。
Python使用缩进来识别块,所以我们只是把我们想要提取的代码放在def语句和缩进下。
在你的情况,这会看起来像这样:
def calculation_function(n_items):
# Initializing the constants inside extracted function
# since they don't change, they don't need to be parameters.
cost_per_item = 27 #Without discount
discount_percent = 27
discount_threshold = 20
#Calculate the total cost
cost = n_items * cost_per_item #line 1
if n_items > discount_threshold: #line 2
cost = cost * (1 - discount_percent/100) #line 3
return cost
def main():
# Get the quantity of item to be priced
n_items = int(input("How many items? "))
# call extracted function and store returned value in variable
cost = calculation_function(n_items)
# Printing the results
print('{} items cost ${:.2f}'.format(n_items, cost))
#Call the main function to run the program
main()
答
TheAtomicOption这里有一些很好的代码。在这个只有一个函数的小程序中,我不会定义主函数,然后在下一行中调用它。然而,在一个更大的计划中,我会重新考虑这一立场。您的要求确实要求提供,所以我会说这是对的。
请记住,您的变量可能不像您的代码所指示的那样静态。除非他们永远都是那些价值观,否则我会建议将他们视为投入。
当我在你的答案中运行代码时,出现一个错误,提示'cost'没有在print('{} items cost $ {:. 2f}')的行中定义。format(n_items,cost) )',任何想法是什么导致这个问题?感谢您的回答,真的有帮助 – UbermenschSpecimen
编辑的代码应该可以工作。如果您在发布时几分钟内复制了我的代码,请尝试使用当前代码。 错误是由于在计算之前没有'cost =',这是第4步:确保我们在原始范围中需要的结果值被返回。 – TheAtomicOption