我正在使用python代码创建一个ATM,我需要创建存款和取款函数,它们的行为与ATM一样。另外,存取款功能起作用。但是,当我先取款然后存款时,余额不会更新。同样的事情当我存款然后取款。
谢谢你,非常感谢你的帮助。

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()

如果我提取17英镑,余额将为583英镑。但是,当我存12时,余额变成612,这是错误的,应该是595。

最佳答案

你根本没有改变“平衡”变量!
您的代码应该类似于:

balance = withdraw()
balance = deposit()

但是你的代码还有很多其他的问题。
首先,你不应该做那么多的演员。您必须将用户输入一次转换为一个数字,然后使用该类型计算所有内容。
你使用的是浮点和整数。如果你想填充货币,你应该使用十进制(https://docs.python.org/2/library/decimal.html),因为浮点运算在某些特殊情况下是不精确的(你需要四舍五入),整数显然不提供浮点运算。
另外,您特殊的“while”用法不符合常见的编码标准,使您的代码难以阅读。最好编写一个函数来获取用户输入,并将其与drawing()和deposit()逻辑分开。
编辑:既然你看起来是个初学者,我将提供一个最低限度的工作解决方案。
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))

关于python - 在python中,当我取款然后存钱时如何更新余额?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55970682/

10-10 01:20
查看更多