[英]Having inputs add onto each other in python
我是初學者,我正在研究一個簡單的信用計划。 我希望它能正常工作,所以每次我添加一個數字輸入時,它都會存儲在一個顯示我的總余額的變量中。 現在的問題是該程序只是一個一次性程序,因此我輸入的輸入不會保存到變量中,因此當我輸入另一個值時,它會被添加到先前的輸入中。 代碼如下:
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)
您需要引入一個 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()
編輯:
這是一個每次都保留余額的版本。 關鍵區別在於變量可以等於其先前值加上更改。 為了清楚起見,我重寫了一些內容。
credit_limit = 2000
current_balance = 0
while True:
print('Welcome to the Credit Card Company')
Purchase = int(input("How much was your purchase? "))
current_balance = current_balance + Purchase
print("Your account value right now: ", current_balance)
if current_balance == credit_limit:
print("You have reached your credit limit!", current_balance)
如果使用 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)
一個很好的練習是添加一些邏輯以確保購買不超過信用額度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.