2014-11-04 106 views
0

下面是功能問題:修改變量從一個功能到另一個在Python

def ATM(): 
    global mode 
    pinNum = input('Please enter your 4 digit secret code: ') 
    userBalance = float(dict2[pinNum]) 
    while mode == 0: 
     if pinNum in dict1: 
      greet = input('Hello {}, please enter 1 to check your balance, 2 to make a withdrawal, 3 to make a deposit, or 4 to end your session: '.format(dict1[pinNum])) 
     if greet == '1': 
      balance(userBalance) 
     elif greet == '2': 
      withdraw(userBalance) 
     elif greet == '3': 
      deposit(userBalance) 
     elif greet == '4': 
      mode = 1 

def balance(userBalance): 
    print('Your current balance is {}.'.format(userBalance)) 


def deposit(userBalance): 
    amount = input('Please enter the amount you wish to be deposited: ') 
    userBalance += float(amount) 
    return userBalance 


def withdraw(userBalance): 
    amount = input('Please enter the amount you wish to withdraw" ') 
    if userBalance - float(amount) < 0: 
      print('You do not have sufficient funds.') 
    else: 
     userBalance -= float(amount) 

我無法作出調整,平衡,當我打電話存款或在ATM提取功能()。我想我可能不會在存取功能中正確返回數據。該程序模擬ATM參考,dict1和dict2定義在函數之外。任何幫助表示讚賞。

回答

1

我認爲這可以幫助你:

def ATM(): 
    global mode 
    pinNum = input('Please enter your 4 digit secret code: ') 
    userBalance = float(dict2[pinNum]) 
    actions = { 
     '1': balance, 
     '2': withdraw, 
     '3': deposit 
    } 
    while mode == 0: 
     if pinNum in dict1: 
      greet = input('Hello {}, please enter 1 to check your balance, 2 to make a withdrawal, 3 to make a deposit, or 4 to end your session: '.format(dict1[pinNum])) 
     if greet == '4': 
      break 
     else: 
      userBalance = actions.get(greet)(userBalance) or userBalance 

def balance(userBalance): 
    print('Your current balance is {}.'.format(userBalance)) 


def deposit(userBalance): 
    amount = input('Please enter the amount you wish to be deposited: ') 
    userBalance += float(amount) 
    return userBalance 


def withdraw(userBalance): 
    amount = input('Please enter the amount you wish to withdraw" ') 
    if userBalance - float(amount) < 0: 
      print('You do not have sufficient funds.') 
    else: 
     userBalance -= float(amount) 
    return userBalance 
+0

這個工作,非常感謝你。你介意解釋你對動作和.get()命令做了什麼?我從來沒有使用過,只是想了解它的功能。 – Droxbot 2014-11-04 01:54:57

+0

https://docs.python.org/2/library/stdtypes.html#dict.get 我使用它從一個鍵獲取值(它更安全) – yograterol 2014-11-04 01:56:23