Python中的ATM脚本

时间:2018-12-11 22:58:59

标签: python

我正在做一个上课的项目,无法弄清楚我要去哪里。该代码可在各部分中运行,但是当我一起运行所有代码时,它将在首次输入后立即关闭。

我认为我需要在某个地方调用函数-但是如何以及在哪里?

到目前为止,我的所有代码都带有注释。

import sys

#account balance 
account_balance = float(500.25)

##prints current account balance
def printbalance(): 
   print('Your current balance: %2g'% account_balance)

#for deposits 
def deposit(): 
  #user inputs amount to deposit
  deposit_amount = float(input()) 
  #sum of current balance plus deposit
  balance = account_balance + deposit_amount 
  # prints customer deposit amount and balance afterwards
  print('Deposit was $%.2f, current balance is $%2g' %(deposit_amount, 
balance))

#for withdrawals
def withdraw(): 
  #user inputs amount to withdraw
  withdraw_amount = float(input()) 
  #message to display if user attempts to withdraw more than they have
  if(withdraw_amount > account_balance):
    print('$%.2f is greater than your account balance of $%.2f\n' % 
(withdraw_amount, account_balance)) 
  else:
    #current balance minus withdrawal amount
    balance = account_balance - withdraw_amount 
    # prints customer withdrawal amount and balance afterwards
    print('Withdrawal amount was $%.2f, current balance is $%.2f' % 
(withdraw_amount, balance)) 

#system prompt asking the user what they would like to do
userchoice = input ('What would you like to do? D for Deposit, W for 
Withdraw, B for Balance\n')
if (userchoice == 'D'): #deposit
  print('How much would you like to deposit today?')
  deposit()
elif userchoice == 'W': #withdraw
  print ('How much would you like to withdraw today?')
elif userchoice == 'B': #balance
  printbalance()
else:
  print('Thank you for banking with us.')
  sys.exit()

1 个答案:

答案 0 :(得分:1)

此部分应为userchoice = input ('What would you like to do? D for Deposit, W for Withdraw, B for Balance\n')

不确定是否偶然缩进,但是python不喜欢这样。

另外,为您的代码提供建议。确保用户可以输入大写或小写字母,即使用户在输入字符串后放置空格也要确保它仍能抓取输入。  输入字符串字符W后,您的提款退出程序。 余额未获取正确的存款。 使用循环和条件保持循环,并询问用户何时退出。