Python 2.7.3中的函数和参数

4 投票
1 回答
7562 浏览
提问于 2025-04-17 16:24

在我的计算机科学课上,我刚开始学习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() 中的值没有被定义。)

1 个回答

-1

这个练习的主要目的是让你理解如何把参数传递给函数。所以,只需要把所有需要的变量传递给函数就可以了!

简单来说,可以认为每个函数都有自己的命名空间。如果你想在一个函数里使用其他地方的值,就必须把这个值作为参数传进去。如果你想在更低的层级再用到这个值,就需要把它返回。

举个例子:

###   Level "enterValue"   ###
def enterValue():
    return float(raw_input("Enter a value: "))
### End Level "enterValue" ###

###   Level "addCharge"   ###
def addCharge(enter, balance):
    balance = balance + enter
    return balance
### End Level "addCharge" ###

###   Level "showBalance"   ###
def showBalance(balance):
    print "Your balance is %f" % balance
### End Level "showBalance" ###

### Level "Mainlevel" ###
# This is where your program starts.
transaction = None
balance = 0.0
while transaction != "Z":
    transaction = raw_input("Enter C for charges, P for payments, and B to show your balance.\nEnter Z to exit: ").upper()

    if transaction == "C":
        enter = enterValue()
        balance = addCharge(enter, balance)
        showBalance(balance)
    elif transaction == "P":
        balance = addPayment(enter, balance)
        showBalance(balance)
    elif transaction == "B":
        showBalance(balance)
### End Level "Mainlevel" ###

撰写回答