我正在学习编码,下面我们在华氏和摄氏之间进行简单的转换。我在check函数中创建了一个循环,如果用户在confirm数组中输入了一些内容,我将再次调用convert函数(我删除了数组以节省空间)。
从我被告知的情况来看,更好的编码实践是使用do-while循环而不是在函数内调用函数。
所以我想知道新功能可能没有想到的功能中可能会出现什么问题。
def convert():
while True:
usrchoice = input("Would you like to change Cel or Far? :")
if usrchoice in Celsius:
usrcel = int(input("Input temp in Celc: "))
far = usrcel * (9.0/5.0) +32
print("that's " + str(far) + " degrees in Far")
break
elif usrchoice in Far:
usrfar = int(input("Input temp in Far: "))
cel = (usrfar - 32) / (9.0/5.0)
print("that's " + str(cel) + " degrees in Cel" )
break
else: print("Choose Cel or Far")
continue
def check():
while True:
dblchk = input("Would you like to make another conversion? ")
if dblchk in Confirm:
convert()
elif dblchk in Deny:
print("Conversion finished")
break
else: print("Please enter yes or no")
continue
convert()
check()
好吧,你可能会出现堆栈溢出!
当您调用新函数时,有关它的一些信息将保存在内存中。在运行时,它的局部变量也会保存在那里。该结构称为“堆栈帧”。当你在一个函数中调用一个函数时,描述调用者的堆栈帧会保留在那里,因为控制必须(或至少预期)在某个时刻返回给调用者(有一些技术,如尾调用优化来防止这种情况,但是它们不适用于大多数情况),因此进入递归的深度越大,堆栈帧就越多。
可能由于堆栈上堆栈帧过多而导致内存耗尽,这称为堆栈溢出,导致程序崩溃。
作为一个例子,我曾经写过一个递归函数,它不断崩溃我的Python解释器,因为它是在一个内存非常低的环境中运行的。一旦我从所述函数中删除了一个局部变量,它就会停止崩溃。正如您所看到的,有时一个局部变量(在新的堆栈帧中一次又一次地复制)可能会有所不同。