I built a simple Python program to find if an input is a power of two or not. I have two functions,
play_again then runs and reruns
Here's my code:
num = int(raw_input('Input a number (type 0 to quit): '))
while y < x:
if x in z or x == 1:
elif x == 0:
num = int(raw_input('Input a number: '))
Is code like this acceptable among Python programmers or is there a better way to replicate what I am doing here?
Best How To :
One problem with this approach is that you will eventually run out of stack, because we have a pair of mutually recursive functions. Each call uses up memory in the stack, which is never recovered.
This isn't obvious with an interactive program since it will take a long time to create enough recursive calls, but if we speed things up:
RuntimeError: maximum recursion depth exceeded while calling a Python object
Some languages can do tail-call optimisation so this technique works fine - but in Python it's better to create a loop to "play again", unless you can be sure that there will only be a small call depth.