python 2.7.3中的函数和参数

2024-05-28 20:08:24 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的计算机科学课上,我刚刚开始学习python中的函数和参数。现在我的老师让我们学习参数传递。我只是在下面重新输入了作业指南,而不是对我的课程进行一个大的总结。

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

使用以下函数名:

  • 输入值用户输入值

  • 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()中的值没有被定义。)


Tags: 函数用户forinputreturndef余额transaction
1条回答
网友
1楼 · 发布于 2024-05-28 20:08:24

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

例如:

###   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" ###

相关问题 更多 >

    热门问题