python 2.7.3中的函数和参数

问题描述 投票:4回答:1

在我的计算机科学课上,我刚开始学习python中的函数和参数。现在我的导师正在让我们学习参数传递。我没有输入我的程序的大量摘要,而是重新输入了下面的分配指南。

说明:在此计划中,用户必须选择输入费用,输入付款或在信用卡上显示余额。允许用户通过在键盘上输入代码来指示他们的选择。

使用以下函数名称:

  • enterValue用户输入一个值
  • addCharge传递给函数的值被添加到余额中
  • addPayment从天平中减去传递给函数的值
  • showBalance显示信用卡上的当前余额

让用户为相应的操作输入以下代码:

  • 进入收费的“C”
  • 用于输入付款的“P”
  • “B”表示余额
  • 允许输入事务,直到输入“Z”

Program

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. ") 

Output

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()里面的价值没有定义。)

python function python-2.7 parameter-passing computer-science
1个回答
0
投票

练习的主要目的是了解传递函数的参数。所以只需将函数中所有需要的变量传递给它!大概你可以说所有函数都有自己的命名空间,如果你想在其中使用另一个级别的值,你必须将它作为参数传递,如果你想在较低级别重用它,则返回它。

例如:

###   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" ###
© www.soinside.com 2019 - 2024. All rights reserved.