官术网_书友最值得收藏!

1.2.2 實現1:不使用函數的單個賬戶

在代碼清單1-2顯示的最初版本中,只有一個賬戶。

代碼清單1-2:只包含一個賬戶的銀行模擬程序(文件: Bank1_OneAccount.py)

   # Non-OOP
   # Bank Version 1
   # Single account
 
? accountName = ‘Joe’
   accountBalance = 100
   accountPassword = ‘soup’
 
   while True:
     ? print()
       print(‘Press b to get the balance’)
       print(‘Press d to make a deposit’)
       print(‘Press w to make a withdrawal’)
       print(‘Press s to show the account’)
       print(‘Press q to quit’)
       print()
 
       action = input(‘What do you want to do? ‘)
       action = action.lower() # force lowercase
       action = action[0] # just use first letter
       print()
 
       if action == ‘b’:
           print(‘Get Balance:’)
           userPassword = input(‘Please enter the password: ‘)
           if userPassword != accountPassword:
               print(‘Incorrect password’)
           else:
               print(‘Your balance is:’, accountBalance)
 
       elif action == ‘d’:
           print(‘Deposit:’)
           userDepositAmount = input(‘Please enter amount to deposit: ‘)
           userDepositAmount = int(userDepositAmount)
           userPassword = input(‘Please enter the password: ‘)
 
           if userDepositAmount < 0:
                print(‘You cannot deposit a negative amount!’)
 
           elif userPassword != accountPassword:
               print(‘Incorrect password’)
 
           else: # OK
               accountBalance = accountBalance + userDepositAmount
               print(‘Your new balance is:’, accountBalance)
 
       elif action == ‘s’: # show
           print(‘Show:’)
           print(‘       Name’, accountName)
           print(‘       Balance:’, accountBalance)
           print(‘       Password:’, accountPassword)
           print()
 
       elif action == ‘q’:
           break
 
       elif action == ‘w’:
           print(‘Withdraw:’)
 
           userWithdrawAmount = input(‘Please enter the amount to withdraw: ‘)
           userWithdrawAmount = int(userWithdrawAmount)
           userPassword = input(‘Please enter the password: ‘)
 
           if userWithdrawAmount < 0:
               print(‘You cannot withdraw a negative amount’)
 
           elif userPassword != accountPassword:
               print(‘Incorrect password for this account’)
 
           elif userWithdrawAmount > accountBalance:
               print(‘You cannot withdraw more than you have in your account’)
 
           else: #OK
               accountBalance = accountBalance - userWithdrawAmount
               print(‘Your new balance is:’, accountBalance)
 
   print(‘Done’)

程序首先初始化了3個變量,用于代表一個賬戶的數據(?)。然后,顯示了一個菜單,用于選擇操作(?)。程序的主代碼直接操作全局賬戶變量。

在本例中,所有操作都在主代碼級別;代碼中沒有使用函數。程序可以正確運行,但看起來有點長。為了使很長的程序變得更加清晰,通常采用的方法是將相關代碼放到函數中,然后調用那些函數。我們在銀行程序的下一個實現中將探討這種方法。

主站蜘蛛池模板: 无棣县| 黄梅县| 兴业县| 墨脱县| 江孜县| 新蔡县| 澄迈县| 濉溪县| 洛扎县| 苏尼特左旗| 旌德县| 枞阳县| 根河市| 佛坪县| 宿迁市| 宾川县| 潮州市| 灌南县| 永登县| 岳阳市| 永靖县| 西峡县| 孟连| 原平市| 嘉黎县| 房山区| 巨野县| 垫江县| 彭水| 于都县| 巩留县| 永丰县| 陆丰市| 甘德县| 龙海市| 亳州市| 汝南县| 建始县| 东阳市| 嵊泗县| 虎林市|