我一直在想,如何清理代码,使我的代码更容易,更可读的其他人审查我的代码。我对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(OorientedObjectp程序设计)。有时您的代码会非常简单,不需要使用类。这个范例取决于您想要构建的项目类型。如果您使用
imperative programmation
,那么最佳实践就是在您正在做的事情中使用函数。如果您想改进代码,以下是一些提示:max()
函数来重写其他函数。你知道吗请随时更新这个答案与其他良好的编程模式!你知道吗
相关问题 更多 >
编程相关推荐