[英]Functions and parameters in python 2.7.3
在我的計算機科學課上,我剛剛開始學習 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()
值沒有被定義。)
練習的主要任務是了解將參數傳遞給函數。 所以只需將函數中所有需要的變量傳遞給它! 大概你可以說所有函數都有自己的命名空間,如果你想在其中使用另一個級別的值,你必須將它作為參數傳遞,如果你想在較低級別重用它,則必須返回它。
例如:
### 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" ###
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.