简体   繁体   English

如何获取变量以保持 Python 的运行总计?

[英]How to get a variable to keep a running total on Python?

I am trying to get this function take_input to add to the total whenever the function is run.每当运行 function 时,我都试图让这个 function take_input添加到总数中。 However, I am unable to get the variable daily_expense to accumulate when an expense is added a second time.但是,当第二次添加费用时,我无法让变量daily_expense累积。

def take_input():
    daily_expense = 0
    inp = int(input("How much did you spend?: "))
    daily_expense += inp
    print(f"Total expenses = {daily_expense}")

    while True:
        x = input("Add another expense? Y/N: ").lower()
        if x == "y":
            take_input()
        elif x == "n":
            break
        else:
            print("Please return a valid response")

def start_program():
    start = input("Add expense? Y/N: ").lower()
    if start == "y":
        take_input()

start_program()

This is the working code这是工作代码

def take_input(daily_expense:int):
   
    inp = int(input("How much did you spend?: "))
    daily_expense += inp
    print(f"Total expenses = {daily_expense}")

    while True:
        x = input("Add another expense? Y/N: ").lower()
        if x == "y":
            take_input(daily_expense)
        elif x == "n":
            break
        else:
            print("Please return a valid response")

def start_program():
    daily_expense = 0
    start = input("Add expense? Y/N: ").lower()
    if start == "y":
        take_input(daily_expense)

start_program()

You're currently defining daily_expense inside of the function;您当前正在 function 中定义 daily_expense; which means every time take_input() is called, you are resetting daily_expense to 0.这意味着每次调用 take_input() 时,您都会将 daily_expense 重置为 0。

Instead, you should either define daily_expense outside of the function so it will no longer be reset each time;相反,您应该在 function 之外定义 daily_expense,这样它就不会再每次都被重置; or you should accumulate it all within the loop and then print the final value, like so:或者你应该在循环中累积它,然后打印最终值,如下所示:

    def take_input():
        daily_expense = 0

        more_expenses = input("Add expense? Y/N: ").lower()

        while(more_expenses == "y"):
            inp = int(input("How much did you spend?: "))
            daily_expense += inp
            more_expenses = input("Add expense? Y/N: ").lower()

            if(more_expenses == "n"):
                break
            elif(more_expenses == "y"):
                continue
            else:
                print("Please return a valid response")
                more_expenses = input("Add expense? Y/N: ").lower()

        print(f"Total expenses = {daily_expense}")

    def start_program():
        take_input()

    start_program()

Edit: Additional notes:编辑:附加说明:

  • Every time this function is called, the value resets again and reaccumulates.每次调用此 function 时,该值都会再次重置并重新累加。

  • If you want to store this value in a database, then I recommend returning it and then using the returned value to update a database entry like so:如果您想将此值存储在数据库中,那么我建议返回它,然后使用返回的值来更新数据库条目,如下所示:

     def take_input(): daily_expense = 0 more_expenses = input("Add expense? Y/N: ").lower() while(more_expenses == "y"): inp = int(input("How much did you spend?: ")) daily_expense += inp more_expenses = input("Add expense? Y/N: ").lower() if(more_expenses == "n"): break elif(more_expenses == "y"): continue else: print("Please return a valid response") more_expenses = input("Add expense? Y/N: ").lower() print(f"Total expenses = {daily_expense}") return daily_expense def start_program(): save_this_number_to_db = take_input() # store save this number into database start_program()

Use a while loop instead of recursion to continually process user input.使用while循环而不是递归来持续处理用户输入。

def start_program():
    daily_expense = 0
    extra = ""
    while 1:
        x = input(f"Add {extra}expense? Y/N: ").lower()
        if x == "y":
            inp = int(input("How much did you spend?: "))
            daily_expense += inp
            print(f"Total expenses = {daily_expense}")
            extra = "another "
        elif x == "n":
            break
        else:
            print("Please return a valid response")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM