Reputation: 15
I'm in the process of learning coding and below we have a simple conversion between Fahrenheit and Celsius. I have created a loop in the check function that will call the convert function again if the user inputs something in the confirm array (I removed the arrays to save space).
From what I've been told it is better coding practice to have something like a do-while loop as opposed to calling functions within functions.
So I'm wondering what issues could arise with functions within functions that new people may not think of.
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()
Upvotes: 0
Views: 1546
Reputation: 44828
Well, you may get a stack overflow!
When you call a new function, some information about it is saved in memory. While it runs, its local variables are saved there as well. This structure is called a "stack frame". When you call a function within a function, the stack frames that describe the caller stay there since control must (or at least is expected to) return to the caller at some point (there are techniques like tail-call optimisation to prevent that, but they don't apply to most cases), so the deeper you go into recursion, the more stack frames are pushed onto the stack.
It may happen that you'll run out of memory solely because of the excessive amount of stack frames on the stack, which is known as a stack overflow, which causes your program to crash.
As an example, I once wrote a recursive function that kept crashing my Python interpreter because it was running in an environment which was very low on memory. Once I removed one single local variable from said function, it stopped crashing. As you can see, sometimes one local variable (that's copied over and over again in new stack frames) can make a difference.
Upvotes: 3