[英]How do I print the actions done by previous functions using for loops?
作為一項作業,我正在用 python 制作一個簡單的界面,它可以顯示余額,添加到該余額,從該余額中取出資金,檢查利率,然后最后檢查之前完成的三個操作。 這將是選擇 == 5。那么我在底部定義中寫什么才能這樣做?
usd = 500
def main():
print("""
1. Balance
2. Add
3. Retrieve
4. Interest
5. Last Changes
""")
choice = int(input("Choose: "))
if choice == 1:
global usd
balance()
elif choice == 2:
add()
elif choice == 3:
retrieve()
elif choice == 4:
interest()
elif choice == 5:
changes()
def balance():
global usd
print("Balance: ", round((usd),2))
main()
def add():
global usd
amount = int(input("How much do you want to add? "))
usd = amount + usd
print("New balance = ", round((usd),2))
main()
def retrieve():
global usd
amount = int(input("How much do you want to retrieve: "))
usd = usd - amount
print("New balance = ", round((usd),2))
main()
def interest():
global usd
if usd<=1000000:
usd = ((usd/100)*101)
print("New balance: ", round(((usd/100)*101), 2))
elif usd>=1000000:
usd = ((usd/100)*102)
print("New balance: ", round(((usd/100)*102), 2))
main()
def changes():
main()
main()
所需的輸出看起來有點像這樣;
Choose: 5
+6105
-500000
+1110000
聽起來您想記錄以前的操作。 您可以通過創建一個列表並在每次完成操作時附加一個新條目來完成此操作。 然后您的更改功能可以打印出列表中的最后 3 個項目。
您可以將列表設為全局並以與訪問usd
相同的方式訪問它。
您也可以在 main 中創建列表並將其作為參數傳遞給更改。 如果你決定這樣做,你可以讓每個函數返回它們的日志,這樣你就可以將它附加到 main 中的列表中。
例如(僅使用 add 函數說明)
使用全局變量(這是不好的做法,但更短):
usd = 500
log = []
def add():
global usd
amount = int(input("How much do you want to add? "))
usd = amount + usd
print("New balance = ", round((usd),2))
log.append(f"+{amount}") # add change to log
main()
def changes():
# print last 3 items in log
for change in log[-3:]:
print(change)
main()
或者更典型的方式,使用循環(沒有全局變量)
usd = 500
def main():
log = []
choice = 0
while choice != 6:
print("""
1. Balance
2. Add
3. Retrieve
4. Interest
5. Last Changes
6. Quit
""")
choice = int(input("Choose: "))
if choice == 1:
balance()
elif choice == 2:
log.append(add()) # add change to log
elif choice == 3:
log.append(retrieve()) # add change to log
elif choice == 4:
interest()
elif choice == 5:
changes(log)
def add():
global usd
amount = int(input("How much do you want to add? "))
usd = amount + usd
print("New balance = ", round((usd),2))
return f"+{amount}"
def changes(log):
# print last 3 items in log
for change in log[-3:]:
print(change)
main()
這種方法的一個潛在問題是因為您無限期地將項目添加到日志列表中,理論上您最終可能會耗盡計算機上的內存。 為了補救,只要列表的長度大於 3,您就可以從列表中刪除額外的日志。
列表文檔: https : //docs.python.org/3/tutorial/datastructures.html
全局變量通常是不好的做法,因此最好避免使 usd 成為全局變量,但我將把它留給你
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.