-3

我一直想知道如何清理代码以使我的代码更容易阅读,以便其他人查看我的代码。我对python相当陌生,所以我把所有东西都写成函数而不是使用类。我应该使用更多的类来更好地理解python吗?我知道如果代码有效,那么您执行它的方式并不重要,但我只想学习如何减少我的代码行。

def paymentData():
    calculateTotal = {}
    remainingAmount = []
    balance = int(raw_input('What is the balance of your bank account? \n'))
    amount = int(raw_input('What is the amount you would like to subtract? \n'))

    calculateTotal[balance]=amount

    total = balance - amount
    print('your total is: ' + str(total))

    remainingAmount.append(total)
    while True:
        choice = raw_input('To continue press "Enter" or type "q" to exit (For options type "o"). \n')
        if choice == '':
            clearScreen()
            paymentData()
            break
        elif choice.lower() == 'q':
            clearScreen()
            menuBudget()
            break
        elif choice.lower() == 'o':
            return calculateTotal, remainingAmount
            clearScreen()
            options_menu()
            break
        else:
            print('Invalid value.')
            continue

这是我的一个程序中的一个函数,它是一个预算程序,它采用balance用户输入的值并从值中减去它amount

此函数调用三个不同的函数,其中之一是clearScreen()清除终端:

def clearScreen(numlines=100):
    if os.name == "posix":
        os.system('clear')
    elif os.name in ("nt", "dos", "ce"):
        os.system('CLS')
    else:
        print('\n' * numlines)

options_menu()告诉你所有投入的结果的功能(这还没有完成,我也不打算完成这个项目)。

def options_menu():
    print('Do you want to see all of you total amounts?\n(Enter 1 for Yes, 2 for no.)')
    choice = int(raw_input())
    if choice == 1:
        time.sleep(3)

    elif choice == 2:
        menuBudget()
    else:
        print('Invalid Response.')

and the `menuBudget()` function that is the main menu for this script:

def menuBudget():                                                               # this is a menu for budget fast.
    menuRunning = True
    while menuRunning:
        print("""
        1. payment calculator.
        2. Comming Soon.
        3. Comming Soon.
        4. Exit/Quit.
        """)
        ans = input('Pick on the options above.\n')
        if ans == 1:
            clearScreen()
            paymentData()
            break
        elif ans == 2:
            print('Comming soon!')
            continue
        elif ans == 3:
            print('Comming soon!')
            continue
        elif ans == 4:
            break
        else:
            print('Unknown Option Seleted!')
            continue

4

1 回答 1

0

使用classes意味着使用OOP 面向对象程序)。有时您的代码会非常简单,不需要使用类。此范例取决于您要构建的项目类型。 如果你使用,最好的做法是使用你正在做的函数。如果你想改进你的代码,这里有一些提示:
imperative programmation

  • 使用有意义的变量名
  • 使用有意义的函数名
  • 将您的代码分类为多个文件,随意拥有所需的文件。尝试用意味深长的名字再次称呼他们。
  • 尽可能简化您的代码,并使用 python 库函数(这是有经验的)。例如,改用该max()函数来重写其他函数。
  • 向您的代码添加注释,使其即使在一个月后仍可重复使用

随意用其他好的编程模式更新这个答案!

于 2019-07-27T17:05:25.940 回答