我有一个包含大约170行代码的程序,当前有5个函数(每个函数大约有35行代码)。每个函数都有两次用户输入(正如您所知,函数用于平方数或乘法等)。此外,输入变化相当大,所以我不认为我可以创建一个类来检查是否会有不良的用户输入(例如,在某些地方“c”应该是有效的,而在其他函数中它不应该,并且制作复杂的参数来看看“c”是否应该有效似乎是一种甚至更多效率低的方式。)
当我自己制作try
和exception
时,会导致程序的大小加倍,因为每个函数中基本上只有一半的代码检查无效的用户输入。我知道,一旦我开始更大的项目,用户输入在大多数情况下将不会是程序的一半,并且这样做是有道理的,但是对于类似于这样的情况,没有更有效的方法来执行此操作矿?
修改
def power():
select = input("Enter:\n'f' to find powers of numbers,\n'v' to view powers of "
"numbers (such as for study purposes),\n'x' to exit. "
"\nEnter what you would like to do: ").lower()
if select == "f":
while 1 == 1:
base = float(input("\nEnter base (enter '0' to exit): "))
if base == 0:
print()
break
print("\nPower:", pow(base, float(input("Enter exponent: "))))
if select == "v":
while 1 == 1:
until = int(input("\nEnter how many powers you would like to view "
"(enter '0' to exit): "))
if until == 0:
print()
break
exponent = float(input("Enter the exponent: "))
print("\n'^' indicates \"raised to the power of\"\n")
for number in range(until):
print(number, "^", exponent, ": ", pow(number, exponent),
sep = "")
if select == "x":
return
power()