编写以下程序来在银行中执行不同的操作。 如何识别可以编写的功能并使代码模块化?
我还需要将适当的代码分组到已识别的函数中。
account_list=[1001,1002,1003,1004,1005]
balance_list=[2500,10000,7000,1500,500]
amount=1000
account_number=1003
transaction_type="Withdraw"
flag=None
if(transaction_type=="Withdraw"):
for index in range(0,len(account_list)):
if(account_list[index]==account_number):
flag=True
value=index
if(flag==True):
balance=balance_list[value]
new_balance=balance-amount
if(new_balance >= 500):
balance_list[value]=new_balance
print("Transaction completed successfully")
print("Balance Amount :", new_balance)
else:
print("Insufficient Balance")
else:
print("Invalid Account number")
elif(transaction_type=="Deposit"):
for index in range(0,len(account_list)):
if(account_list[index]==account_number):
flag=True
value=index
if(flag==True):
balance=balance_list[value]
new_balance=balance+amount
balance_list[value]=new_balance
print("Transaction completed successfully")
print("Balance Amount :", new_balance)
else:
print("Invalid Account number")
elif(transaction_type=="Balance Enquiry"):
for index in range(0,len(account_list)):
if(account_list[index]==account_number):
flag=True
value=index
if(flag==True):
balance=balance_list[value]
print(balance)
else:
print("Invalid Account number")
else:
print("Invalid Transaction Type")
另外的解释将帮助我学习。
答案 0 :(得分:0)
在进行编程时,功能的基本标准是程序的功能。对于您的示例,您可以使每个操作都发挥作用,而不是使用if
条件和相应代码。提现:
def withdraw(amount, account_list, account_number, balance_list):
'''
function description
'''
for index in range(0,len(account_list)):
if(account_list[index]==account_number):
flag=True
value=index
if(flag==True):
balance=balance_list[value]
new_balance=balance-amount
if(new_balance >= 500):
balance_list[value]=new_balance
print("Transaction completed successfully")
print("Balance Amount :", new_balance)
else:
print("Insufficient Balance")
else:
print("Invalid Account number")