我一直想知道如何清理代码以使我的代码更容易阅读,以便其他人查看我的代码。我对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