我正在努力学习如何创建函数。如何将此代码更改为多个函数?你知道吗
purchase = input('Enter the amount of purchase: ')
statetaxes = purchase * 0.05
countytaxes = purchase * 0.025
totaltaxes = (statetaxes + countytaxes)
totalPurchase = (purchase + totaltaxes)
print('The amount of purchase is $'), format(purchase, ',.2f')
print('State tax: $'), format(statetaxes, ',.2f')
print('County tax: $'), format(countytaxes, ',.2f')
print('Total tax: $'), format(totaltaxes, ',.2f')
print('Total: $'), format(totalPurchase, ',.2f')
会是这样的吗:
def main():
purchase = get_purchase
statetaxes = get_state
countytaxes = get_county
totaltaxes = statetaxes + countytaxes
totalPurchase = totaltaxes + purchase
print('The amount of purchase is $', purchase)
print('State tax: ', statetaxes)
print('County tax: ', countytaxes)
print('Total tax: ', totaltaxes)
print('Total: $'. totalPurchase)
def get_purchase():
purchase = float(input('Please enter the amount of purchase')
return purchase
def get_state():
state = purchase * 0.05
return statetaxes
def get_county():
countytaxes = purchase * 0.025
return countytaxes
main()
是这样吗?如果不是,我哪里做错了?你知道吗
我在没有python解释器的情况下这样做,因为我现在正在使用平板电脑等待航班。你知道吗
编辑:我要做的是把顶层程序分成多个函数。当我输入此代码时:
def get_purchase():
return float(input('Please enter the amount of purchase '))
def get_state():
return purchase * 0.05
def get_county():
return purchase * 0.025
def main():
purchase = get_purchase()
statetaxes = get_state()
countytaxes = get_county()
totaltaxes = statetaxes + countytaxes
totalPurchase = totaltaxes + purchase
print('The amount of purchase is $', purchase)
print('State tax: ', statetaxes)
print('County tax: ', countytaxes)
print('Total tax: ', totaltaxes)
print('Total: $'. totalPurchase)
main()
我得到这个错误:
Please enter the amount of purchase 5000
Traceback (most recent call last):
File "salestax.py", line 49, in <module>
main()
File "salestax.py", line 38, in main
statetaxes = get_state()
File "salestax.py", line 27, in get_state
return purchase * 0.05
NameError: name 'purchase' is not defined
我现在正在上飞机,但会在中途停留时再检查一下,看看我做错了什么。你知道吗
代码审查:
将main()代码移到底部。你知道吗
所以我们把main()移到了底部。你知道吗
最后,在模块的底部,不要只调用
main()
,使用常见的Python习惯用法:如果导入模块,它会阻止代码执行main()。导入模块时,其
__name__
不再与'__main__'
相关:What does if __name__ == "__main__": do?这个答案跟在您修改代码之后,现在得到了一个运行时异常。你知道吗
函数def
get_state()
和get_county()
都引用了名为purchase
的变量,该变量不在函数的作用域中。你知道吗您应该将
purchase
传递到每个函数中,如下所示:还有其他方法可以做到这一点,例如基于类的方法,但是正如您所说的,您正在学习函数,这可能是一种方法。你知道吗
您需要通过添加左/右括号来调用函数:
在
get_state()
中有state
和statetaxes
变量—您只想使用其中的一个。你知道吗另外,作为mhawke mentioned,需要使
get_state
和get_county
接受purchase
参数,并在调用这些函数时将purchase从main传递给它们。你知道吗除此之外,您的函数似乎正确地分隔了逻辑操作。你知道吗
相关问题 更多 >
编程相关推荐