首页 > 解决方案 > 如何使用 for 循环打印先前函数完成的操作?

问题描述

作为一项任务,我正在 python 中创建一个简单的界面,它可以显示余额、添加到该余额、从该余额中取出钱、检查利率,然后最后检查之前完成的三个操作。这将是选择 == 5。那么我应该在底部的 def 中写什么呢?

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

标签: pythonfor-loop

解决方案


听起来您想记录以前的操作。您可以通过创建一个列表并在每次操作完成时附加一个新条目来做到这一点。然后您的更改功能可以打印出列表中的最后 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 设为全局变量,但我将由您决定


推荐阅读