我一直想知道如何清理代码以使我的代码更容易和其他人查看我的代码时更具可读性。我对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
使用的classes
装置使用的OOP(ø riented ö bject P rogrammation)。有时您的代码会非常简单,不需要使用类。此范例取决于您要构建的项目类型。
如果您使用imperative programmation
,最佳做法是按您的方式使用函数。如果你想改进你的代码,这里有一些提示:
max()
函数来重写其他函数。随意用其他好的编程模式更新这个答案!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句