- Python面向對象編程:構建游戲和GUI
- (美)艾維·卡爾布
- 456字
- 2023-06-29 17:17:45
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個變量,用于代表一個賬戶的數據(?)。然后,顯示了一個菜單,用于選擇操作(?)。程序的主代碼直接操作全局賬戶變量。
在本例中,所有操作都在主代碼級別;代碼中沒有使用函數。程序可以正確運行,但看起來有點長。為了使很長的程序變得更加清晰,通常采用的方法是將相關代碼放到函數中,然后調用那些函數。我們在銀行程序的下一個實現中將探討這種方法。
推薦閱讀
- Cocos2d Cross-Platform Game Development Cookbook(Second Edition)
- Mastering Entity Framework Core 2.0
- NativeScript for Angular Mobile Development
- 21天學通C++(第5版)
- Scratch·愛編程的藝術家
- BeagleBone Robotic Projects(Second Edition)
- Qlik Sense? Cookbook
- Python商務數據分析(微課版)
- 會當凌絕頂:Java開發修行實錄
- C++17 By Example
- 深入理解Kafka:核心設計與實踐原理
- HTML5 and CSS3:Building Responsive Websites
- Java基礎案例教程(第2版)
- 軟件自動化測試實戰解析:基于Python3編程語言
- Python量子計算實踐:基于Qiskit和IBM Quantum Experience平臺