【问题标题】:Having inputs add onto each other in python让输入在 python 中相互添加
【发布时间】:2022-11-30 02:28:34
【问题描述】:

我是初学者,我正在研究一个简单的信用计划。我希望它能正常工作,所以每次我添加一个数字输入时,它都会存储在一个显示我的总余额的变量中。现在的问题是该程序只是一个一次性程序,因此我输入的输入不会保存到变量中,因此当我输入另一个值时,它会被添加到先前的输入中。代码如下:

Purchase = int(input("How much was your purchase? "))


credit_balance = 0

credit_limit = 2000


Total = credit_balance + Purchase
    
print("Your account value right now: ", Total)


if Total == credit_limit:
    print("You have reached your credit limit!", Total)

【问题讨论】:

    标签: python


    【解决方案1】:

    如果使用 while 循环,则可以无限地获取用户输入:

    credit_balance = 0
    credit_limit = 2000
    
    while true:
        purchase = int(input("How much was your purchase? "))
        credit_balance += purchase  # add purchase to credit_balance
        
        print("Your account value right now: ", credit_balance)
        
        if credit_balance >= credit_limit:
            print("You have reached/exceeded your credit limit!", Total)
    

    一个很好的练习是添加一些逻辑以确保购买不超过信用额度。

    【讨论】:

      【解决方案2】:

      如果您不希望您的代码退出,您可以使用 while 循环。

      credit_balance = 0
      credit_limit = 2000
      
      while True:
          purchase = int(input("How much was your purchase? "))
          Total = credit_balance + purchase
          print("Your account value right now: ", Total)
          if Total == credit_limit:
              print("You have reached your credit limit!", Total)

      请注意,我还将变量 Purchase 更改为 purchase。 这是因为在 python 中,变量的约定是小写字母。

      您可以在此处阅读有关约定的更多信息:

      Python Conventions

      另外,如果你想了解更多关于循环的信息,你可以在这里看看: Python Loops

      祝你好运,欢迎使用 python :)

      【讨论】:

        【解决方案3】:

        您需要引入一个 while 循环来让它继续运行。尝试这个:

        credit_limit = 2000
        credit_balance = 0
        
        while True:
        
            print('Welcome to the Credit Card Company')
            Purchase = int(input("How much was your purchase? "))
            Total = credit_balance + Purchase
        
            print("Your account value right now: ", Total)
        
            if Total >= credit_limit:
                print("You have reached your credit limit!", Total)
        

        请注意,这将使它无限期地继续下去。您需要为用户添加逻辑以输入退出命令。你可以使用类似的东西:

            print('Welcome to the Credit Card Company')
            Purchase = int(input("How much was your purchase? Or type Exit to exit."))
        

        然后:

        if Purchase == 'Exit':
            exit()
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-06-28
          • 2016-01-14
          • 2022-01-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多