如何在python中识别功能并模块化代码?

时间:2018-12-27 07:03:41

标签: python function modularity

编写以下程序来在银行中执行不同的操作。 如何识别可以编写的功能并使代码模块化?

我还需要将适当的代码分组到已识别的函数中。

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")

另外的解释将帮助我学习。

1 个答案:

答案 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")