在python中,当我取款然后存款时,如何更新余额?
我正在使用python代码创建一个ATM,我需要创建存款和取款函数,它们的行为就像ATM一样。另外,存款和取款功能也可以工作。但是,当我先取款再存款时,余额不会更新。存款和取款都是一样的 谢谢你,非常感谢你的帮助在python中,当我取款然后存款时,如何更新余额?,python,python-3.3,Python,Python 3.3,我正在使用python代码创建一个ATM,我需要创建存款和取款函数,它们的行为就像ATM一样。另外,存款和取款功能也可以工作。但是,当我先取款再存款时,余额不会更新。存款和取款都是一样的 谢谢你,非常感谢你的帮助 balance = 600 def withdraw(): # asks for withdrawal amount, withdraws amount from balance, returns the balance amount counter = 0 whi
balance = 600
def withdraw(): # asks for withdrawal amount, withdraws amount from balance, returns the balance amount
counter = 0
while counter <= 2:
while counter == 0:
withdraw = int(input("Enter the amount you want to withdraw: AED "))
counter = counter + 1
while ((int(balance) - int(withdraw)) < 0):
print("Error Amount not available in card.")
withdraw = int(input("Please enter the amount you want to withdraw again: AED "))
continue
while ((float(balance) - float(withdraw)) >= 0):
print("Amount left in your account: AED" + str(balance - withdraw))
return (balance - withdraw)
counter = counter + 1
def deposit():
counter = 0
while counter <= 2:
while counter == 0:
deposit = int(input("Enter amount to be deposited: "))
counter = counter + 1
while ((int(balance) + int(deposit)) >= 0):
print("Amount left in your account: AED" + str(balance + deposit))
return (balance + deposit)
counter = counter + 1
withdraw()
deposit()
余额=600
def draw():#请求提取金额,从余额中提取金额,返回余额金额
计数器=0
当计数器=0时):
打印(“账户剩余金额:AED”+str(余额-提取))
退货(余额-提取)
计数器=计数器+1
def存款():
计数器=0
当计数器=0时):
打印(“账户剩余金额:AED”+str(余额+存款))
退货(余额+押金)
计数器=计数器+1
撤回
存款()
如果我提取17,余额将为583。但是,当我存入12英镑时,余额变成了612英镑,这是错误的,应该是595英镑。你只是忘记保存新的余额,你只是把它打印出来
balance = 600
def withdraw(): # asks for withdrawal amount, withdraws amount from balance, returns the balance amount
while True:
withdraw = int(input("Enter amount to be withdrawn: "))
if withdraw > balance:
print("Error Amount not available in card.")
else:
new_balance = balance - withdraw
print("Amount left in your account: AED" + str(new_balance))
return (new_balance)
def deposit():
deposit = int(input("Enter amount to be deposited: "))
new_balance = balance + deposit
print("Amount left in your account: AED" + str(new_balance))
return (new_balance)
# This is the only place you HAVE to change for it to work
balance = withdraw()
balance = deposit()
虽然有点随意改变,但最重要的是,你应该保持新的平衡
我还建议在将整数转换为整数之前检查它是否为int,从而使整数转换更安全
draw\u string=输入(“输入要提取的金额:”)
尝试:
撤销int=int(撤销字符串)
这是真的吗
除值错误外:
打印(“无效输入”)
is_int=False
如果为_int==True:
您根本没有更改“余额”变量!
您的代码应该类似于:
balance = withdraw()
balance = deposit()
但是,您的代码还有许多其他问题。
首先,你不应该做那么多的演员。您必须将用户输入转换为一个数字,然后使用该类型计算所有内容。
您使用的是float和int。如果您想使用currency,您应该使用decimal(),因为在某些特殊情况下(您需要四舍五入),浮点运算不精确,而integer显然不提供浮点运算
此外,您的特殊“while”用法不符合常见的编码标准,使您的代码难以阅读。最好编写一个函数来获取用户输入,并将其与取款()和存款()逻辑分离
编辑:因为你似乎是一个初学者,我将提供一个最低限度的工作解决方案
import decimal
balance = 600
def get_user_input(action):
# Get user input and convert it to decimal type
return decimal.Decimal(input("Please enter amount to {} from your account: ".format(action)))
def withdraw():
amount = get_user_input("withdraw")
return balance - amount
def deposit():
amount = get_user_input("deposit")
return balance + amount
print("Your Balance is {} AED".format(balance))
balance = withdraw()
balance = deposit()
print("Your Balance is {} AED".format(balance))
我同意@Chetan Ranpariya的建议,您没有更改代码中两个函数的
余额变量。您可以使用表达式balance+=
、balance-=
或balance=balance+
等更改balance
变量
balance = 600
def withdraw(): # asks for withdrawal amount, withdraws amount from balance, returns the balance amount
counter = 0
while counter <= 2:
while counter == 0:
withdraw = int(input("Enter the amount you want to withdraw: AED "))
counter = counter + 1
while ((int(balance) - int(withdraw)) < 0):
print("Error Amount not available in card.")
withdraw = int(input("Please enter the amount you want to withdraw again: AED "))
continue
while ((float(balance) - float(withdraw)) >= 0):
print("Amount left in your account: AED" + str(balance - withdraw))
return (balance - withdraw)
counter = counter + 1
def deposit():
counter = 0
while counter <= 2:
while counter == 0:
deposit = int(input("Enter amount to be deposited: "))
counter = counter + 1
while ((int(balance) + int(deposit)) >= 0):
print("Amount left in your account: AED" + str(balance + deposit))
return (balance + deposit)
counter = counter + 1
balance = withdraw()
balance = deposit()
余额=600
def draw():#请求提取金额,从余额中提取金额,返回余额金额
计数器=0
当计数器=0时):
打印(“账户剩余金额:AED”+str(余额-提取))
退货(余额-提取)
计数器=计数器+1
def存款():
计数器=0
当计数器=0时):
打印(“账户剩余金额:AED”+str(余额+存款))
退货(余额+押金)
计数器=计数器+1
余额=支取()
余额=存款()
您没有更改余额
变量,您只返回添加或减少的存款
或取款
的值
请尝试更改代码,以便在返回新的余额之前将其保存。因此,不是:
print("Amount left in your account: AED" + str(balance - withdraw))
return (balance - withdraw)
尝试:
然后对存款
功能执行相同操作
您的新代码:
balance = 600
def withdraw(): # asks for withdrawal amount, withdraws amount from balance, returns the balance amount
counter = 0
while counter <= 2:
while counter == 0:
withdraw = int(input("Enter the amount you want to withdraw: AED "))
counter = counter + 1
while ((int(balance) - int(withdraw)) < 0):
print("Error Amount not available in card.")
withdraw = int(input("Please enter the amount you want to withdraw again: AED "))
continue
while ((float(balance) - float(withdraw)) >= 0):
balance = (balance - withdraw)
print("Amount left in your account: AED" + str(balance))
return balance
counter = counter + 1
def deposit():
counter = 0
while counter <= 2:
while counter == 0:
deposit = int(input("Enter amount to be deposited: "))
counter = counter + 1
while ((int(balance) + int(deposit)) >= 0):
balance = (balance + deposit)
print("Amount left in your account: AED" + str(balance))
return balance
counter = counter + 1
withdraw()
deposit()
余额=600
def draw():#请求提取金额,从余额中提取金额,返回余额金额
计数器=0
当计数器=0时):
余额=(余额-提取)
打印(“账户剩余金额:AED”+str(余额))
返回余额
计数器=计数器+1
def存款():
计数器=0
当计数器=0时):
余额=(余额+存款)
打印(“账户剩余金额:AED”+str(余额))
返回余额
计数器=计数器+1
撤回
存款()
在deposit()
和widthdraw()
函数中,您从未实际接触到保持平衡的变量,这就是为什么您看不到变化
您已经定义了变量balance,但您从未使用balance=balance-x
更新过该值。您仅使用str(余额+存款)
打印该数学运算的结果,该代码实际上不会改变您的余额
要更改平衡,您需要使用balance+=widthdraw
更新该全局变量。但如果将该代码放入代码中,则会出现以下错误:
UnboundLocalError:分配前引用的局部变量“balance”
这是因为为了从函数内部更新全局变量,需要使用global关键字,以便链接到全局变量
下面的代码现在可以工作了,下面是两行重要的代码:
balance -= withdraw
balance += deposit
这就是您实际修改balance变量中的值的方式,而不仅仅是查看数学运算的输出
balance = 600
def withdraw(): # asks for withdrawal amount, withdraws amount from balance, returns the balance amount
global balance
counter = 0
while counter <= 2:
while counter == 0:
withdraw = int(input("Enter the amount you want to withdraw: AED "))
counter = counter + 1
while ((int(balance) - int(withdraw)) < 0):
print("Error Amount not available in card.")
withdraw = int(input("Please enter the amount you want to withdraw again: AED "))
continue
while ((float(balance) - float(withdraw)) >= 0):
balance -= withdraw
print("Amount left in your account: AED " + str(balance))
return (balance)
counter = counter + 1
def deposit():
global balance
counter = 0
while counter <= 2:
while counter == 0:
deposit = int(input("Enter amount to be deposited: "))
counter = counter + 1
while ((int(balance) + int(deposit)) >= 0):
balance += deposit
print("Amount left in your account: AED" + str(balance))
return balance
counter = counter + 1
withdraw()
deposit()
让我们一点一点地看一遍
装饰师是这样的
def exit_on_input_cast_error(func):
def wrapper(arg):
try:
return func(arg)
except ValueError as ex:
print("Exiting, bye.")
exit()
return wrapper
这只是装饰器的语法。重要的部分是返回函数(arg)。这就是将被捕获的函数。因此,这个decorator只负责捕获ValueError异常,当您尝试转换int('
balance = 600
def withdraw(): # asks for withdrawal amount, withdraws amount from balance, returns the balance amount
counter = 0
while counter <= 2:
while counter == 0:
withdraw = int(input("Enter the amount you want to withdraw: AED "))
counter = counter + 1
while ((int(balance) - int(withdraw)) < 0):
print("Error Amount not available in card.")
withdraw = int(input("Please enter the amount you want to withdraw again: AED "))
continue
while ((float(balance) - float(withdraw)) >= 0):
tmp_balance -= withdraw
print("Amount left in your account: AED " + str(tmp_balance))
return tmp_balance
counter = counter + 1
def deposit():
counter = 0
while counter <= 2:
while counter == 0:
deposit = int(input("Enter amount to be deposited: "))
counter = counter + 1
while ((int(balance) + int(deposit)) >= 0):
tmp_balance += deposit
print("Amount left in your account: AED" + str(tmp_balance))
return tmp_balance
counter = counter + 1
balance = withdraw()
balance = deposit()
def exit_on_input_cast_error(func):
def wrapper(arg):
try:
return func(arg)
except ValueError as ex:
print("Exiting, bye.")
exit()
return wrapper
class ATM():
"""A simple atm machine"""
def __init__(self, balance):
self.cash_available = balance
@exit_on_input_cast_error
def withdraw(self):
'''Withdraws entered amount, until user exits'''
continue_withdraw = True
while continue_withdraw:
withdraw_amount = self._get_withdraw_input()
self.cash_available -= withdraw_amount
self.print_balance("left in")
withdraw_again = str(input("Would you like to withdraw another amount? (Y or N)"))
continue_withdraw = withdraw_again.lower() in ['1', 'y', 'yes']
self.print_bye()
@exit_on_input_cast_error
def _get_withdraw_input(self):
input_error = True
while input_error:
withdrawl = int(input("Enter the amount you want to withdraw (Press N to exit): AED "))
if (self.cash_available - withdrawl) < 0:
print("Error Amount not available in machine.")
input_error = True
elif (self.cash_available - withdrawl) > self.cash_available:
print("Error, you can't withdraw a negative amount.")
input_error = True
else:
input_error = False
return withdrawl
@exit_on_input_cast_error
def deposit(self):
input_error = True
while input_error:
depositing = int(input("Please enter the amount you want to deposit (Press N to exit): AED "))
if (self.cash_available + depositing) < self.cash_available:
print("You cannot deposit a negative amount.")
else:
input_error = False
self.cash_available += depositing
self.print_balance("now in")
self.print_bye()
def print_balance(self, custom_insert = 'in'):
print(f"Amount {custom_insert} your account: AED {self.cash_available}")
def print_bye(self):
print("Thank you for using our services today, bye.")
def exit_on_input_cast_error(func):
def wrapper(arg):
try:
return func(arg)
except ValueError as ex:
print("Exiting, bye.")
exit()
return wrapper
class ATM():
"""A simple atm machine"""
def __init__(self, balance):
self.cash_available = balance
@exit_on_input_cast_error
def _get_withdraw_input(self):
input_error = True
while input_error:
withdrawl = int(input("Enter the amount you want to withdraw (Press N to exit): AED "))
if (self.cash_available - withdrawl) < 0:
print("Error Amount not available in machine.")
input_error = True
elif (self.cash_available - withdrawl) > self.cash_available:
print("Error, you can't withdraw a negative amount.")
input_error = True
else:
input_error = False
return withdrawl
while there's an error do the following:
Get the user input and cast it as an int.
Make sure the amount user has introduced matches the following criteria:
It is not more than the cash available in the atm.
It is not a negative number.
withdrawl = int(input("Enter the amount you want to withdraw (Press N to exit): AED "))
@exit_on_input_cast_error
def withdraw(self):
'''Withdraws entered amount, until user exits'''
continue_withdraw = True
while continue_withdraw:
withdraw_amount = self._get_withdraw_input()
self.cash_available -= withdraw_amount
self.print_balance("left in")
withdraw_again = str(input("Would you like to withdraw another amount? (Y or N)"))
continue_withdraw = withdraw_again.lower() in ['1', 'y', 'yes']
self.print_bye()
while the user wants to withdraw:
Get the user input
Check that the withdraw action does not result in 0 or negative number.
Print the balance
Ask the user if they want to withdraw again.
def print_balance(self, custom_insert = 'in'):
print(f"Amount {custom_insert} your account: AED {self.cash_available}")
def print_bye(self):
print("Thank you for using our services today, bye.")
@exit_on_input_cast_error
def deposit(self):
input_error = True
while input_error:
depositing = int(input("Please enter the amount you want to deposit (Press N to exit): AED "))
if (self.cash_available + depositing) < self.cash_available:
print("You cannot deposit a negative amount.")
else:
input_error = False
self.cash_available += depositing
self.print_balance("now in")
self.print_bye()
atm_a = ATM(600)
atm_a.withdraw()
Enter the amount you want to withdraw (Press N to exit): AED 100
Amount left in your account: AED 500
Would you like to withdraw another amount? (Y or N)Y
Enter the amount you want to withdraw (Press N to exit): AED -1
Error, you can't withdraw a negative amount.
Enter the amount you want to withdraw (Press N to exit): AED 501
Error Amount not available in machine.
Enter the amount you want to withdraw (Press N to exit): AED 5
Amount left in your account: AED 495
Would you like to withdraw another amount? (Y or N)yes
Enter the amount you want to withdraw (Press N to exit): AED 5
Amount left in your account: AED 490
Would you like to withdraw another amount? (Y or N)no
Thank you for using our services today, bye.
atm_a = ATM(600)
atm_a.withdraw()
atm_a.deposit()
Enter the amount you want to withdraw (Press N to exit): AED 500
Amount left in your account: AED 100
Would you like to withdraw another amount? (Y or N)no
Thank you for using our services today, bye.
Please enter the amount you want to deposit (Press N to exit): AED -1
You cannot deposit a negative amount.
Please enter the amount you want to deposit (Press N to exit): AED 1000
Amount now in your account: AED 1100
Thank you for using our services today, bye.