【发布时间】:2013-02-04 15:45:52
【问题描述】:
在我的计算机科学课上,我刚刚开始学习 Python 中的函数和参数。现在我的导师正在让我们学习参数传递。我没有输入我的程序的大量摘要,而是重新输入了下面的作业指南。
说明:在此程序中,用户必须选择输入费用、输入付款或在信用卡上显示余额。允许用户通过在键盘上输入代码来表明他们的选择。
使用以下函数名:
enterValue 用户输入一个值
addCharge 将传递给函数的值添加到余额中
addPayment 从余额中减去传递给函数的值
showBalance 显示信用卡当前余额
让用户为适当的操作输入以下代码:
“C”用于输入费用
“P”用于输入付款
“B”表示余额
在输入“Z”之前允许输入事务
程序
balance = 0
def enterValue ():
enter = input ("Enter a value.")
return enter
def addCharge (enter,balance):
balance = balance + enter
return balance
def addPayment (enter,balance):
balance = balance - enter
return balance
def showBalance ():
print "Your balance is... ", balance
transaction = raw_input ("Enter C for charges, P for payments, and B to show your balance. ")
enterValue ()
while transaction != "Z":
if transaction == "C":
balance = addCharge(enter,balance)
showBalance()
elif transaction == "P":
balance = addPayment (enter,balance)
showBalance()
elif transaction =="B":
balance = enterValue()
showBalance()
transaction = raw_input ("Enter C for charges, P for payments, and B to show your balance. ")
输出
Enter C for charges, P for payments, and B to show your balance. P
Traceback (most recent call last):
File "/Users/chrisblive/Downloads/Charge_Braverman-2.py", line 26, in <module>
balance = addPayment (enter,balance)
NameError: name 'enter' is not defined
(我的问题是我在enterValue() 中的值没有被定义。)
【问题讨论】:
-
您的问题是
enter未在函数外部定义。当您执行addPayment(enter, balance)时,您期望enter是什么? -
您也无需将 enter 传递给 enterValue,因为您正在覆盖它。
-
但是他们不输入,因为你从来没有调用 enterValue 函数。
-
哦……这么多东西。可能最简单的方法是在程序开始时调用
enter = enterValue()。或者只是说enter = input ("Enter a value."),但不在函数内部 -
哈。我不确定你的老师在这里想要完成什么。他要么希望你设置一个全局变量
enter,要么说enter = enterValue()。我的猜测是后者。如果你这样做。函数enterValue()只能是一行return raw_input('Enter a value.')。
标签: python function python-2.7 parameter-passing computer-science