Home > Net >  Having inputs add onto each other in python
Having inputs add onto each other in python

Time:11-30

I am a beginner, and I was working on a simple credit program. I want it to work so every time I add an input of a number it gets stored in a variable that shows my total balance. The problem right now is that the program is only a one use program so the input i enter does not get saved into a variable so that when I enter another value it gets added onto a previous input. Code is below:

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)

CodePudding user response:

If you don't want your code to exit you can use the while loop.

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)

Please notice i also changed the variable Purchase to purchase. this is because in python the convention is lower case letters for variables.

You can read more about conventions here:

Python Conventions

Also if you want to read more about loops, you can have a look here: Python Loops

Good luck and welcome to python :)

CodePudding user response:

You'll need to introduce a while loop to keep it going. Try this:

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)

Note that this will keep it going indefinitely. You'll need to add logic for the user to input a command to exit. You can use something like:

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

Then:

if Purchase == 'Exit':
    exit()

CodePudding user response:

You can get user input infinitely if you use a while loop:

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)

A good exercise would be to add some logic to ensure purchases don't exceed the credit limit.

  • Related